0

i want to make a button to update url. i called data from database using jquery-ajax

this is my views.py

def list_maingroup(request):
    lists = MainGroup.objects.all().order_by('-pk')
    data = []
    for i in lists:
        item = {
           'id':i.id,
           'admin':i.admin.username,
           'main_type':i.main_type,
           'date':i.date
        }
        data.append(item)
    return JsonResponse({'data':data})

def update_maingroup(request,id):
    obj = get_object_or_404(MainGroup,id=id)
    form = MainGroupForm(instance=obj)
    if request.is_ajax() and request.method == 'POST' and request.user.is_superuser:
        if form.is_valid():
            form = MainGroupForm(request.POST,instance=object)
            form.save()
            return JsonResponse({'success':'success'})
        else:
            return JsonResponse({'success':False,'error_msg':form.errors,'error_code':'invalid'})

    context = {'form':form,'obj':obj}
    return render(request,'update_maingroup.html',context)

my urls.py

path('maingroup/update/<int:id>',update_maingroup,name='update_maingroup'), 
path('list-main-group',list_maingroup,name='list-maingroup'),

my form + my model

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']

but it raise this error:

Reverse for 'update_maingroup' with no arguments not found. 1 pattern(s) tried: ['maingroup/update/(?P[0-9]+)$']

my templates

$.ajax({
    type:'GET',
    url:'/list-main-group',

    success:function(data){

      data = data.data
      spinnerBox.classList.add('non-visible')
      var k = '<tbody>'
      for(i = 0;i < data.length; i++){
        const date = new Date(data[i]["date"]).toLocaleString();
        const id = parseInt(data[i]['id'])
        // const url = '{% url "products:update_maingroup" %}'
        // const my_url = url + "/"+id
        
          k+= '<tr>';
          k+= '<td>' + data[i]['id'] + '</td>';
          k+= '<td>' + data[i]["admin"] + '</td>';
          k+= '<td>' + data[i]["main_type"] + '</td>';
          k+= '<td>' + date + '</td>';
          k+= '<td align="center">'+
            
            '<button class="btn btn-info bg-info"  id="update" data-url='+{% url "products:update_maingroup" id %}+ '><i class="far fa-edit"></i></button>'+
            ' <button class="btn btn-danger btn-del bg-danger" data-did='+parseInt(data[i]["id"])+"><i class='far fa-trash'></i></button>"+

              '</td>';               
          k+= '</tr>'
      }
      k+='</tbody>'
        
      tableBody.innerHTML = k   
          
      $('#maingroupid').dataTable({     
        "order": [[ 0, "desc" ]]
      });
    },
    // error:function(error){
    //   console.log(error)
    // }
   
  });

      <div class="card-body table-responsive" >
        <div id="spinner-box" class="spinner-border text-primary text-center" role="status">
        </div>
        <table id="maingroupid" class="table table-bordered table-striped text-center">
        <thead>              
          <tr>
            <th>#</th>
            <th>{% trans "admin" %}</th>
            <th>{% trans "name" %}</th>
            <th>{% trans "date" %}</th>
            <th>{% trans "options" %}</th>

          </tr>
          </thead>
          <tbody id="tableData">

          </tbody>
          </tfoot>
        </table>

      </div>

i know, i have to get the id from server, but i dont know where to get it

James Z
  • 12,209
  • 10
  • 24
  • 44
artiest
  • 554
  • 5
  • 20

1 Answers1

1

The error in your code is very subtle and I don't think that Django documentation is really pointing towards this enough.
When commenting out django template code, you absolutely need to use Django formatting. If you use regular formatting (eg. // in JavaScript or <!-- --> in HTML) the Django syntax will still be executed.

In your code you have the line:

        // const url = '{% url "products:update_maingroup" %}'

This url does not exist, as your update_maingroup url is defined to always be used with the additional parameter id.

I suggest either removing this line or using django formatting when commenting:

{# const url = '{% url "products:update_maingroup" %}' #}

Edit: Additional info about how to use the correct url from javaScript variables:
Please take a look at this question + answers.
Long story short: there is no real way to do this but people have found ways around it: Get javaScript variable into url tag.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Anna M.
  • 400
  • 2
  • 9
  • so where to put the update url into my js code ? and how to give id to the url ? – artiest Aug 10 '21 at 13:07
  • 1
    I have expanded my answer. The short answer is there is no real way to do it, only ways around it. And usually you would need to create a url that needs no parameters and use that as a dummy to then update the url. But you can read more about it in the linked answer. – Anna M. Aug 10 '21 at 13:16