在Django中的模型Form之后,如何保存一个字段commit = False? [英] How to save a field after commit=False with model Form in Django?

查看:112
本文介绍了在Django中的模型Form之后,如何保存一个字段commit = False?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型:

class Book(models.Model):
    name = models.CharField(max_length=100)
    alias = models.CharField(max_length=100)
    description = models.TextField()


    def __unicode__(self):
        return self.name

和forms.py中的ModelForm:

and a ModelForm in forms.py:

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

所以我试图在我的意见中做这样的事情:

So I'm trying to make something like this in my views:

def register_book(request):
if request.method == 'POST':
    formul = BookForm(request.POST)
    if formul.is_valid():
        new_book=formul.save(commit=False)
        new_book.alias='foo'
        new_book.save()
        return HttpResponseRedirect('/')

所以,我从htmlform中保存名称&描述,但我得到表单后,我需要保存的别名。但是不行。

So, I'm saving from a html "form" the name & description, but the alias I need to save after I get the form. But isn't working.

推荐答案

A ModelForm 将默认包括并验证模型的所有字段。如果您始终在视图中指定别名值,那么您不需要窗体中的别名字段你可以排除它:

A ModelForm will by default include and validate all fields of the model. If you always assign the alias value yourself in the view, then you don't need the alias field in the form and you can just exclude it:

class BookForm(ModelForm):

    class Meta:
        model = Book
        fields = ('name', 'description')
        # NOTE: you can also use excludes, but many consider it a bad practice

一如往常, Django文档可以告诉你更多关于它。

As always, Django docs can tell you more about it.

这篇关于在Django中的模型Form之后,如何保存一个字段commit = False?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆