【问题标题】:Django 1.1 forms, models and hiding fieldsDjango 1.1 表单、模型和隐藏字段
【发布时间】:2010-12-11 05:16:20
【问题描述】:

考虑以下 Django 模型:

class Host(models.Model):
    # This is the hostname only
    name = models.CharField(max_length=255)

class Url(models.Model):
    # The complete url
    url = models.CharField(max_length=255, db_index=True, unique=True)
    # A foreign key identifying the host of this url 
    # (e.g. for http://www.example.com/index.html it will
    # point to a record in Host containing 'www.example.com'
    host = models.ForeignKey(Host, db_index=True)

我也有这个表格:

class UrlForm(forms.ModelForm):
    class Meta:
        model = Urls

问题如下:我想自动计算主机字段的值, 所以我不希望它出现在网页中显示的 HTML 表单上。

如果我使用“排除”从表单中省略此字段,我该如何使用表单来保存信息 在数据库中(需要存在主机字段)?

【问题讨论】:

    标签: python django forms models


    【解决方案1】:

    使用commit=False:

    result = form.save(commit=False)
    result.host = calculate_the_host_from(result)
    result.save()
    

    【讨论】:

      【解决方案2】:

      您可以使用排除,然后在表单中“清理”方法设置您想要的任何内容。

      所以在你的形式中:

      class myform(models.ModelForm):
         class Meta:
             model=Urls
             exclude= ("field_name")
         def clean(self):
            self.cleaned_data["field_name"] = "whatever"
            return self.cleaned_data
      

      【讨论】:

        猜你喜欢
        • 2011-06-08
        • 2016-10-10
        • 2011-09-13
        • 2011-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-27
        • 2016-05-31
        相关资源
        最近更新 更多