Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you create a non-empty CharField in Django?

I have a simple model which looks like this:

class Group(models.Model):     name = models.CharField(max_length = 100, blank=False) 

I would expect this to throw an integrity error, but it does not:

group = Group() # name is an empty string here group.save() 

How can I make sure that the name variable is set to something non-empty? I.e to make the database reject any attempts to save an empty string?

like image 666
Kristian Avatar asked Aug 04 '11 11:08

Kristian


People also ask

What is CharField in Django?

CharField is a string field, for small- to large-sized strings. It is like a string field in C/C+++. CharField is generally used for storing small strings like first name, last name, etc. To store larger text TextField is used. The default form widget for this field is TextInput.

What is difference between TextField and CharField in Django?

CharField has max_length of 255 characters while TextField can hold more than 255 characters. Use TextField when you have a large string as input. It is good to know that when the max_length parameter is passed into a TextField it passes the length validation to the TextArea widget.


1 Answers

another option that doesn't require you to manually call clean is to use this:

name = models.CharField(max_length=100, blank=False, default=None) 
  • blank will prevent an empty string to be provided in the admin or using a form or serializer (most cases). However as pointed out in the comments, this unfortunately does not prevent things like model.name = "" (manually setting blank string)
  • default=None will set name to None when using something like group = Group(), thus raising an exception when calling save
like image 130
rptmat57 Avatar answered Sep 18 '22 20:09

rptmat57