Skip to content

Instantly share code, notes, and snippets.

@Font77
Forked from ibarovic/forms.py
Created July 31, 2014 04:18
Show Gist options
  • Save Font77/442402d97171a8978ebf to your computer and use it in GitHub Desktop.
Save Font77/442402d97171a8978ebf to your computer and use it in GitHub Desktop.
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})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment