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
})
Related
There is a view in the Django project (a paginated blog) that is responsible for how likes work. It has one drawback: when a user likes a post, it is redirected to the main page of the site. How can I fix this so that the user would remain on the page where they liked.
views.py
class AddLikeView(View):
def post(self, request, *args, **kwargs):
blog_post_id = int(request.POST.get('blog_post_id'))
user_id = int(request.POST.get('user_id'))
url_from = request.POST.get('url_from')
user_inst = User.objects.get(id=user_id)
blog_post_inst = News.objects.get(id=blog_post_id)
try:
blog_like_inst = BlogLikes.objects.get(blog_post=blog_post_inst, liked_by=user_inst)
except Exception as e:
blog_like = BlogLikes(blog_post=blog_post_inst,
liked_by=user_inst,
like=True)
blog_like.save()
return redirect(url_from)
template.py
<form action="{% if not is_liked_bool %}{% url 'add' %}{% else %}{% url 'remove' %}{% endif %}" method="post">
{% csrf_token %}
<input type="hidden" name="blog_post_id" value="{{ blog_post_id }}">
<input type="hidden" name="user_id" value="{% if user.is_authenticated %}{{ request.user.id }}{% else %}None{% endif %}">
<input type="hidden" name="url_from" value="{{ request.path }}">
{% if is_liked_bool %}
<input type="hidden" name="blog_likes_id" value="{{ blog_likes_id }}">
{% endif %}
<button type="submit" class="btn btn-success">
{% if not is_liked_bool %}
<i class="fi-xnluxl-heart">♥</i>
{% else %}
<i class="fi-xnluxl-heart-solid">♥</i>
{% endif %}
<span class="likes-qty">{{ likes_counter }}</span>
</button>
I think you should check the url_from field first. Just print it and if it's wrong, you should change the {{request.path}} field in your template.
You can try this:
{{ request.get_full_path }}
And also if I remember correctly, you can access the path with request.path in your view and no need to send path via template.
I want to receive variable value in my python code from django-template.
I have two button Yes and No. When I click one of buttons, my python code must receive this django variables and check True or False. But I can`t find information how to take these variables. Here is my html code :
{% with word=words|random %}
<h1>{{ word }}</h1>
<h1>{{ word.word_ru }}</h1>
<form method="POST">
{% csrf_token %}
<input type="submit" value="no" name="Answer" >
<input type="submit" value="yes" name="Answer" >
{% endwith %}
This my python-code:
def index(request):
if request.method == "POST" and request.POST.get("Answer") == 'no':
return render(request, "training/training.html", {})
else:
return render(request, "training/training.html", {})
You could rewrite your code like this:
# template file
{% with word=words|random %}
<h1>{{ word }}</h1>
<h1>{{ word.word_ru }}</h1>
<form method="POST">
{% csrf_token %}
<input type="submit" value="no" name="answer_yes" >
<input type="submit" value="yes" name="answer_no" >
{% endwith %}
And you views.py file:
# views file
def index(request):
if 'answer_yes' in request.POST:
my_answer = request.POST.get('answer_yes')
return render(request, "training/training.html", {'Answer': my_answer})
elif 'answer_no' in request.POST:
my_answer = request.POST.get('answer_no')
return render(request, "training/training.html", {'Answer': my_answer})
It should work but I didn't test it.
EDIT:
You could hide your variable like this:
<input type="hidden" value={{ word }} name="word" >
Then, get the variable value from this command:
if request.POST:
my_answer = request.POST.get('word')
as follows
def test_view(request):
answer = True if request.POST.get("Answer") == "yes" else False
Send the word variable by input type hidden or send by ajax.
If I understand correctly, you want to send variable word to your view? Button value is working fine?
<form method="POST">
{% csrf_token %}
<input type="submit" value="no" name="Answer" >
<input type="submit" value="yes" name="Answer" >
<input type="hidden" value={{word}} name="word" >
</form>
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 %}
I write a message board,When user leave message and success back to the page
I want to alert('Thank you') to let user know it's success.
But the message didn't show
I add this in my setting ,still not work
TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.messages.context_processors.messages",)
Please help me ,Thank you .
views.py
def maininfo(request):
return render(request, 'zh_tw/maininfo.html',)
def create_post(request):
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
form.save()
messages.success(request,'Thank you')
return HttpResponseRedirect('/maininfo/#5thPage')
return render(request, "zh_tw/maininfo.html",{'form': form,'anchor':'#5thPage'})
urls.py
urlpatterns = patterns('',url(r'^maininfo/$', views.maininfo, name='maininfo'),)
template: zh_tw/contact.html
(this is an anchor page included by zh_tw/maininfo.html)
{% if messages %}
{% for message in messages %}
<p{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</p>
{% endfor %}
{% endif %}
<form action="{% url 'core:create_post' %}" method="POST" id="create_post">
{% csrf_token %}
{% if not form %}
<div>
<input type="text" name="name" id="name" placeholder="你的名字">
<input type="text" name="email" id="email" placeholder="你的電子信箱">
</div>
<textarea placeholder="你想說的話" name = "message" id="message"></textarea>
<br>
<button type="submit" value="Submit" id="submit">送出</button>
{% endif %}
{% if form %}
{% if form.errors %}
<div>
<span style="color:red ; font-weight:bold">
{{ form.name.errors }} {{ form.email.errors }} {{ form.message.errors }} </span>
<input type="text" name="name" id="name" placeholder="你的名字" value="{{form.name.value }}" >
<input type="text" name="email" id="email" placeholder="你的電子信箱" value="{{form.email.value}}">
</div>
<textarea placeholder="你想說的話" name = "message" id="message">{{form.message.value}}</textarea>
<br>
<button type="submit" value="Submit" id="submit">送出</button>
{% endif %}
{% endif %}
</form>
You have to add the same message block in the redirection page, return HttpResponseRedirect('/maininfo/#5thPage')
the message will be displayed normaly !
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>