Django, Getting a value from a POST - python

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">

Related

ValueError at /polls/add/ The view polls.views.addQuestion didn't return an HttpResponse object. It returned None instead

I am trying to pass data from html template to django addQuestion view in my polls app.I want to make an add quetion along their vote options template and
I am using django==3.2
Here my html code
<form action="{% url 'polls:add' %}" method="post">
{% csrf_token %}
<label for="your_queston">Question: </label>
<input id="question" type="text">
<br>
<label for="choices">Choice 1</label>
<input id="choice1" type="text"><br>
<label for="choices">Choice 2</label>
<input id="choice2" type="text">
<br>
<label for="choices">Choice 3</label>
<input id="choice3" type="text">
<br>
<input type="submit" value="add">
</form>
and here my addQuestion function in view.py
def addQuestion(request):
if(request.POST):
try:
if(request.POST['question']):
qtext = request.POST.get('question')
q = Question(question_text=qtext, pub_date=timezone.now())
q.save()
if(request.POST['choice1']):
q.choice_set.create(
choice_text=request.POST.get('choice1'), votes=0)
if(request.POST['choice2']):
q.choice_set.create(
choice_text=request.POST.get('choice2'), votes=0)
if(request.POST['choice3']):
q.choice_set.create(
choice_text=request.POST.get('choice3'), votes=0)
q.save()
return HttpResponseRedirect(reverse('polls:index'))
except:
pass
else:
return render(request, 'polls/addQuestion.html')
In your code you have a try-except. As mentioned in the comments, always be specific in what type of expection you want to catch.
But in your code, if an exception happens, the function returns nothing, also know as None. A better way would be:
def view(request):
if request.method == 'POST':
error = False
try:
pass # Do magic here
except YourExpectedException:
# Log the exception
error = True
if error:
return render(request, 'polls/errorPage.html'
return HttpResponseRedirect(reverse('polls:index'))
else:
return render(request, 'polls/addQuestion.html')

How to get html from input and save as variable in Python Django

I'm trying to get a simple input (which would be an integer) from the user, and use it as a variable in the next python function. But whenever I try to print the input it returns None.
Here's my code:
HTML
<form action="/./" method="POST">{% csrf_token %}
<input type="text" name="quantity" placeholder="Repeat" size=2>
<input type="submit" value="Save!">
</form>
Python Django (This is just part of the function.)
def saveCriteria(request):
title = request.POST.get('quantity')
context = {}
print(title)
return render(request, "home.html", context)
Any help or advice would be greatly appreciated!
You should add if statement before that:
def saveCriteria(request):
context = {}
if request.method == "POST":
title = request.POST.get('quantity')
print(title)
return render(request, "home.html", context)
You should refer to the view function in the html template:
<form action="url of saveCriteria" method="POST">
{% csrf_token %}
<input type="text" name="quantity" placeholder="Repeat" size=2>
<input type="submit" value="Save!">
</form>

Django form with checkbox is always False

I'm looking to create a Django form with a checkbox.Irrespective of weather I check or uncheck the box,it is not detected in POST request.Here is the code of the template-
<form action="annotate_page" method="post">{% csrf_token %}
<input id="repeat" type="checkbox" >
<label for="repeat">Repeat Sentence?</label>
<br>
<button type="submit">Next</button><br>
</form>
Here is my forms.py-
from django import forms
class AnnotateForm(forms.Form):
repeat=forms.BooleanField(required=False)
Here is my views logic-
if request.method=="POST":
form = AnnotateForm(request.POST)
if form.is_valid():
print(request.POST)#prints only csrf_token in Query_dict
print(form.cleaned_data["repeat"])#Always false
Irrespective of weather the checkbox is checked or not,the print statement always gives False.
I know there are questions similar,but they don't solve my problem.
<form action="annotate_page" method="post">{% csrf_token %}
<input id="repeat" name="something" type="checkbox" >
<label for="repeat">Repeat Sentence?</label>
<br>
<button type="submit">Next</button><br>
</form>
and in view
if request.method=="POST":
form = AnnotateForm(request.POST)
if form.is_valid():
print(request.POST)#prints only csrf_token in Query_dict
print(form.cleaned_data["something"])#Always false
you need to give a name in the input field or else it wont be captured

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>

Disappearing {% csrf_token %} on website file

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.

Categories

Resources