Django ajax form, choicefields dependancy
models.py
class Book(models.Model开发者_如何学C):
title = models.CharField()
genre = models.ManyToManyField(Genre)
class Genre(models.Model):
name = models.Charfield()
class ReadBook(models.Model):
genre = models.ForeignKey(Genre)
books = models.ManyToManyField(Book)
Also I have one ModelForm:
class ReadBookForm(ModelForm):
class Meta:
model = ReadBook
template.html
<form action="/add_report/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
The purpose: By default to show a visitor only one field - genre. When he is with done this choice - show other fields from books model, related to selected genre.
inside form tag:
{{ form.genre }}
<div id="books"></div>
<input type="submit" value="Submit" disabled="yes" />
then in javascript (jQuery is great for this stuff):
$('#{{ form.genre.id }}').change(function(){
$('#books').load('{% url get_genre_books %}', {genre: $(this).value()})
});
you must create a view that will return a html that should be placed in this div:
def get_genre_books(request):
genre = get_object_or_404(pk=request.GET.get('genre', None))
# here render a template or something that shouls be multiple selector of the books)
resp = ", ".join(genre.book_set.values_list('title', flat=True))
return HttpResponse(resp)
and of course add this view to the urls.py.
One of many solutions :) didnt' test it (written only here, so maybe small bugs somewhere) :)
精彩评论