[英]When posting to a Django form, are all fields posted?
我正在嘗試為表單編寫測試以模擬我只想更新一個字段的情況。 這是測試:
from django.test import TestCase
from django.forms.models import model_to_dict
class FamilyDemographicsUpdateTest(TestCase):
def test_update_phone_types_with_fields_from_family_factory(self):
# Create a family for which the employee uses an iPhone
family = FamilyFactory(employee_phone_type=Family.IPHONE)
url = reverse('dashboard:family', kwargs={'pk': family.id, 'tab': 'family-demographics'})
data = model_to_dict(instance=family, fields=FamilyDemographicsForm.base_fields)
form = FamilyDemographicsForm(data=data)
之后我使用import ipdb; ipdb.set_trace()
進入調試器import ipdb; ipdb.set_trace()
import ipdb; ipdb.set_trace()
。 在這里,我注意到form
有errors
:
ipdb> form.errors
{'employee_email': ['This email is already taken.']}
這可以追溯到表單所基於的Family
模型。 表單是一個ModelForm
:
class FamilyDemographicsForm(forms.ModelForm):
class Meta:
model = Family
該視圖基於 Django 的通用UpdateView
:
class FamilyUpdate(SuccessMessageMixin, DashboardAccessMixin, UpdateView):
template_name = 'families/edit.html'
model = Family
success_message = "Family was updated successfully."
def get_form_class(self, **kwargs):
tab = self.kwargs['tab']
if tab == 'family-demographics':
return FamilyDemographicsForm
並且相應的Family
對象有一個clean()
方法,它會觸發此錯誤(在class Family(models.Model)
):
def clean(self):
if self.employee_email:
db_user = User.objects.filter(username=self.employee_email).first()
if db_user and db_user.family and db_user.family != self:
raise ValidationError({'employee_email': 'This email is already taken.'})
if self.partner_email:
db_user = User.objects.filter(username=self.partner_email).first()
if db_user and db_user.family and db_user.family != self:
raise ValidationError({'partner_email': 'This email is already taken.'})
但是,如果我真的在瀏覽器中使用表單並提交,它似乎工作得很好。 簡而言之,當您在瀏覽器中提交表單時,這不等同於post
數據 - 對於您尚未更改的字段 - 與最初相同嗎? 為什么會在此測試中而不是在瀏覽器中觸發此錯誤?
這與發布數據根本沒有任何關系。 問題是您的視圖是一個更新,它將現有實例傳遞給表單,以便 Django 知道如何更新它。 你的測試不這樣做。
(您的測試並不是真正測試您的代碼;您真的應該使用請求工廠或測試客戶端 v 調用視圖並將數據傳遞到那里。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.