Django ModelForm with foreign key

前端 未结 2 1986
醉梦人生
醉梦人生 2021-01-16 06:28

I\'m trying to create a ModelForm that updates a table with foreign keys. What I have seems to work, but I was hoping someone could tell me if there\'s a bette

相关标签:
2条回答
  • 2021-01-16 06:35

    The only thing that's wrong with this code is you are overriding the default behaviour of your model form. Change it to look like:

    class BookForm(ModelForm):
    
        class Meta:
            model = Book
            fields = ['title', 'author', 'genre']
    

    And let django handle with the definition of those. if you need to add labels or widgets, you can define them in the Meta class:

    class BookForm(ModelForm):
    
         class Meta:
             model = Book
             fields = ['title', 'author', 'genre']
             labels = {'title': 'Book title', }
    

    For example.

    0 讨论(0)
  • 2021-01-16 06:42

    I'm not really sure what you're asking here, or why you would want a queryset on Book.

    You haven't actually changed any of the defaults on any of the fields, so there is no need to redefine them: your form could be simply

    class BookForm(ModelForm):
        class Meta:
            model = Book
    

    and it would work exactly the same.

    0 讨论(0)
提交回复
热议问题