samedi 25 avril 2015

Django Form Clean Method Test Error

I'm testing a form that I wrote up earlier. For some reason, the test won't pass. It's like the form is ignoring the data I pass it, and I don't see why. The traceback tells me that the user variable in the clean method of the form is None, though a User is definitely passed into the form. The traceback:

... in clean if user.pk is 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() 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

The Test:

class CreateAuditFormTestCase(TestCase):

    def setUp(self):
        super(CreateAuditFormTestCase, self).setUp()
        self.form = CreateAuditForm
        ...
        self.website = Website.objects.create(
            title="permanence",
            url="http://ift.tt/1b2bVGL",
            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 is probably a simple issue that I can't pick up on, which is what's frustrating me, lol. Help would be appreciated.

Aucun commentaire:

Enregistrer un commentaire