Skip to content

Instantly share code, notes, and snippets.

@ibarovic
Created July 11, 2012 20:00
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save ibarovic/3092910 to your computer and use it in GitHub Desktop.
Save ibarovic/3092910 to your computer and use it in GitHub Desktop.
django crispy forms and django inline forms example (inlineformset_factory)
class AuthorForm(ModelForm):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.layout = Layout(
Field('name'),
)
super(AuthorForm, self).__init__(*args, **kwargs)
class Meta:
model = Author
class BookForm(ModelForm):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.layout = Layout(
Field('title'),
)
super(BookForm, self).__init__(*args, **kwargs)
class Meta:
model = Book
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
author = models.ForeignKey(Author)
title = models.CharField(max_length=100)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>TEST</title>
</head>
<body>
{% load crispy_forms_tags %}
<form method="post" action="" class="">
{% crispy form %}
{% crispy formset formset.form.helper %}
<input class="submit" type="submit" value="Submit data">
</form>
</body>
</html>
def manage_books(request, id_author=None):
if id_author is None:
author = Author()
BookInlineFormSet = inlineformset_factory(Author, Book, form=BookForm, extra=2, can_delete=False)
else:
author = Author.objects.get(pk=id_author)
BookInlineFormSet = inlineformset_factory(Author, Book, form=BookForm, extra=2, can_delete=True)
if request.method == "POST":
form = AuthorForm(request.POST, request.FILES, instance=author, prefix="main")
formset = BookInlineFormSet(request.POST, request.FILES, instance=author, prefix="nested")
if form.is_valid() and formset.is_valid():
form.save()
formset.save()
return redirect('/bookauthor/formset')
else:
form = AuthorForm(instance=author, prefix="main")
formset = BookInlineFormSet(instance=author, prefix="nested")
return render(request, "test_app/manage_books.html", {"form":form, "formset": formset})
@Aidan-Huang
Copy link

This is what I actually wanted.

@nspo
Copy link

nspo commented Apr 21, 2017

Awesome, thanks!

Edit: Seems like I cannot delete any books, though :-/ The delete checkbox just is not shown
Edit 2: Found a solution: http://stackoverflow.com/a/43548407/997151 :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment