Django 1.1表单,模型和隐藏字段

时间:2009-10-29 11:48:41

标签: python django forms models

考虑以下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表单上。

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

2 个答案:

答案 0 :(得分:3)

使用commit=False

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

答案 1 :(得分:1)

你可以使用exclude然后在表单“clean”方法中设置你想要的任何内容。

所以在你的表格中:

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