artiest
artiest

Reputation: 592

update post via ajax django modelform

hi there i'm trying to update post via ajax request and django ModelForm i want to check validation form before submitting

class MainGroup(models.Model):
    admin = models.ForeignKey(User,on_delete=models.CASCADE)
    main_type = models.CharField(max_length=40,unique=True)
    date = models.DateTimeField(auto_now_add=True)

class MainGroupForm(forms.ModelForm):
    class Meta:
       model = MainGroup
       fields = ['main_type']

       error_messages = {
            'main_type':{
               'required':_('required to fill'),
               'unique':_('taken'),

           }
       }
       widgets = {
           'main_type':forms.TextInput(attrs={'class':'form-control','placeholder':_('main group')})
      }

my views.py

@login_required
def update_maingroup(request):  
    id = request.POST.get('eid')  
    object = get_object_or_404(MainGroup,id=id)
    form = MainGroupForm(instance=object)
    if request.method == 'POST':
        form = MainGroupForm(request.POST,instance=object)
        if form.is_valid():
           form.save(commit=True)
           return JsonResponse({'success':'success','data':form})
        else:
           return JsonResponse({'sucess':False,'error_msg':form.errors,'error_code':'invalid'})   

my templates

$("tbody").on("click",".btn-edit",function(){
        const id = $(this).attr('data-edit');
        const csr = $("input[name=csrfmiddlewaretoken]").val();
        mythis = this
        mydata = {
          eid:id,
          csrfmiddlewaretoken:csr
        }
        $.ajax({
          url:'{% url 'products:update_maingroup' %}',
          method:'POST',
          data:mydata,
          success:function(data){
            console.log(data) 

          },

        });

      });
        <table id="maingroupid" class="table table-bordered table-striped text-center">
        <thead>              
          <tr>
            <th>#</th>
            <th>admin</th>
            <th>main group</th>
            <th>date</th>
            <th>actions</th>

          </tr>
          </thead>
          <tbody id="tableData">
          
          {% for i in lists %}
            <tr>
              <td>{{i.id}}</td>
              <td>{{i.admin}}</td>
              <td>{{i.main_type}}</td>
              <td>{{i.date | date:'d-m-Y h:i A'}}</td>
              <td align="center"> 
                <button class="btn btn-info btn-edit bg-info" data-edit="{{i.id}}"><i class="far fa-edit"></i></button>
                <button class="btn btn-danger btn-del bg-danger" data-did="{{i.id}}" ><i class="far fa-trash"></i></button>
              </td>
            </tr>
            {% endfor %}
          </tbody>
          </tfoot>
        </table>

the console always returns

required to fill

i want to update it within this modal form but i'm not so good in js to do it

  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
          <h4 class="modal-title" id="myModalLabel"> update form
        </div>
        <form id="updateMain" role="form">
          <div class="card-body">
              <div class="form-group row">
                  <label for="mainGroup" class="col-sm-2 control-label">name group </label>
                  <div class="col-sm-10">
                    {{form.main_type | attr:'id:mainGroup'}}
                    <p id="main_error" class="alert alert-danger" aria-disabled="true" hidden></p>
                  </div>
                </div>
          </div>
          <!-- /.card-body -->
          <div class="card-footer">
              <button type="submit" class="btn btn-success">update</button>
            </div>
        </form>
      </div>
    </div>
  </div>

Upvotes: 1

Views: 333

Answers (1)

Daniel Hepper
Daniel Hepper

Reputation: 29967

Add a print(request.POST) to your view and you will see that you are not actually sending the value of your main_type field. You can add it like this:

const id = $(this).attr('data-edit');
const csr = $("input[name=csrfmiddlewaretoken]").val();
const main_type = $("input[name=main_type]").val();

mythis = this
mydata = {
    eid:id,
    csrfmiddlewaretoken:csr
    main_type:main_type
}

Upvotes: 1

Related Questions