开发者

Django Form based on multiple models

If I have two models in Django application like this:

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    author = models.ForeignKey(Author)
    title = models.CharField(max_length=100)

How can I create a single form that allows you add both an Author and a Book simultaneously. If the author exists in the system, I could simply display the book Form and link that to the author but it is very often that I need to allow my users to cre开发者_C百科ate the book and the author simultaneously.

How can I do this?

Thanks.


You can write a custom form, which will check if the author exists in the system use existing, if no, create new with provided name.

class CustomForm(forms.ModelForm):
    author = forms.CharField()

    def save(self, commit=True):
       author, created = Author.objects.get_or_create(name=self.cleaned_data['author'])

       instance = super(CustomForm,self).save(commit=commit)
       instance.author = author
       if commit:
          instance.save()
       return instance

    class Meta:
        model=Book

Not sure this code is working, but I suppose it can explain my idea.


You can create a view that handles multiple forms - see http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/ for an excellent example.

You'd have to ensure that the rendering of the form objects are done in the template with only one tag and one submit button.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜