Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choices defined for model fields not being enforced?

So I've defined some fields as choices:

class MyModel(models.Model):
    # Text language.                                                                                 
    ENGLISH = 'eng'                                                                                   
    FRENCH  = 'fr'                                                                                   

    LANGUAGES_CHOICES = [                                                                            
        (ENGLISH, 'English'),                                                                        
        (FRENCH, 'French'),                                                                          
    ]                                                                                                

    language = models.CharField(                                                                     
            max_length=max(len(language) for language in LANGUAGES_CHOICES),                         
            choices=LANGUAGES_CHOICES,                                                               
            blank=False,                                                                             
            null=True)

However, I can do MyModel(language='hurhurhur').save() without any error or complaint. What am I missing?

like image 819
alexgolec Avatar asked Feb 21 '14 03:02

alexgolec


People also ask

How do you define choice fields in Django?

ChoiceField in Django Forms is a string field, for selecting a particular choice out of a list of available choices. It is used to implement State, Countries etc. like fields for which information is already defined and user has to choose one. It is used for taking text inputs from the user.

What are model fields?

Field models are used to calculate the values of field functions under given boundary and loading conditions. Field functions are physical quantities which depend on their geometrical location, such as temperature (a scalar field) or velocity (a vector field).

How do I create a choice in Django?

Choices can be any sequence object – not necessarily a list or tuple. The first element in each tuple is the actual value to be set on the model, and the second element is the human-readable name. Let us create a choices field with above semester in our django project named geeksforgeeks.


1 Answers

Django validates a model when you validate a modelform, or if you explicitly call modelinst.full_clean() Calling modelinst.save() doesn't validate.

like image 135
Nils Avatar answered Oct 02 '22 22:10

Nils