Ajax and Django forms
I'd like to add Ajax to my admin form for editing a model. The model has a list field. I would like the Ajax to create a list of inputs with add and remove buttons, 开发者_运维问答automatically calling back to the server when the user clicks "add" or "remove".
What I'm stuck on is: how does the widget know what the backing model is? If it doesn't know, how can it update the values? (I would want to provide Urls like api/remove-list-item?pk=foo&item=bar
to the front end.)
This makes me think that it doesn't fit with the general Django framework philosophy to be doing this. Instead, perhaps I should be keeping the values locally and sending them through the same validation process as the rest of the data. But I'm a bit unsure of how to do this.
I am doing something similar to this (although not in an admin form). I'm not sure if it is a recommended way of doing things...but it does seem to work for me.
I have an action set on a html form in the template that calls a view which basically has the sole task of updating the data in the database and returning a "success" (or whatever I happen to want it to return).
On the template side of things I also use the jquery form plugin, which I use to update the div to show the new value.
Again, I'm not sure if this is the way others would recommend, but I do feel it seems to make sense....and it does seem to work just fine.
In urls.py, make a rule like:
(r'^api/remove-list-item/(?P<id>\d+)$', 'yourApp.views.remove'),
then in the yourApp.views have something like:
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')
You can then make queries like /api/remove-list-item/123
精彩评论