我已覆蓋AdminModel
的ModelForm
使User
字段可以從Person
的管理員更改表格中獲得並保存。如何測試ModelForm save()方法將更改保存在模型中?
class Person(models.Model):
user = models.OneToOneField(User)
#and also some char, text fields
@property
def name(self):
return self.user.first_name
@name.setter
def name(self, value):
self.user.first_name = value
#and by analogy surname and email properties
class PersonForm(ModelForm):
class Meta:
model = Person
name = forms.CharField(max_length=100, required=False)
surname = forms.CharField(max_length=100, required=False)
email = forms.EmailField(required=False)
def save(self, commit=True):
instance = super(PersonForm, self).save(commit)
user = instance.user
user.first_name = self.cleaned_data['name']
user.last_name = self.cleaned_data['surname']
user.email = self.cleaned_data['email']
user.save()
return instance
class PersonAdmin(admin.ModelAdmin):
fields = ['name', 'surname', 'email', 'and_others']
form = PersonForm
admin.site.register(Person, PersonAdmin)
但是我寫一個測試,檢查save()方法掙扎:
def test_form_saves_values_to_instance_user_on_save(self):
"""
test that, form saves name, surname, email values to corresponding User
when commiting form
"""
user = User.objects.get(username='admin')
person = Person.objects.get(user=user)
personform = PersonForm(instance=person, data={'name': 'has_changed'})
# if uncommented raisesValueError: The Person could not be changed
# because the data didn't validate.
# personform.save()
self.assertEquals("has_changed", User.objects.get(pk=user.pk).first_name)
UPD測試
UPD解決方案。事實證明,我沒有填寫要求無形字段'用戶'。排除使表格有效並通過測試。
admin.py
class PersonForm(ModelForm):
class Meta:
model = Person
exclude = ('user',)
# ...
tests.py
def test_form_saves_values_to_instance_user_on_save(self):
"""
test that, form saves name, surname, email values to corresponding User
when commiting form
"""
person = Person.objects.get(user__username='admin')
personform = PersonForm(instance=person, data={'name': 'has_changed'})
if personform.is_valid():
person = personform.save()
self.assertEquals(User.objects.get(pk=person.user.pk).first_name, "has_changed")
else:
self.fail("personform not valid")
這將返回'ValueError異常:該人不能被改變,因爲該數據沒有validate.' –
' self.assertEquals(user.first_name,「has_changed」)'''''''''''''''''''''''''''''''''''''因爲'user'中的數據不會從數據庫重新加載,所以無法更改。 – knbk
如何使personform有效或使其失效? –