Disappearing {% csrf_token %} on website file - python

When I wanted use my registration form in my site, I get ERROR 403: "CSRF verification failed. Request aborted." In source of this website I realised that is missing. This is part of view-source from my site:
<div style="margin-left:35%;margin-right:35%;">
<fieldset>
<legend> Wszystkie pola oprócz numeru telefonu należy wypełnić </legend>
<form method="post" action=".">
<p><label for="id_username">Login:</label> <input id="id_username" maxlength="30" name="username" type="text" required/></p>
<p><label for="id_email">Email:</label> <input id="id_email" name="email" type="email" required /></p>
<p><label for="id_password1">Hasło:</label> <input id="id_password1" name="password1" type="password" required /></p>
<p><label for="id_password2">Powtórz hasło:</label> <input id="id_password2" name="password2" type="password" required /></p>
<p><label for="id_phone">Telefon:</label> <input id="id_phone" maxlength="20" name="phone" type="text" /></p>
<p><label for="id_log_on">Logowanie po rejestracji:</label><input id="id_log_on" name="log_on" type="checkbox" /></p>
<input type="submit" value="Rejestracja"><input type="reset" value="Wartości początkowe">
</form>
</fieldset>
</div>
I was surprised of that, because in my files on Pythonanythere this fragment of code is present.
This is part of my file register.html on Pythonanythere:
<div style="margin-left:35%;margin-right:35%;">
<fieldset>
<legend> Wszystkie pola oprócz numeru telefonu należy wypełnić </legend>
<form method="post" action=".">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Rejestracja"><input type="reset" value="Wartości początkowe">
</form>
</fieldset>
</div>
What am I doing wrong that my webpage don't see this piece of code? It is seamed on server but on webpage view-source It isn't.
EDIT:
This is view, which render my template:
def register(request):
if request.method == 'POST':
form = FormularzRejestracji(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
user.last_name = form.cleaned_data['phone']
user.save()
if form.cleaned_data['log_on']:
user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'])
login(request, user)
template = get_template("osnowa_app/point_list.html")
variables = RequestContext(request, {'user': user})
output = template.render(variables)
return HttpResponseRedirect("/")
else:
template = get_template("osnowa_app/register_success.html")
variables = RequestContext(request, {'username': form.cleaned_data['username']})
output = template.render(variables)
return HttpResponse(output)
else:
form = FormularzRejestracji()
template = get_template("osnowa_app/register.html")
form = FormularzRejestracji()
variables = RequestContext(request, {'form': form})
output = template.render(variables)
return HttpResponse(output)

You should pass a plain dict and the request object to template.render(), not a RequestContext. The template engine will convert it to a RequestContext for you:
template = get_template("osnowa_app/register.html")
context = {'form': form}
output = template.render(context, request)
Right now, the template.render() function sees a dict-like object as the first argument, but no request as the second argument. Without a request as the second argument, it converts the dict-like RequestContext into a plain Context object. Since the Context object doesn't run context processors, your context is missing the csrf token.
Alternatively you can just use the render shortcut, which returns a HttpResponse object with the rendered template as content:
from django.shortcuts import render
def register(request):
...
return render(request, "osnowa_app/register.html", {'form': form})
This particular case is also being discussed in ticket #27258.

CSRF token gets included in HTML form by calling hidden_tag function on your form object.
For example check this gist, line number 6. This is how you add form and it's elements in jinja.

Related

How to fix error "The view app.views.uploadform didn't return an HttpResponse object. It returned None instead."?

So I have a form in a html document and I'm trying to use it to add a new item to my django database.
Here is the HTML form :
<form method="POST" action="{% url 'uploadform' %}" enctype="multipart/form-data">
{% csrf_token %}
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="details">Details:</label><br>
<input type="text" id="details" name="details"><br>
<label for="littype">Type of Literature:</label><br>
<input type="text" id="littype" name="littype"><br>
<label for="image">Cover:</label><br>
<input type="file" id="image" name="image"><br>
<input type="submit" value="Submit">
</form>
Here is my views.py handling the function :
def uploadform(request):
if request.method == 'POST':
if request.POST.get('name') and request.POST.get('details') and
request.POST.get('littype') and request.POST.get('image'):
post = PostForm()
post.name = request.POST.get('name')
post.details = request.POST.get('details')
post.littype = request.POST.get('littype')
post.image = request.POST.get('image')
if PostForm.is_valid():
PostForm.save()
return render(request, 'uploadform.html')
else:
return render(request, 'uploadform.html')
Here is my models.py even though i think the issue is in views.py :
class PostForm(models.Model):
name = models.CharField(max_length=200)
details = models.TextField()
littype = models.TextField()
image = models.FileField(upload_to='app/files/')
And finally for the issue, im getting an error saying "The view app.views.uploadform didn't return an HttpResponse object. It returned None instead.". I'm not sure what is causing the error and in addition,if there are any changes I have to make thats stopping the form from being turned into a new item in my database, I'd love to get help for that too.
Thanks for any answers! Have a good day!

How to pass data from a template to the Django side

I just started to code Python Django. I just wanted to make a basic login project. I tried to pass login variables from the HTML side to file views.py.
Here is my HTML code:
<form action="/index" method="post">
{% csrf_token %}
<div class="form-group">
<label for="username">Username</label>
<input class="form-control" id="username" type="email"/>
</div>
<div class="form-group">
<div class="d-flex justify-content-between">
<label for="password">Password</label><a class="fs--1">Forgot Password?</a>
</div>
<input class="form-control" id="password" type="password" />
</div>
<div class="custom-control custom-checkbox">
<input class="custom-control-input" type="checkbox" id="card-checkbox" checked="checked"/>
<label class="custom-control-label" for="card-checkbox">Remember me</label>
</div>
<div class="form-group">
<button class="btn btn-primary btn-block mt-3"
type="submit"
id= "login"
name="submit">Log in</button>
</div>
</form>
My urls.py file:
urlpatterns = [
path('', views.loginPage, name="login"),
path('index', views.home, name="index")
]
My forms.py file:
from django import forms
class LoginForm(forms.Form):
username = forms.EmailField(label="Username"),
password = forms.CharField(label="Password")
And my views.py file:
def home(request):
context = {}
if request.method == 'POST':
form = LoginForm(request.POST)
print('form:', form)
if form.is_valid():
print('niceee')
else:
return render(request, 'index.html', context)
else:
form = LoginForm()
I just want to see username and password values into views.py. However, I can't see variables into views.py. How can I fix this?
def home(request):
if request.method == 'POST':
form = LoginForm(request.POST)
print('form:', form)
if form.is_valid():
print('username:', form.cleaned_data.get('username'))
print('password:', form.cleaned_data.get('password'))
print('niceee')
else:
form = LoginForm()
context = {}
return render(request, 'index.html', context)
Check the server for username and password values.
You are a halfway there! Once the form has been validated by Django, you can access the form's variables in its cleaned_data attribute:
def home(request):
context = {}
if request.method == 'POST':
form = LoginForm(request.POST)
print('form:', form)
if form.is_valid():
print('You submitted this username:', form.cleaned_data['username'])
print('You submitted this password:', form.cleaned_data['password'])
else:
return render(request, 'index.html', context)
else:
form = LoginForm()
However, consider reusing django.contrib.auth.views.LoginView because then you won't have to write any Python code at all. Just customize the registration/login.html template.

Django, Getting a value from a POST

I have in my template:
This is passed by {{form}}
<form action="" method="POST">
Inicio: <input type="text" id="start">
<input type="submit" value="Sned" >
{% csrf_token %}
</form>
Then in the views.py
def test(request):
if request.method != 'POST':
context = {'form': 'by GET'}
return render(request, 'test.html', context)
else:
if 'start' in request.POST:
start = request.POST['start']
else:
start = False
context = {'form': start}
return render(request, 'test.html', context)
It seems that always return False
If I dont check the existance of the key I have this error:
MultiValueDictKeyError
And the erropage says : "'start'" (single plus double quotes)
id is intended for javascript and css purposes. For variables that are important on server side, you should use name tag.
<input type="text" id="start" name="start">
You need to add a name attribute in your input, so when you are getting the POST data it will be found.
<form action="" method="POST">
Inicio: <input type="text" id="start" name="start">
<input type="submit" value="Sned" >
{% csrf_token %}
</form>
Also I recommend you to do the following change in your view:
Replace
request.POST['start']
by:
request.POST.get('start')
So, if the field is not found, it will be reassigned whith a None value.
add name
<input type="text" name="start" id="start">

Django, form is_valid() is always false

I'm learning Django and have some troubles with forms. I try to create a simple form where I type a name and show it on another page. But is_valid() always returns false. Please, help me to find my error
forms.py
from django import forms
class OrderForm(forms.Form):
user=forms.CharField(max_length=100)
views.py
def order(request):
return render(request, 'myapp/order.html', {})
def contact(request):
username='not logged'
if request.method == 'POST' :
form=OrderForm(request.POST)
if form.is_valid():
username=form.cleaned_data['username']
else:
username='not worked'
else:
form=OrderForm()
return render(request, 'myapp/contacts.html', {'username':username})
order.html
<form name = "form" action = "{% url 'contact' %}" method = "POST" >
{% csrf_token %}
<input type="text" name="username" placeholder="Name">
<button type="submit">Login</button>
</form>
contacts.html
You are : <strong>{{ username }}</strong>
Your form control has the name username in HTML, while your form's field is named user in Django. Thus, nothing is set in the form field.
Normally you'd put the form into the context and then render it either as {{ form }} or the like, or render each field, rather than build your own form controls. The docs show how: https://docs.djangoproject.com/en/1.10/topics/forms/#working-with-form-templates
views.py
from forms import OrderForm
def order(request):
form = OrderForm()
return render(request, 'myapp/order.html', {"form" : form})
order.html
<form name = "form" action = "{% url 'contact' %}" method = "POST" >
{% csrf_token %}
{{form.as_p}}
<button type="submit">Login</button>
</form>
At the time of rendering template {{form.as_p}} looks like
<p><label for="id_username">Username:</label>
<input id="id_username" type="text" name="username" maxlength="100" required /></p>

Django throwing "CSRF token missing or incorrect" Error (because of empty value of csrfmiddlewaretoken)

I recently got stuck with a pretty strange issue. I have a form in my template as follows:
<form class="form" id="loginForm" role="form" action="/user/login/"
method="POST">
{% csrf_token %}
<div class="form-group">
<input type="email" class="form-control" id="email" name="email"
placeholder="Enter email" value="">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password"
name="password" placeholder="Password" value="">
</div>
<div class="cl-effect-7">
<button type="submit" class="btn btn-primary">SIGN IN</button>
</div>
</form>
I was getting CSRF token missing or incorrect. Digging further deep down i found that though csrftoken cookie is getting correctly set in the browser the POST request is having empty value of csrfmiddlewaretoken and hence it throws the error with the said reason.
Also here is my view(though I doubt if there is anything wrong with it)
def user_login(request):
context = RequestContext(request)
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
user = authenticate(username=email, password=password)
if user:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/user/')
else:
return HttpResponse("Your account is disabled.")
else:
return HttpResponse("Invalid login details supplied.")
else:
return render_to_response('user/login.html', {},context_instance = context)
Here's the other view which redirects to login.html:
def index(request):
context_dict = {}
template = "user/login.html" #default template to render
user = None
user_profile = None
user = request.user.id
if user != None:
user_profile,created = UserProfile.objects.get_or_create(user=user)
#Check whether the user is new,if yes then he needs to select btw Mentor-Mentee
if user_profile and user_profile.is_new:
context_dict['selected'] = None
template = "user/select.html" #User has to select either Mentor/Mentee,so redirect to select.html
return render_to_response(template,context_dict,context_instance = RequestContext(request))
Now I used little JavaScript to get around this, by setting the value of csrfmiddlewaretoken from the cookie manually but that's a little strange behavior from Django.
PS: Im using Django 1.7 and tested this on all browsers.
Try adding this to your form:
<div style="display:none">
<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
</div>
Source: https://docs.djangoproject.com/en/dev/ref/csrf/#other-template-engines

Categories

Resources