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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With