简体   繁体   English

使用模型中的默认字段值保存Django ModelForm

[英]Save a Django ModelForm with default fields values in Model

I have a model FooModel with 2 fields with a default value ( default=xxx ) and marked as blank ( blank=True ), I created a ModelForm ( django.forms.ModelForm ) using FooModel and now I want to save it after submission, so in my view I have the following code: 我有一个带有2个字段的FooModel模型,其默认值( default=xxx )并标记为空白( blank=True ),我使用FooModel创建了一个ModelFormdjango.forms.ModelForm ),现在我想在提交后保存它,所以在我看来,我有以下代码:

f = FooForm(request.POST)

if f.is_valid():
  f.save()

the problem is that in this way I get a violation exception from the database because the fields that are not rendered in the html form are not automatically inherited in the FooForm instance as I would expect... how can I include fields from the original model which should not be displayed to the user? 问题在于,以这种方式,我从数据库中收到了一个违规异常,因为未以html形式呈现的字段不会像我期望的那样在FooForm实例中自动继承...如何包含原始模型中的字段哪些不应该显示给用户? (I don't want to render them as hidden fields!) (我不想将它们渲染为隐藏字段!)

So far I tried 2 approaches, both failed... 到目前为止,我尝试了2种方法,但均失败了...

  1. Specify instance in the FooForm constructor ( f = FooForm(request.POST, instance=FooModel()) ) 在FooForm构造函数中指定实例( f = FooForm(request.POST, instance=FooModel())

  2. Create an instance of a FooModel and manually assign the auto-generated values to the form's data: 创建FooModel的实例,然后将自动生成的值手动分配给表单的数据:

     i = FooModel() f.data.fieldA = i.fieldA f.data.fieldB = i.fieldB 

UPDATE: 更新:

by reading the django documentation more accurately, I solved in this way: 通过更准确地阅读django文档,我以这种方式解决了:

if f.is_valid():
  formModel = f.save(commit=False)
  foo = FooModel()
  formModel.fieldA = foo.fieldA
  formModel.fieldB = foo.fieldB
  formModel.save()

but, to be honest, I'm not satisfied... I would like to abstract out the addition of those fields... perhaps by using a custom decorator... something like: 但是,老实说,我不满意...我想抽象出这些字段的内容...也许通过使用自定义装饰器...类似:

f = MissingFieldsDecorator(FooForm(request.POST))
f.save()

how can I include fields from the original model which should not be displayed to the user? 如何包含原始模型中不应显示给用户的字段?

Answering this part of your question 回答问题的这一部分

class FooForm(ModelForm):
    class Meta:
        model = FooModel
        exclude = ('not_displayed_field',)

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

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