0

I am trying to implement email authentication during sign up. But always the compiler returning the invalid form. Can anyone suggest what may be the reason behind this? I am using SALEOR package for this project. Below I have posted model, forms and views code

models.py

class User(PermissionsMixin, AbstractBaseUser):
    email = models.EmailField(unique=True)
    addresses = models.ManyToManyField(Address, blank=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now, editable=False)
    default_shipping_address = models.ForeignKey(
        Address, related_name='+', null=True, blank=True,
        on_delete=models.SET_NULL)
    default_billing_address = models.ForeignKey(
        Address, related_name='+', null=True, blank=True,
        on_delete=models.SET_NULL)

    USERNAME_FIELD = 'email'

    objects = UserManager()

forms.py

class SignupForm(forms.ModelForm):
    password = forms.CharField(
        widget=forms.PasswordInput)
    email = forms.EmailField(
        error_messages={
            'unique': pgettext_lazy(
                'Registration error',
                'This email has already been registered.')})

    class Meta:
        model = User
        fields = ('email',)
        labels = {
            'email': pgettext_lazy(
                'Email', 'Email'),
            'password': pgettext_lazy(
                'Password', 'Password')}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self._meta.model.USERNAME_FIELD in self.fields:
            self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update(
                {'autofocus': ''})

    def save(self, request=None, commit=True):
        user = super().save(commit=False)
        password = self.cleaned_data['password']
        user.set_password(password)
        if commit:
            user.save()
        return user

views.py the else part of if form.is_valid getting executed every time

def signup(request):

if request.method == 'POST':
    form = SignupForm(request.POST or None)
    print('POST Method')
    if form.is_valid():
        print('Valid Form')

        user = form.save(commit=False)
        user.is_active = False
        user.save()

        current_site = get_current_site(request)
        mail_subject = "Activate Your Account"
        message = render_to_string('account/activate.html', {
            'user': user,
            'domain': current_site.domain,
            'uid':force_text(urlsafe_base64_encode(user.pk)),

            'token':account_activation_token.make_token(user),
        })
        to_email = form.cleaned_data.get('email')
        from_email = settings.EMAIL_HOST_USER
        email = EmailMessage(
                    mail_subject, message,  to=[to_email]
        )
        email.send()
        print('Mail Sent')
        return HttpResponse('Please confirm your email address to complete the registration')
    else:
        form = SignupForm()
        print('else of form valid')
        return render(request, 'account/signup.html', {'form': form})
else:
    print('Not POST Method')
    form = SignupForm()
    return render(request,'account/signup.html',{'form':form})
  • `form = SignupForm(request.POST or None)` why you add `or None` in the brackets? you should bind `request.POST` with the form `form = SignupForm(request.POST)` – Haifeng Zhang Apr 26 '18 at 05:03
  • I am using SALEOR package, it was there from beginning. I have tried by removing None but no result @haifzhan –  Apr 26 '18 at 05:05
  • 1
    It doesn't make sense if the SignupForm bind with None, the fields are required, right? – Haifeng Zhang Apr 26 '18 at 05:06
  • yes all fields are required @haifzhan –  Apr 26 '18 at 05:09
  • `None` means when someone visits the view, with request POST, it will keep data from POST, otherwise, it will be None... that is not a problem – Lemayzeur Apr 26 '18 at 05:43
  • 1
    if you always got `invalid form` that is because the form is actually invalid. add `print("form.errors")` after this line `print('else of form valid')` or `{{form.errors}}` in template to debug. BTW you don't really need to assign form yet again in the 7 last lines. remove them. – Lemayzeur Apr 26 '18 at 05:47
  • Might be slightly offtopic, but there's an open PR which implements email authentication https://github.com/mirumee/saleor/pull/1672/files you might take some inspiration from there – Pythonist Apr 27 '18 at 15:44
  • Thanks for your suggestion. Though it is really helpful but I am getting some error. Can you tell me why I am getting such error? 'NoneType' object has no attribute 'get_exception_info' in this line send_confirmation_mail_if_required(request,user) @Pythonist –  May 02 '18 at 12:19

0 Answers0