Why not work is_valid for ModelForm in the transmission instance?

Override the user model:
# models.py

class CustomConfirmedUser(AbstractBaseUser, PermissionsMixin):
 """Model user with the option confirmation by e-mail, it inherits from AbstractBaseUser"""

 email = models.EmailField("Email user", max_length=128, unique=True)
 username = models.CharField("Username", max_length=128, unique=True)
 is_active = models.BooleanField(default=True)
 is_staff = models.BooleanField(default=False)
 confirm = models.BooleanField("User confirmed", default=False)

 objects = CustomUserManager()
 confirmed = CustomConfirmedManager()

 USERNAME_FIELD = 'username'
 REQUIRED_FIELDS = ['email',]

 def get_full_name(self):
 return self.username

 def get_short_name(self):
 return self.username

# forms.py

class CustomConfirmedUserChangeForm(forms.ModelForm):
 """Form to edit CustomConfirmedUser"""
 password = ReadOnlyPasswordHashField()

 class Meta:
 model = CustomConfirmedUser
 fields = ('username', 'email', 'confirm', 'password', 'is_staff', 'is_superuser')

 def clean_password(self):
 return self.initial['password']

# tests.py

class TestCustomUserChangeForm(TestCase):

 def setUp(self):
 self.username = 'test'
 self.email = 'test@test.ru'
 self.password = 'password123'
 self.user = CustomConfirmedUser.objects.create_user(
self.username
self.email
self.password
)

 def test_clean_password(self):
 form = CustomConfirmedUserChangeForm(
 {'username': 'newtest',},
instance=self.user
)
form.is_valid()
print(form.initial)
print(form.errors)
 self.assertTrue(form.is_valid())


The result:
{'password': 'pbkdf2_sha256$150000$nGiR5RBeDrAU$7s+IaSLRR3W/io1W7jQahjLRBGitxOwmvDXtEeD83/A=', 'is_superuser': False, 'email': 'test@test.ru', 'username': 'test', 'is_staff': False, 'confirm': False}
<ul class="errorlist"><li>email<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
F...
======================================================================
FAIL: test_clean_password (my_auth.tests.test_forms.TestCustomUserChangeForm)
----------------------------------------------------------------------
Traceback (most recent call last):
 File "/home/v-ampire/Projects/django-base/django_base/my_auth/tests/test_forms.py", line 100, in test_clean_password
self.assertTrue(form.is_valid())
AssertionError: False is not true


Don't understand, well given instance, unless the username does not have to be there?
April 4th 20 at 00:54
1 answer
April 4th 20 at 00:56
Solution
When you output the form, it takes values for the fields of the instance, but when sending the POST request, it must contain at least all mandatory data, not only those that have changed what you have stated in error.

Find more questions by tags Django