Django template pass array to input field - python

I have a hidden input field in my django template where I'm passing as value an array.
<form method="post" action="{% url 'flights:flight-selection' %}">{% csrf_token %}
<input type="hidden" id="fa_f_ids" name="fa_f_ids" value="{{ value.fa_f_ids }}">
<button type="submit" class="btn btn-light">Select</button>
</form>
When I submit this form via post request I want to get the value of fa_f_ids as an array but I am getting a string instead when I'd like to get an array.
request.POST.get("fa_flight_id")
#=> <QueryDict: {'csrfmiddlewaretoken': ['UoYqbTUlNxTEJW5AUEfgsgsLuG63dUsvX88DkwGLUJfbnwJdvcfsFhi75yie5uMX'], 'fa_f_ids': ["['AMX401-1560750900-schedule-0000', 'AMX19-1560782100-schedule-0001']"]}>

You need to split the array into several hidden fields, each representing one position of your array:
<form method="post" action="{% url 'flights:flight-selection' %}">
{% csrf_token %}
{% for val in value.fa_f_ids %}
<input type="hidden" name="fa_f_ids[{{ forloop.counter0 }}]" value="{{ val }}">
{% endfor %}
<button type="submit" class="btn btn-light">Select</button>
</form>

Related

Getting None instead of Value from HTML form (Django)

Here below my HTML-template
<form action="{% url 'test-data' %}" method="POST" name="test" enctype="multipart/form-data">
{% csrf_token %}
<h2>
{{ result }}
</h2>
<div class="d-flex justify-content-center">
<button type="submit" class="btn btn-primary">Show</button>
</div>
</form>
my View.py
def show_result(request):
if request.method == "POST":
result = request.POST.get('test')
return HttpResponse(result)
By pressing the button 'Show' I got None instead of {{ result }} value.
So, how I can get a Value inside curly brackets?
Thanks a lot for any help.
In order to submit the data, they need to be values of form elements like input, textarea, select options...
You can choose the right type for the input field. You can make use of the hidden field type to submit data that will not be displayed to the client...
You probably do not need to use the heading inside the form.
<h2>{{ result }}</h2>
<form action="{% url 'test-data' %}" method="POST" name="test" enctype="multipart/form-data">
{% csrf_token %}
<div class="d-flex justify-content-center">
<input type="hidden" name="result_field" value="{{ result }}" />
<button type="submit" class="btn btn-primary">Show</button>
</div>
</form>
On the backend, you can retrieve the data as follow:
result = request.POST.get('result_field')
I hope that works for you.

Django multiple radio input from HTML form with same name

I am having a problem with Django forms. I am currently using the request.POST to validate the POST within views.
I want to send inputed-data(radio type) from my template with the same name.
In my template.py:
<form method="post" action="{% url 'app:AnsSubmission' %}">
{% csrf_token %}
{% for i in Exam %}
<div class="form-group col-xl-12">
<label>{{ i.question }}</label>
<div class="radio">
<label><input type="radio" class="mx-2" name="givenAns" array_column="{{ i.pk }} value="True" required>True</label>
</div>
<div class="radio">
<label><input type="radio" class="mx-2" name="givenAns" array_column="{{ i.pk }} value="False" required>False</label>
</div>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
And willing to fetch these data in views.py like:
givenAns_list = request.POST.getlist('givenAns')
for i in givenAns_list:
this_givenAns = givenAns_list[i]
But the problem here is this radio type input field doesn't take value for the same name(not as a list I wish). If I select answer of 2nd question, the 1st one's selection is unselected.
Please suggest how can I fix this?

How to get the data from HTML field to the view.py in django(HTML field is iterating)

I have an app which reads the questions from database and display them .I need to enter the response to it and save it back in the database.Is it possible to do it without using forms
My HTML section
<form id="survey" method="post" action="/Survey/restricted/" class="form col-md-12 center-block">
{% csrf_token %}
{% for b in obj1 %}
<textarea class="form-control">{{b.question}}</textarea>
<textarea class="form-control" rows="3" name="response1" width="100%;">{{b.response}}</textarea>
{% endfor %}
<input type="submit" name="submit" class="btn btn-success" value="Submit Response" />
</form>
I tried to access the data after entering the response and submitting using
res=request.POST.get('response1')
but it returns none
You should move the response1 field outside the loop, but then it should be passed as a separate field (e.g. response), not as part of the obj1 list of questions (or not passed at all if keeping the previous answer is unnecessary).
<form id="survey" method="post" action="/Survey/restricted/" class="form col-md-12 center-block">
{% csrf_token %}
{% for b in obj1 %}
<textarea class="form-control">{{b.question}}</textarea>
{% endfor %}
<textarea class="form-control" rows="3" name="response1" width="100%;">{{response}}</textarea>
<input type="submit" name="submit" class="btn btn-success" value="Submit Response" />
</form>
Also, I think the questions should not be editable (i.e. disabled, or not a textarea altogether)

How is this code supposed to be indented?

I'm learning django and python and I want to know how to indent this code properly. How should it be done?
{% block content %}
<h2>Nyinkommet</h2>
{% if request.GET.sorting == 'desc' %}
<form method="get" action=".">
<input type="hidden" name="sorting" value="asc">
<input type="submit" value="Visa äldsta ärende först">
</form>
{% else %}
<form method="get" action=".">
<input type="hidden" name="sorting" value="desc">
<input type="submit" value="Visa nyaste ärende först">
</form>
{% endif %}
You could use the template tags {{ sortvalue }} to check the value and set the specific attribute value.
You could achieve it somewhere as:
my_template.html
{% block content %}
<h2>Nyinkommet</h2>
<form method="post" action="/postingUrl">
<input type="hidden" name="sorting" value="{{ sortvalue }}">
<input type="submit" value="Visa äldsta ärende först">
</form>
{% endblock %}
Pass the sortvalue in the rendering of template:
The view that returns "my_template.html":
def get_home_page(request):
sortvalue = "asc" # Calculate what value you want, (asc or desc)
return render_to_response('my_template.html',
{ 'sortvalue' : sortvalue },
context_instance=RequestContext(request))
Code indentation comes down to personal preference. As long as your code is readable it is up to you and those you work with; do what you want.
For ideas and general good practises you should look through the django documentation. It is contributed to by x00's of developers and will give you a good idea of formatting and best practices.
Personally I would indent the elements inside the forms. I also try to keep all HTML dom elements at the same nesting level as their siblings even when using django template operations.
{% block content %}
<h2>Nyinkommet</h2>
{% if request.GET.sorting == 'desc' %}
<form method="get" action=".">
<input type="hidden" name="sorting" value="asc">
<input type="submit" value="Visa äldsta ärende först">
</form>
{% else %}
<form method="get" action=".">
<input type="hidden" name="sorting" value="desc">
<input type="submit" value="Visa nyaste ärende först">
</form>
{% endif %}
One small improvement you could make to the code is the following:
{% block content %}
<h2>Nyinkommet</h2>
<form method="get" action=".">
{% if request.GET.sorting == 'desc' %}
<input type="hidden" name="sorting" value="asc">
{% else %}
<input type="hidden" name="sorting" value="desc">
{% endif %}
<input type="submit" value="Visa äldsta ärende först">
</form>
{% endblock content %}

Flask-Social on a CSRF enabled website

I'm trying to implement login/registration views in Flask that support both regular login (through Flask-Security) and OAuth login (through Flask-Social).
My website uses CSRF protection, but when I implement a link to the OAuth login page (as per the Flask-Social example project) I get a CSRF error. Here is the template:
{% extends "base.html" %}
{% from "security/_macros.html" import render_field_with_errors, render_field %}
{% block title %}Login{% endblock %}
{% block body %}
<h1>Login</h1>
{% include "security/_messages.html" %}
<form action="{{ url_for_security('login') }}" method="POST"
name="login_user_form">
{{ login_user_form.hidden_tag() }}
{{ render_field_with_errors(login_user_form.email,
class="form-control", placeholder="Your email") }}
{{ render_field_with_errors(login_user_form.password,
class="form-control", placeholder="Password") }}
{{ render_field(login_user_form.remember) }}
{{ render_field(login_user_form.next) }}
{{ render_field(login_user_form.submit, class="btn btn-primary") }}
</form>
<form action="{{ url_for('social.login', provider_id='google') }}"
name='google_login_form' method="POST">
<input class="btn btn-primary btn-large" type="submit"
name="login_google" value="Login with Google" >
</form>
{% include "security/_menu.html" %}
{% endblock %}
The problem seems to be that the second form does not have a CSRF field; what can I do about this?
You should follow the Flask-WTF docs on using templates without forms.
As per the docs, in the app
from flask_wtf.csrf import CsrfProtect
CsrfProtect(app)
and in the template
<form method="post" action="/">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
</form>
Your second form would be
<form action="{{ url_for('social.login', provider_id='google') }}"
name='google_login_form' method="POST">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
<input class="btn btn-primary btn-large" type="submit"
name="login_google" value="Login with Google" >
</form>

Categories