Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hidden field in Django Model

A while back I made a Model class. I made several ModelForms for it and it worked beautifully.

I recently had to add another optional (blank=True, null=True) field to it so we can store some relationship data between Users. It's essentially a referral system.

The problem is adding this new field has meant the referral field shows up where I haven't changed the ModelForms to exclude it. Normally this would just mean an extra 10 minutes going through and excluding them but in this case, due to project management politics out of my control, I only have control over the Models for this application.

Can I either:

  • Set the field to auto-exclude?
  • Set it so it renders as a hidden (acceptable if not perfect)?
like image 664
Oli Avatar asked Jan 18 '10 13:01

Oli


People also ask

How to hide a field in Django model?

Django: Hidden field in Django Model from the docs on Using a subset of fields on the form: Set editable=False on the model field. As a result, any form created from the model via ModelForm will not include that field.

How do I hide fields in Django admin?

In Django 1.8 exclude = ('fieldname',) does works with admin. ModelAdmin so one does not have to inherit from InlineModelAdmin anymore. Also works in Django 1.6.

How to use get and POST method in Django?

GET and POSTDjango's login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response. GET , by contrast, bundles the submitted data into a string, and uses this to compose a URL.

How do I delete a field in Django?

If you want to drop the data completely, you need to create a Django migration (using ./manage.py makemigrations preferably) that will remove those columns from the database.


2 Answers

If you have access to the template you could render it as a hidden field with the following code:

{{ form.field_name.as_hidden }} 

instead of the standard:

{{ form.field_name }} 
like image 74
Gregor Müllegger Avatar answered Sep 28 '22 00:09

Gregor Müllegger


from the docs on Using a subset of fields on the form:

Set editable=False on the model field. As a result, any form created from the model via ModelForm will not include that field.

like image 45
Ofri Raviv Avatar answered Sep 28 '22 00:09

Ofri Raviv