我正在测试我之前写过的表单。出于某种原因,测试不会通过。就像表单忽略了我传递的数据一样,我不明白为什么。回溯告诉我,表单的clean方法中的用户变量是None,尽管用户肯定会传递给表单。追溯:
......干净利落 如果user.pk不是userwebsite.user.pk:AttributeError:' NoneType'对象没有属性' pk'
表格:
class CreateAuditForm(forms.Form):
user = forms.ModelChoiceField(queryset=User.objects.all(), widget=HiddenInput)
website = forms.ModelChoiceField(queryset=UserWebsite.objects.all(), widget=HiddenInput)
emails = forms.CharField(
max_length=250,
required=False
)
def clean_user(self):
user = self.cleaned_data.get('user', None)
if not user.groups.filter(name__iexact='subscribed').exists() and not user.groups.filter(name__iexact='addon').exists():
raise forms.ValidationError(_("You must have an active subscription to request \
website audits. Please try again after subscribing to us."))
return user
def clean(self):
data = self.cleaned_data
user = data.get('user')
userwebsite = data.get('website', None)
if userwebsite.user:
if user.pk is not userwebsite.user.pk:
raise forms.ValidationError(_("Sorry, try again."))
elif userwebsite.addon:
if user.pk is not userwebsite.addon.pk:
raise forms.ValidationError(_("Sorry, try again."))
return self.cleaned_data
def save(self):
# Action
测试:
class CreateAuditFormTestCase(TestCase):
def setUp(self):
super(CreateAuditFormTestCase, self).setUp()
self.form = CreateAuditForm
...
self.website = Website.objects.create(
title="permanence",
url="https://www.badabuyhere.com",
display="www.bababuyhere.com")
self.unsubscriber = User.objects.create(
username="adiagojesse",
first_name="adiago",
last_name="jesse",
email="bannerfare@coldmount.com",
password="tigermountainvalley"
)
self.unsubscriberwebsite = UserWebsite.objects.create(
user=self.unsubscriber,
website=self.website,
is_competitor=False
)
...
def test_user_validation(self):
data = {
"user":self.unsubscriber.pk,
"website":self.unsubscriberwebsite.pk,
"emails":"john@gmail.com, jeff@gmail.com"
}
self.assertTrue(self.unsubscriber)
self.assertTrue(self.unsubscriberwebsite)
audit = self.form(data)
self.assertEqual(audit.is_valid(), False)
这可能是一个我无法接受的简单问题,这让我感到沮丧,哈哈。帮助将不胜感激。
答案 0 :(得分:1)
我的猜测是CreateAuditForm.clean
,user
为None
,因为clean_user
提出ValidationError
。 ValidationError
来自于用户没有他需要的组的事实。
我看到的另一个问题是,为了测试Django中模型实例之间的相等性,您不应该使用主键,而是使用==
而不是is
直接使用实例进行测试。 (有关is
和==
)
示例:
if user != userwebsite.user:
# etc...