简体   繁体   English

带有外键的 Django ModelForm

[英]Django ModelForm with foreign key

I'm trying to create a ModelForm that updates a table with foreign keys.我正在尝试创建一个使用外键更新表的ModelForm What I have seems to work, but I was hoping someone could tell me if there's a better way to do this or if there's a problem with the way I'm doing it below.我所拥有的似乎有效,但我希望有人能告诉我是否有更好的方法来做到这一点,或者我在下面的做法是否有问题。

Is it correct to use the queryset on the Author and Genres table?AuthorGenres表上使用查询集是否正确? It feels like I should be using a queryset on the Book model, and relate the foreign key to those tables.感觉就像我应该在Book模型上使用查询集,并将外键与这些表相关联。

models.py : models.py

class Author(models.Model):
    name = models.CharField(max_length=200)
    
class Genre(models.Model):
    name = models.CharField(max_length=200)
    
class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey('Author')
    genre = models.ForeignKey('Genre')

forms.py : forms.py

class BookForm(ModelForm):
    title = forms.CharField(max_length=200)
    author = forms.ModelChoiceField(queryset=Author.objects.all())
    genre = forms.ModelChoiceField(queryset=Genre.objects.all())

    class Meta:
        model = Book
        fields = ['title', 'author', 'genre']

views.py : views.py

def add_book(request):
    if request.method == 'POST':
        form = BookForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect('/add/')
    else:
        form = BookForm()

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.让 Django 处理这些定义。 if you need to add labels or widgets, you can define them in the Meta class:如果需要添加标签或小部件,可以在 Meta 类中定义它们:

class BookForm(ModelForm):

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

For example.例如。

I'm not really sure what you're asking here, or why you would want a queryset on Book.我不太确定你在这里问什么,或者你为什么想要一个关于 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.它的工作原理完全相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM