2
votes

I'm writing an enrollment website for my school, and using Django for the framework. For the registration, I require a username, password, and registration token. Those have yet to be validated, all I'm attempting to do right now is go from the registration input page (which uses a POST request) to a "You have successfully registered" page. Somewhere along the line, the csrf token is apparently refusing to be validated.

My view:

def register(request):
    return render(request, 'enroller/successfulEnroll.html')

My page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="{% url 'register' %}" method="post"> {% csrf_token %}
    <div class="container">
        <label><b>New Username</b></label>
        <input type="text" placeholder="Username" name="uname" required>
        <br>
        <label><b>Password</b></label>
        <input type="password" placeholder="Password" name="psw" required>
        <br>
        <label><b>Registration Password</b></label>
        <input type="text" placeholder="Registration Key" name="reg" required>
        <br>
        <input type="submit" value="Register" />
    </div>
    </form>
</body>
</html>

When I attempt to go from the registration page to the success page, it gives me an error 403 (CSRF Verification failed. Request aborted). However, when I attempt to go to the url mysite.com/register/, it returns the page I requested with no error.

Is there any way to fix this? I've been looking at RequestContext, but I'm not entirely sure where it would be used.

2
The 1.10 docs on csrf mention that the render function you're using (assuming it's django's render that's imported) should cover the RequestContext. The code you've shown so far looks fine. It's likely another issue somewhere in middleware settings, site settings, but not in the code you've posted which looks fine. As an aside, when you go direct to a url with a browser that's a GET request, which CSRF isn't really relevant for. It might be worth considering having a separate success view and doing an HttpResponseRedirect after the successful form processing.Daniel Petrikin

2 Answers

2
votes

Got it to work. Daniel was right - it was a problem with the configuration of my middleware. I added two lines before my middleware array in settings.py, and all of the sudden it worked.

SESSION_COOKIE_SECURE = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True

I can't say I'm entirely sure why it worked, or what the issue was exactly, but it works now. Thanks Daniel!

0
votes

maybe you can use this method. And djang version is 1.11.1

from django.shortcuts import render
from django.template.context_processors import csrf

form = LoginForm()
c = {'form': form}
c.update(csrf(request))
return render(request, 'a_template.html', c)

I found this method at http://djangobook.com/security-in-django/
For me, work fine, but not the best, because more than a line.