Search code examples
python-3.xdjango-templatesdjango-viewsdjango-csrf

Python 3.6 / Django 2.1.4 : "signing up with an already existing username/email breaks the CSRF_TOKEN"


I was running some tests in Django to see if form.errors raises all types of errors in the form (which it does).

Now here's where things went south:

If i try to sign up with an existing email/username (just checking the efficiency) more than once , i get this

Forbidden (403)
CSRF verification failed. Request aborted.

Help text : (all those conditions are met.)

I think these tests break the csrf_token.

So i don't know if the problem is coming from my code or the csrf_token is just doing its job by protecting the owner of that username/email.

Did anyone encounter an issue like this before ?

SignUp View

class SignUp(View):

    def get(self, request):
        form = MyModelCreation()
        return render(
            request,
            'signup.html',
            {'form': form}
        )

    def post(self, request):
        form = MyModelCreation(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False  # Create an inactive user
            user.save()

            # Send a confirmation Email
            # Generate a token for the new user --tokens.py--
            current_site = get_current_site(request)
            mail_subject = 'Activate your profile account.'
            message = render_to_string('account_activation_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
                'token': user_token.make_token(user),
            })
            receiver = form.cleaned_data.get('email')
            email = EmailMessage(
                mail_subject, message, to=[receiver]
            )
            email.send()
            return redirect("account_activation_sent")
        else:
            return render_to_response(
                   'signup.html', 
                   {"form": form}, 
                   RequestContext(request)
                   )

SignUp Template

{% extends 'base_test.html' %}
{% block title %}My Site | Sign Up{% endblock title %}
{% block content %}
<div class="padding">
  <h2>Sign up : <small>*ALL FIELDS ARE REQUIRED</small></h2>
  <form method="post" class="form">
    {% csrf_token %}
    {% for field in form %}
      <p>
        {{ field.label_tag }}<br>
        {{ field }}
        {% for error in field.errors %}
          <p style="color: red">{{ error }}</p>
        {% endfor %}
      </p>
    {% endfor %}
    <button class="btn btn-primary btn-lg" type="submit">Sign up</button>
  </form>
</div>
{% endblock %}

Solution

  • well i fixed it by switching back to render(), i think render_to_response() requires some additional data that i don't know of.

    return render(request, 'signup.html', {'form': form})
    

    Thank you !