Skip to content Skip to sidebar Skip to footer

Update Existing Post Called Using Dictionary , Using Ajax - Django

i'm trying to go update page . my models.py class MainGroup(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) main_type = models.CharField(max_length=

Solution 1:

You are mixing Django template tags with JavaScript in your template:

{% url "products:update_maingroup"id %}

This does not work because the template tag only gets evaluate once when the template is rendered, not when the JavaScript get executed.

You have to generate the URL in your view:

@login_requireddeflist_maingroup(request):
    lists = MainGroup.objects.all().order_by('-pk')
    data = []
    for i inlists:
        item = {
           'id':i.id,
           'admin':i.admin.username,
           'main_type':i.main_type,
           'date':i.date,
           'url': reverse("products:update_maingroup", kwargs={"id": i.id})
        }
        data.append(item)
    return JsonResponse({'data':data})

In your template:

...
'<buttonclass="btn btn-info bg-info"id="update"data-url='+data[i]["url"] + '><iclass="far fa-edit"></i></button>'+
...

There are a bunch of alternatives:

  • you can create a "template URL" with a dummy values and replace those

    var urlTemplate = "{% url "products:update_maingroup" 9999 %};
    var url = urlTemplate.replace("9999", id);
    
  • you can use a third-party library that provides URL reversal in JavaScript, e.g. django-js-reverse

Post a Comment for "Update Existing Post Called Using Dictionary , Using Ajax - Django"