开发者

Django 1.1 forms, models and hiding fields

Consider the following Django models:

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

cla开发者_如何学编程ss 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)

I also have this form:

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

The problem is the following: I want to compute the value of the host field automatically, so I don't want it to appear on the HTML form displayed in the web page.

If I use 'exclude' to omit this field from the form, how can I then use the form to save information in the database (which requires the host field to be present) ?


Use commit=False:

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


You can use exclude and then in the forms "clean" method set whatever you want.

So in your form:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜