Reputation: 3513
I'd like to add a form to log a user at more than one page on my website using Django. Instead of having to replicate the form multiple times, I want to use an "include" statement to import the same form. My code right now does two things incorrectly: it does not show a field to enter a username or password, and submiting the form produces a CSRF 403 (Forbidden) error.
sample html:
<!-- Login -->
<div id="login">
<form action="/login/" method="post">
{% csrf_token %}
{% include "registration/login_snippet.html" %}
<p>
<input type="submit" value="login"/></p>
</form>
</div>
login_snippet.html:
{% csrf_token %}
<label for="id_username">
Username:
</label>
{% if form.username.errors %}
<span class="error">
{{ form.username.errors|join:", " }}
</span>
{% endif %}
{{ form.username }}
<label for="id_password">
Password:
</label>
{% if form.password.errors %}
<span class="error">
{{ form.password.errors|join:", " }}
</span>
{% endif %}
{{ form.password }}
Here is what's being displayed:
Any help would be greatly appreciated!
Upvotes: 0
Views: 93
Reputation: 1062
For problem 1 (no field for username and password):
Are you sure the form object is in the context? It seems like there is no {{ form }} that the template has access to, so it can't render {{ form.username }}
For Problem 2 (csrf):
You are including the {% csrf_token %} twice. Once in sample.html and once in login_snippet.html. Removing one of them might solve the issue.
Finally,
Also, is there any reason why the entire login form is not in one snippet? Why separate the 'form' element from the fields?
Upvotes: 0
Reputation: 1994
Try Adding the following to your code. I am not 100% sure, but I think it should work. Obviously, this disables the csrf protection. However, it should allow you to continue to run your website. While csrf is important, I am not sure that it is mandatory on every single view.
from django.views.decorators.csrf import csrf_exempt
#Make this a function in your classview
@csrf_exempt
def dispatch(self, *args, **kwargs):
return super(YOUR_VIEW_NAME_HERE, self).dispatch(*args, **kwargs)
Upvotes: 1