考虑以下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'从表单中省略此字段,我该如何使用该表单来保存信息 在数据库中(需要主机字段存在)?

有帮助吗?

解决方案

使用commit=False

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

其他提示

您可以使用排除,然后使用表单<!>“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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top