2

im using django and i wanna save list of data in my models "Detail_equipement" :

this is my models where i want to save data :

class Detail_equipement(models.Model):

    equipements=models.ForeignKey(Equipement,on_delete=models.CASCADE,default=True)
    interventions=models.ForeignKey(Intervention,on_delete=models.CASCADE)
    QTE = models.IntegerField()

models of foreignkey equipements:

class Equipement(models.Model):
    nom_equipement = models.CharField(max_length=60)
    qte_stock=models.IntegerField()
    prix_equipement = models.CharField(max_length=600)

and this is my template html when i send data to views :

{%  block content %}

<div class="row">
      <div class="col-md-6 grid-margin stretch-card">
                <div class="card">
                  <div class="card-body">
                    <h4 class="card-title">Ajouter Intervention</h4>
                    <form id="modal_form_signup" method="POST">
                        {% csrf_token %}
              
                          <div class="modal-content">
                              <div class="modal-header">
                                  <h5 class="modal-title">
                                      <i class="fa fa-lock mr-1"></i>Detail Equipement Utiliser
                                  </h5>
                                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                      <span>&times;</span>
                                  </button>
                              </div>
                              <div class="modal-body">
                                  <div class="form-row">
                                    {% for equipment in interv.equipements.all %}
              
                                      <div class="col-sm-6">
                                        <div class="form-group">
                                          <label for="modal_signup_firstname">Equipement</label>
                                          <div class="input-group">
                                              
                                              <input type="text" id="modal_signup_firstname" name="equipements" value="{{ equipment.nom_equipement }}" class="form-control" placeholder="Equipement" disabled/>
                                          </div>
                                      </div>
                                  
                                            
                                       
                                          
                                      </div>
                                      <div class="col-sm-4">
                                          <div class="form-group">
                                              <label for="modal_signup_lastname">QTE</label>
                                              <div class="input-group">
                                                
                                                  <input type="text" id="modal_signup_lastname" name="qte" class="form-control" placeholder="QTE" />
                                              </div>
                                          </div>
                                      </div>
                                      {% endfor %}
                                  </div>
                                 
                              </div>
                              <div class="modal-footer">
                                  <button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button>
                                  <button type="submit" class="btn btn-primary">Confirmer</button>
                              </div>
                          </div>
                      </form>
            
</div>
</div>
{%  endblock content %}

enter image description here

im trying to use for loop to bring all data but it not working for me it show error

"GET /techniciens/terminer/7 HTTP/1.1" 200 13999

So Here is my function in views.py :

def terminer(request,pk):
        get_interv= Intervention.objects.get(id=pk)
        if request.method=='POST':
            equipements = request.POST.getlist('equipements')
            qte = request.POST.getlist('qte')
            for equip in equipements:
                for qt in qte:
                    d=Detail_equipement(equipements=Equipement.objects.get(id=equipements),interventions=get_interv,QTE=qte)
                    

        
        context = {
                    'interv':get_interv,
                    
                    }
        return render(request, 'techniciens/terminer_interv.html',context)
2
  • 1
    200 is not an error code! Commented Jun 24, 2020 at 21:22
  • hi ! owkay thanks for your answer but if you can help me ! how can i save list of data to my database models ? Commented Jun 24, 2020 at 21:25

1 Answer 1

1

It looks like you are using getlist instead of just get and are sending over simple strings, not lists of items. Based on your form, your view should probably look like this (assuming you have a single field):

def terminer(request,pk):
        get_interv= Intervention.objects.get(id=pk)
        if request.method=='POST' and request.is_ajax():
            equipements = request.POST.get('equipements')
            qte = request.POST.get('qte')
            # do something with equipements and qte

getlist works with form multi-selects and similar objects, like this:

    <select name="equipements" id="equipements" multiple>
{% for equipment in interv.equipements.all %} 
        <option value="{{equipment.id}}">{{equipment.nome}}</option>
{% endfor %}
      </select>

If you need to collect multiple variables for each entry, you could perhaps do it dynamically via JavaScript:

$("#mysubmitbutton").click(function(){
    {% for equipment in interv.equipments.all %}
       var equipment_{{equipment.id}} =  $("#equipment_type_{{equipment.id}}").val();
       var equipment_{{equipment.id}}_qty = $("#equipment_qty_{{equipment.id}}").val();
    {% endfor %}

    var equipments = [
      {% for equipment in interv.equipments.all %}
        { id: equipment_{{equipment.id}}, qty: equipment_{{equipment.id}}_qty,
      {% endfor %}
    ];
    var form_field1 = $("#field1").val();
    var csrfToken = $( "input[name='csrfmiddlewaretoken']");
//collect the rest of the form here
$.ajax({
    ContentType: 'application/json; charset=utf-8',
    dataType: 'json',
    type: 'POST',
    url: '{% url 'Detail_equipement' %}',
    data: { "equipments": equipments, 'form_field1': form_field1, ..., 'csrdmiddlewaretoken':csrftoken, })
               .done(function(data) {
                            if (data.result === true){
                                alert(data.message);
                           }
                       });
});

In your template:

 {% for equipment in interv.equipements.all %}
                  
                                          <div class="col-sm-6">
                                            <div class="form-group">
                                              <label for="modal_signup_firstname">Equipement</label>
                                              <div class="input-group">
                                                  
                                                  <input type="text" id="equipment_type_{{equipment.id}}" name="equipment_type_{{equipment.id}}" value="{{ equipment.nom_equipement }}" class="form-control" placeholder="Equipement" disabled/>
                                              </div>
                                          </div>
</div>
                                      <div class="col-sm-4">
                                          <div class="form-group">
                                              <label for="modal_signup_lastname">QTE</label>
                                              <div class="input-group">
                                                
                                                  <input type="text" id="equipment_{{equipment.id}}_qty" name="equipment_{{equipment.id}}_qty" class="form-control" placeholder="QTE" />
                                              </div>
                                          </div>
                                      </div>
    {% endfor %}

Then, in your view you should be able to use getlist:

def terminer(request,pk):
            get_interv= Intervention.objects.get(id=pk)
            data = {}
            if request.method=='POST' and request.is_ajax():
                equipements = request.POST.getlist('equipments')
                for e in equipements:
                   detail = Detail_equipement.objects.get_or_create(equipements__id=e['id'])
                   detail.QTE = e['qty']
                   detail.save()
             if request.is_ajax():
                return JsonResponse(data)
             else:
                context = {
                'interv':get_interv,
                
                }
                return render(request, 'techniciens/terminer_interv.html',context)

Also, default=True doesn't do anything in a ForeignKey field and you'll need to update your model to this for my code to work (or pass the interventions value in the POST data via ajax):

class Detail_equipement(models.Model):

    equipements=models.ForeignKey(Equipement,on_delete=models.CASCADE)
    interventions=models.ForeignKey(Intervention,on_delete=models.CASCADE, blank=True, null=True)
    QTE = models.IntegerField()

This may need some tweaking, as I can't see the rest of your code to be sure it will work. But hopefully it will get you started.

Sign up to request clarification or add additional context in comments.

12 Comments

You just get iterate over the equipment list, get the equipment object based on the id, and update and save it
Then use get_or_create (I updated my code to show it, but see my comment below for changes needed for it to work)
I updated my code to use get_or_create but in order to use my code, you'll either have to pass the Interventions data in the POST data or make Interventions blank=True and null=True in the model
The code I posted does that but you may have to modify it to work properly in your environment.
Without seeing the whole error I can't help. I'm sorry, but what I posted will work but you will have to experiment with it to learn it. There are other ways to do it, but they require a lot more code. You'll have to experiment.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.