Followup: missing required Charfield in django Modelform is saved as an empty string and does not cause an error

If I try to save an instance of an incomplete model in Django 1.10, I expect Django to raise an error. This does not seem to be the case.

models.py:

from django.db import models

class Essai(models.Model):
    ch1 = models.CharField(max_length=100, blank=False)
    ch2 = models.CharField(max_length=100, blank=False)

So, I have two fields that are not allowed to be empty (the default behavior, the restriction NOT NULLapplies when creating a Django table when creating MySQL). I expect Django to break the error if one of the fields is not set before saving.

However, when I create an incomplete instance, the data is stored just fine:

>>> from test.models import Essai
>>> bouh = Essai()
>>> bouh.ch1 = "some content for ch1"
>>> bouh.save()
>>> bouh.id
9
>>> bouh.ch1
'some content for ch1'
>>> bouh.ch2
''
>>> 

I would expect Django to raise an error. However, if I force ch2- None, it raises an error:

>>> bouh = Essai()
>>> bouh.ch1 = "some content for ch1"
>>> bouh.ch2 = None
>>> bouh.save()
Traceback (most recent call last):
  (...)
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: test_essai.ch2
>>> bouh.id
>>> bouh.ch1
'some content for ch1'
>>> bouh.ch2
>>>

: Django , SQL "" NULL, Django blank = False ?

, ModelForm, django doc, , :

:  https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#selecting-the-fields-to-use

Django , , , () ModelForm . , , : (...)

modelForm , .

, ModelForm: class EssaiModelForm(forms.ModelForm): class Meta: model = Essai fields = ['ch1'] ch1.

  • ch1 , EssaiModelFormInstance.is_valid(), .
  • ch1 , , ch2 . EssayModelFormInstance.save() , , django. ch2 - , , SQL (NOT NULL).

, "" Charfield , save() validation, .

+4
2

ch1 ch2, , , ,

from django.db import models

class Essai(models.Model):
    ch1 = models.CharField(max_length=100)
    ch2 = models.CharField(max_length=100)

class EssaiModelForm(forms.ModelForm):
class Meta:
    model = Essai
    fields = ['ch1', 'ch2']

Django is_valid()

blank=False

Django - blank = False, required = False

0

. Model.save() . , , , IntegrityError. Model.full_clean(), ModelForm, django, .

, django, ModelForms , . , , .

0

Source: https://habr.com/ru/post/1656048/


All Articles