Ajax and Django Forms

I would like to add Ajax to my administrative form to edit the model. The model has a list box. I would like Ajax to create a list of inputs with add and remove buttons, automatically redirecting the server back when the user clicks "add" or "delete".

What I'm stuck with: how does the widget know what a support model is? If he does not know how can he update the values? (I would like to provide Urls, for example api/remove-list-item?pk=foo&item=bar, with the front end.)

This makes me think that this is not in line with the general philosophy of the Django framework. Instead, perhaps I should store the values โ€‹โ€‹locally and send them through the same validation process as the rest of the data. But I'm a little unsure how to do this.

+3
source share
2 answers

I am doing something similar to this (although not in the form of an administrator). I'm not sure if this is the recommended way to do something ... but it seems to work for me.

I have a set of actions in html form in a template that invokes a view that basically has the only task of updating the data in the database and returning โ€œsuccessโ€ (or whatever I want it to return).

On the template side, I also use the jquery form plugin , which I use to update the div to show the new value.

Again, I'm not sure others recommend it, but I feel it makes sense ... and it looks like everything is working fine.

0
source

In urls.py create a rule, for example:

(r'^api/remove-list-item/(?P<id>\d+)$', 'yourApp.views.remove'),

yourApp.views - :

from django.shortcuts import get_object_or_404, redirect

def remove(request, id):
  dbObj = get_object_or_404(YourModel, id=id)
  dbObj.active = False # Or whatever you want to do with the object
  dbObj.save()

  return redirect('some-view')

, /api/remove-list-item/123

0

Source: https://habr.com/ru/post/1785963/


All Articles