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)

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 this: I want to automatically calculate the value of the host field, so I do not want it to be displayed in HTML form displayed on the web page.

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

+3
source share
2 answers

Use commit=False:

result = form.save(commit=False)
result.host = calculate_the_host_from(result)
result.save()
+3
source

You can use an exception, and then in the form of a "clean" method, set everything 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
+1

Source: https://habr.com/ru/post/1721386/


All Articles