python - Django Form Clean Method Test Error -
i'm testing form wrote earlier. reason, test won't pass. it's form ignoring data pass it, , don't see why. traceback tells me user variable in clean method of form none, though user passed form. traceback:
... in clean if user.pk not userwebsite.user.pk: attributeerror: 'nonetype' object has no attribute 'pk'
the form:
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() , not user.groups.filter(name__iexact='addon').exists(): raise forms.validationerror(_("you must have active subscription request \ website audits. please try again after subscribing 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 not userwebsite.user.pk: raise forms.validationerror(_("sorry, try again.")) elif userwebsite.addon: if user.pk not userwebsite.addon.pk: raise forms.validationerror(_("sorry, try again.")) return self.cleaned_data def save(self): # action
the test:
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)
this simple issue can't pick on, what's frustrating me, lol. appreciated.
my guess in createauditform.clean
, user
is none
because clean_user
raised validationerror
. validationerror
comes fact user not have groups needs.
another issue see test equality between model instances in django, should not use primary keys test using instances directly, using ==
, not is
. (see https://stackoverflow.com/a/13650309/1644198 more information on is
, ==
)
example:
if user != userwebsite.user: # etc...
Comments
Post a Comment