Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value for field in Django model

Suppose I have a model:

class SomeModel(models.Model):     id = models.AutoField(primary_key=True)     a = models.CharField(max_length=10)     b = models.CharField(max_length=7) 

Currently I am using the default admin to create/edit objects of this type. How do I remove the field b from the admin so that each object cannot be created with a value, and rather will receive a default value of 0000000?

like image 254
Yuval Adam Avatar asked Apr 16 '09 12:04

Yuval Adam


People also ask

How do I set default value in Django?

To set default form values with Django Python, we create the form instance with the default values in the constructor arguments. Or we can put the default values in the form definition. to create a JournalForm instance with the initial argument set to a dictionary with the initial form values.

Are Django fields nullable by default?

@AlfonsIngomar Incorrect, from the docs - docs.djangoproject.com/en/1.8/ref/models/fields/#null "If True, Django will store empty values as NULL in the database. Default is False."

What is required field in Django model?

required is often used to make the field optional that is the user would no longer be required to enter the data into that field and it will still be accepted. Let's check how to user required in a field using a project.


2 Answers

Set editable to False and default to your default value.

http://docs.djangoproject.com/en/stable/ref/models/fields/#editable

b = models.CharField(max_length=7, default='0000000', editable=False) 

Also, your id field is unnecessary. Django will add it automatically.

like image 94
FogleBird Avatar answered Oct 11 '22 23:10

FogleBird


You can set the default like this:

b = models.CharField(max_length=7,default="foobar") 

and then you can hide the field with your model's Admin class like this:

class SomeModelAdmin(admin.ModelAdmin):     exclude = ("b") 
like image 33
Andrew Hare Avatar answered Oct 11 '22 21:10

Andrew Hare