views:

130

answers:

2

Consider the following Django models:

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)

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) ?

+1  A: 

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
Arkaitz Jimenez
+3  A: 

Use commit=False:

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