How to get all the options submitted by form - python

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

Related

Trying to reverse posts from newer on top but I keep getting errors in Flask

Here is the code I'm trying to run in my Flask App
{% extends "bootstrap/base.html" %}
{% block title %}Testing title{% endblock %}
{% block content %}
<div class="container">
<h1>Posts</h1>
<h3>Postings</h3>
<form action="/" method="post">
<input hidden placeholder="Name" name="name">
<input placeholder="Post whatever you want..." name="post" required>
<button class="btn btn-primary" type="submit" value="Submit">Submit</button>
</form>
{% for post in posts reversed %}
<div>
{{ 'Anonymous' + ': ' + post[2] }}
</div>
{% endfor %}
</div>
{% endblock %}
This is the error I get jinja2.exceptions.TemplateSyntaxError: expected token 'end of statement block', got 'reversed'
Figure reversed would work since I found some examples online that does that
The correct syntax in Jinja2 to loop through a list in reverse order is:
{% for post in posts|reverse %}
{{ post }}
{% endfor %}

working with form in Django

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')

Trying to create a button per object instance

I'm trying to make a list of buttons, each corresponding to an object in my database. However, when I press one of them, it is always the value of the last button generated which is sent back to the view:
{% if segmenter %}
<form method="post">
{% csrf_token %}
<ul>
{% for segment in segments %}
<li>
<input type="hidden" name="id" value="{{ segment.pk }}"/>
<button type="submit">{{ segment }}</button>
</li>
{% endfor %}
</ul>
{% else %}
<strong>No segments registered. </strong><br />
{% endif %}
Form items are distinguished by name but you're using the same name for your inputs. Besides using one form means you intend to send all the inputs when the inputs are differentiated.
You should do:
{% if segmenter %}
{% csrf_token %}
<ul>
{% for segment in segments %}
<form method="post">
<li>
<input type="hidden" name="id_{{ segment.pk }}" value="{{ segment.pk }}"/>
<button type="submit">{{ segment }}</button>
</li>
</form>
{% endfor %}
</ul>
{% else %}
<strong>No segments registered. </strong><br />
{% endif %}
which posts a separate form on click of each button

Django form wizard multiple formsets on one page

I am trying to create a form in Django with the form wizard where there are multiple (repeating) formsets in the same step of the wizard.
What I have is:
# forms.py
class FormStep1A(forms.Form):
answerA = forms.CharField(max_length=100)
remarkA = forms.CharField(widget=forms.Textarea)
class FormStep1B(forms.Form):
answerB = forms.CharField(max_length=100)
remarkB = forms.CharField(widget=forms.Textarea)
class FormStep1(forms.Form):
partA = formset_factory(FormStep1A)
partB = formset_factory(FormStep1B)
and
# urls.py
STEPS = (
('1', FormStep1),
# ...
)
# FormWizard is a subclass of NamedUrlSessionWizardView
wizard = FormWizard.as_view(STEPS, url_name='form_new_step')
urlpatterns = patterns(
'',
url(r'^new/(?P<step>.+)/$', wizard,
name='form_new_step'),
url(r'^new/$', wizard, name='form_new'),
)
And my template looks the same as in the documentation. However, my form is rendered empty with no fields at all.
I know there are similar questions or recipes out there:
Django formwizard with formsets and forms on same page
django wizard, using form and formset in the same step
Combining a Form and a FormSet in Django: How to pass them in the context?
But I just cannot get this to work. Any help is much appreciated, thank you!
UPDATE: My template looks like this:
{% extends 'base.html' %}
{% load i18n %}
{% block head %}
{{ wizard.form.media }}
{% endblock %}
{% block content %}
<div class="row">
<div class="large-12 columns">
<h3>{% trans "Questionnaire" %}</h3>
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
<form action="" method="post">
{% csrf_token %}
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ wizard.form }}
{% endif %}
{% if wizard.steps.prev %}
<button class="button tiny" name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "First step" %}</button>
<button class="button tiny" name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "Prev step" %}</button>
{% endif %}
<input class="button tiny" type="submit" value="{% trans "Submit" %}"/>
</form>
</div>
</div>
{% endblock %}

two-dimensional array Django

I have a two-dimension array in my django app which I need to pass to html template.
How I can make HTML handle two-dimensional array?
{% block content %}
<h2>Survey</h2>
<form>
{% for q in question %}
<p>{{q[0]}}</p>
<p>{{q[1]}}</p>
{% endfor %}
<input type="submit" value="submit">
</form>
{% endblock %}
I got error:
Could not parse the remainder: '[0]' from 'q[0]'
{% block content %}
<h2>Survey</h2>
<form>
{% for q in question %}
<p>{{q.0}}</p>
<p>{{q.1}}</p>
{% endfor %}
<input type="submit" value="submit">
</form>
{% endblock %}
Django just doesn't have a pre-setup way for passing multi-dimensional arrays to templates.
The best work-around is to separate the columns out manually like so... ("i" corresponds to each row in final output)
data = {}
for i, question_answer in enumerate(question_answer_pairs):
data[i]= {
'question':question_answer.question,
'answer':question_answer.answer
}
return render(request, 'survey.html', data)
Then in your template
{% block content %}
<h2>Survey</h2>
<form>
{% for key,value in data.items %}
<p>{{value.question}}</p>
<p>{{value.answer}}</p>
{% endfor %}
<input type="submit" value="submit">
</form>
{% endblock %}

Categories

Resources