working with form in Django - python

This is page that designed to submit the answers of my MCQ(multiple choice question) App in Django.
{% extends 'quiz/base.html' %}
{% block content%}
<h1>You are at quiz page</h1>
<form action="{% url 'quiz:process_data' %}" method="post">
{% csrf_token %}
{% for question in question_set %}
<h3>{{question.id}}.{{question.question_text }}</h3>
{% for option in question.options_set.all %}
<input type="radio" name="choice" value="{{ option.options}}" > {{option.options}}<br>
{% endfor %}
{% endfor %}
<input type="Submit" name="Submit">
</form>
{% endblock%}
The problem is that it can only select the answer of one question. There is something wrong with my form. Thank you

<input type="radio" name="choice" value="{{ option.options}}">
by this line name of radio button will be same for each question. that's why you are able to select only one answer.
name of radio button should be different for diff. question
<input type="radio" name="choice{{question.id}}" value="{{ option.options}}">
you can use this code. In this name of radio buttons in first question will be "choices1". and you can get selected option by
request.POST.get('choice1')

Related

django template -TemplateSyntaxError [duplicate]

This question already has answers here:
Invalid block tag : 'endblock'. Did you forget to register or load this tag?
(15 answers)
Closed 12 days ago.
I am a beginner in Django world. When I try render my login.html template I'm facing this problem even there is a closing block.
TemplateSyntaxError at /login/
Invalid block tag on line 12: 'else', expected 'endblock'. Did you forget to register or load this tag?`
Here is my template
{% extends 'base.html' %}
{% block content %}
{% if not request.user.is_authenticated %}
<div style="margin-top: 30px">
<form method="POST">
{% csrf_token %} {% if error %}
<p style="color: red">{{error}}</p>
{% endif %}
<div>
<input type="text" name="username" placeholder="username" />
</div>
<div>
<input type="password" name="password" placeholder="password" />
</div>
<button type="submit">Login</button>
</form>
</div>
{% else %}
<p>
You're already logged in. Would you like to logout?
</p>
{% endif %}
{% endblock content%}
The issue seems to be from the csrf_token. You are using it as a tag instead of variable.
Change {% csrf_token %} to {{ csrf_token }} and it should fix the issue.

HTML element to dynamically pop up specific suggestions for field in form

I'm working on a database tool using python+flask+werkzeug and learning how to use most of it for the first time. For the "Institution" field in the template, as the user starts typing in the name I would like existing options that fit the pattern to pop up in a drop-down, then with an option to add a new one if it's not found in that list. I've found the <select> element, and I can see a way to do it with that. However, it just has hard-coded in choices with no way to type in, and there may be hundreds of institutions I wouldn't want to put all in here. I don't know the terminology for the element I'm looking for so I don't really know what to google. Any thoughts?
{% extends 'base.html' %}
{% block header %}
<h1>{% block title %}Add New Member{% endblock %}</h1>
{% endblock %}
{% block content %}
<form method="post">
<label for="full_name">Full Name</label>
<input type="text" name="full_name" id="full_name" value="{{ request.form['full_name'] }}" required>
<label for="phone_number">Phone #</label>
<input type="tel" name="phone_number" id="phone_number" value="{{ request.form['phone_number'] }}">
<label for="email">Email</label>
<input type="email" name="email" id="email" value="{{ request.form['email'] }}">
<label for="institution_name">Institution</label>
<select id="institution_name" name="institution_name">
{% for institution in institution %}
<option value="{{ institution['institution_name'] }}">{{ institution['institution_name'] }}</option>
{% endfor %}}
<option value="not_found">Not found. Add new?</option>
</select>
<input type="submit" value="Submit">
</form>
{% endblock %}
There are JavaScript plugins that allow for this, such as Select2, but a simpler option could be to use a datalist element for this.
<div>
<datalist id="institution_list">
{% for institution in institution %}
<option value="{{ institution['institution_name'] }}">{{ institution['institution_name'] }}</option>
{% endfor %}}
</datalist>
<input autoComplete="on" list="institution_list"/>
</div>

Can't get form data in view function: Django

I need to submit a string to a view function via a dropdown menu and submit button.
in my template I have:
<form action="{% url 'exec_task' %}" method="post">
{% csrf_token %}
<select id="select_task" form="select_task" name="select_task">
{% for task in available_tasks %}
<option id="selected_task" value="{{ task }}">{{ task }}</option>
{% endfor %}
</select>
<input class="button" type="submit" value="Run Selected Task">
</form>
in my view function I have:
def exec_task(request):
if request.method == 'POST':
task = request.POST.get('select_task')
print(task)
getattr(tasks, task)(0)
return redirect('management')
The print(task) always comes out as None, which generates an error when I try to call it via getattr in the next line.
I've read through all the questions and tutorials I can find on this and I don't know what I'm doing wrong, but when I print the request.POST object, all I get is the csrf token. The QueryDict has nothing else in it.
Any ideas?
As discussed in comments please remove
form="select_task" from select tag.
So final select tag / html would be.
<form action="{% url 'exec_task' %}" method="post">
{% csrf_token %}
<select id="select_task" name="select_task">
{% for task in available_tasks %}
<option id="selected_task" value="{{ task }}">{{ task }}</option>
{% endfor %}
</select>
<input class="button" type="submit" value="Run Selected Task">
</form>

How to get all the options submitted by form

How to get all the options submitted by the form in Django, this is the form which I used.
{% extends 'quiz/base.html' %}
{% block content%}
<h1>You are at quiz page</h1>
<form action="{% url 'quiz:process_data' %}" method="post">
{% csrf_token %}
{% for question in question_set %}
<h3>{{question.id}}.{{question.question_text }}</h3>
{% for option in question.options_set.all %}
<input type="radio" name="choice{{question.id}}" value="{{ option.options}}" > {{option.options}}<br>
{% endfor %}
{% endfor %}
<input type="Submit" name="Submit">
</form>
{% endblock%}
I tried selected_choice=request.POST ,but getting this as output csrfmiddlewaretokenchoice1Submitchoice3. How can I solve this? Thank you
In django request.POST is dictionary-like object, see details here.
So to obtain argument choice in view you can use following syntax:
selected_choice=request.POST.get('choice')
which return choice value or None in case this is empty.
Since request.POST is dict-like object you can use items() method to get all values and filter them:
for k, v in request.POST.items():
if k.startswith('choice'):
print(k, v)
this will print only those params with choice text in name.
selected_choice=request.POST.get('choice')
The above should work just fine, but if you're crazy, you can try this:
{% extends 'quiz/base.html' %}
{% block content%}
<h1>You are at quiz page</h1>
<form action="{% url 'quiz:process_data' %}" method="post" id= "crazyform">
{% csrf_token %}
{% for question in question_set %}
<h3>{{question.id}}.{{question.question_text }}</h3>
{% for option in question.options_set.all %}
<input type="radio" name="choice" value="{{ option.options}}" > {{option.options}}<br>
{% endfor %}
{% endfor %}
<input type="hidden" name="crazychoice" class="crazy" value="nothing">
<input type="Submit" name="Submit">
</form>
{% endblock%}
Then some JQuery:
$('#crazyform input').on('change', function() {
$(".crazy").val($('input[name=choice]:checked', '#crazyform').val())})
Everytime you click a radio button, the value of the hidden input field changes to the value of the selected radio button.
Then in your view you can:
selected_choice = request.POST.get("crazychoice", "")

GAE template code to check is item in the list

How to use "in" statement to check is item in the list or not. If I use:
{% for picture in pictures %}
{% if picture in article.pictures %}
<input type="checkbox" checked="true" name="picture" value="{{ picture.key }}" />
{% else %}
<input type="checkbox" name="picture" value="{{ picture.key }}" />
{% endif %}
<img src='/img?img_id={{ picture.key }}'></img> <br />
{% endfor %}
this is failing with:
TemplateSyntaxError: 'if' statement improperly formatted
on line
{% if picture in article.pictures %}
help?
By default, Django templates do not support full conditional expressions. You can check if one value is "true" with if, or you can check whether two values are equal with ifequal, etc.
Perhaps you can decorate your pictures in the view before you render the template.
for picture in pictures:
picture.is_in_article = (picture in article.pictures)
Then in the template you can act on the value of that new attribute.
{% for picture in pictures %}
{% if picture.is_in_article %}
<input type="checkbox" checked="true" name="picture" value="{{ picture.key }}" />
{% else %}
<input type="checkbox" name="picture" value="{{ picture.key }}" />
{% endif %}
<img src='/img?img_id={{ picture.key }}'></img> <br />
{% endfor %}
I've not worked with GAE, but the code for a custom "ifin" Django tag can be found in the patch here. As mentioned in my comment, it looks like that functionality may be implemented in Django 1.2

Categories

Resources