2009-10-29 65 views
3

考虑以下Django模型:Django的1.1形式,模式和隐藏领域

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表单中。

如果我使用“排除”从表格中省略该字段,那么我怎样才能使用表格将信息 保存在数据库中(这需要主机字段存在)?

回答

3

使用commit=False

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

你可以使用排除然后在表单“干净”的方法设置任何你想要的。

所以在您的形式:

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