How is this code supposed to be indented? - python

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 %}

Related

Can't figure out the error on my jinja2/django template

Here is my template, the if statements aren't working!
{% extends "auctions/layout.html" %}
{% block body %}
{% if bid.name == User %}
<br>
<h1>You Won the auction</h1>
<br>
{% endif %}
<h1>Title: {{title}}</h1>
<br>
<h1>Seller: {{listing.name}}</h1>
<br>
<h1>Description: {{listing.description}}</h1>
<br>
<h1>Category: {{listing.category}}</h1>
<br>
<h1>price: {{bid.price}} by {{bid.name}}</h1>
<br>
<form action="{% url 'Bid' %}" method="post">
{% csrf_token %}
<input type="hidden" name="title" value="{{title}}">
<input type="number" name="price">
<input type="submit">
</form>
<form action="{% url 'watchlist'%}" method="post">
{ % csrf_token %}
Add to watchlist
<input type="hidden" name="form_type" value="Watchlist">
<input type="hidden" name="title" value="{{title}}">
<input type="submit">
</form>
{% if User == "ilias" %}
<br>
<h1>Close the auction</h1>
<br>
<form action="{% url 'close' %}" method="post">
{% csrf_token %}
<input type="hidden" name="title" value="{{title}}">
<input type="submit">
</form>
<br>
{% endif %}
<form action="{% url 'comment'%}" method="post">
{% csrf_token %}
<h1>Add comment</h1>
<input type="text" name="content">
<input type="hidden" name="title" value="{{title}}">
<input type="submit">
</form>
{%for item in comments%}
<h3>{{item.content}} by {{item.name}}</h3>
<br>
{%endfor%}
{% endblock %}
Here is my views.py
def listings(request, title):
try:
listing = Listing.objects.get(title=title)
except:
return HttpResponse('<h3>Page not found</h3>')
else:
title = listing.title
name = listing.name
comments = comment.objects.filter(title=title)
bid = Bid.objects.get(title=title)
User = request.user.username
print name
return render(request, 'auctions/listing.html', {
'listing': listing,
'title': title,
'comments': comments,
'bid': bid,
'User': User,
'name': name,
})
I can't figure out where is the error. How can I fix this error and how to avoid this types of errors? Django version: Django 3.1.1, Python version: Python 3.8.5
If you need more information ask me in the comments!
It doesn't show the content of the if statements! I don't know why. The views is properly sending data it checked it!
Fixed the error just needed to make them both strings
def listings(request, title):
try:
listing = Listing.objects.get(title=title)
except:
return HttpResponse('<h3>Page not found</h3>')
else:
title = listing.title
name = str(listing.name)
comments = comment.objects.filter(title=title)
bid = Bid.objects.get(title=title)
User = str(request.user.username)
bidder = str(bid.name)
print(name)
return render(request, "auctions/listing.html", {
"listing":listing,
"title":title,
"comments":comments,
"bid":bid,
"User":User,
"name":name,
"bidder":bidder
})

'csrf_tokan', expected 'endblock'. Did you forget to register or load this tag?

{%extends 'base.html'%}
{% block content%}
<h1>hellow {{name}}</h1>
<form action="add" method='post'>
{% csrf_tokan %}
Enter 1st number : <input type="text" name="num1"><br>
Enter 2nd number : <input type="text" name="num2"><br>
<input type="submit">
</form>
{% endblock%}
It is csrf_token not csrf_tokan. So replace {% csrf_tokan %} with {% csrf_token %}

Django template pass array to input field

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>

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>

Getting from POST in included .html page in Django

I am trying to get the POST values of an .html page that has included pages via {% include %} in Django. However, it returns only the POST from the initial html page.
My inner html that is included has the snippet of code:
div id="edit_parameters">Edit Parameters</div>
<div data-id="{{job.slug}}" id="{{job.slug}}" class="collapse">
<form class = "form-inline" method="post">
{% csrf_token %}
{% for parameter in job.get_object.parameters %}
<p>
<input type="text" class="input-small" name="{{parameter}}" value="" id ="{{parameter}}-input" placeholder="{{parameter}}">
</p>
{% endfor %}
<button type="submit" class="btn btn-primary run-job">Submit</button>
</form>
</div>
{% else %}
<div>
No editable parameters for this job.
</div>
{% endif %}
And my outer HTML file has a snippet:
<ul id="available-jobs">
{% if jobs_same_io_type and jobs_diff_io_type %}<h3> Current Step </h3>
{% elif jobs_same_io_type %} <h3> Next Step </h3> {% endif %}
{% for job in jobs_same_io_type %}
{% include "includes/job_li.html" with add=1 %}
{% endfor %}
{% if jobs_diff_io_type %} <h3> Next Step </h3> {% endif %}
{% for job in jobs_diff_io_type %}
{% include "includes/job_li.html" with add=1 %}
{% endfor %}
{% if not jobs_same_io_type and not jobs_diff_io_type %}
<li class="full-height">There are no more available jobs.</li>
{% endif %}
</ul>
<fieldset class="submit">
{% csrf_token %}
<input type="hidden" name="job_to_run" value="" id="job-to-run" />
<input type="hidden" name="workflow_jobs" value="" id="ordered-jobs" />
<input type="hidden" name="job_to_edit" value="" id="job-to-edit" />
<input type="hidden" name="job_to_add" value="" id="job-to-add" />
<input type="hidden" name="job_to_remove" value="" id="job-to-remove" />
<input type="submit" name="done" value="I'm done, start the jobs" id="jobs-ready" />
</fieldset>
The everything that shows in post is in the inputs of the second snippet. But the parameters I want for the first snippet are not included when I use request.POST for all of the POST values.
Any help would be greatly appreciated in explaining why I am not getting the values from the included page and finding a possible solution. Thanks!
In HTML, only the fields in the form element that contain the submit button are included in the POST. the fields in your second file don't seem to be in any form at all, so they will never be posted.

Categories