How can i receive variables from django-template? - python

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>

Related

LIKE button in a Django project

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.

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

Django - How to delete an article?

I'm trying to create a button on the framework django that let me delete my own article on my blog. I tried to create a code for this functionality, but it doesn't work.
views.py
if(request.GET.get('delete')): #if the button is clicked
delete_article = get_object_or_404(Article, id=id)
if request.POST:
form = DeleteNewForm(request.POST, request.FILES)
if form.is_valid():
delete_article.delete()
return HttpResponseRedirect("/")
template.html
<form enctype='multipart/form-data' action="." method="post" class="form" autocomplete="off" autocorrect="off">
{% csrf_token %}
<div class="form-group">TITRE
{{ form.title.errors }}
{{ form.title }}
</div>
<div class="form-group">CONTENU
{{ form.media }}
{{ form.contenu.errors }}
{{ form.contenu }}
</div>
<div class="form-group">
{{ form.image.errors }}
{{ form.image }}
</div>
<input type="submit" class="btn btn-default" value="Edit Article"/>
<input type="submit" class="btn btn-default" value="Delete Article" name="delete">
</form>
Here is what happen when I submit the form : I am not redirected on the index as it should redirect me and the article has not been deleted.
Is there a problem which don't let me delete my article in these lines?
I have no idea what you're doing in your views or in your template. But if I want to delete something, I just define a separate view for that.
# views.py
from django.views.generic.base import View
class DeleteView(View):
def post(self, request *args, **kwargs):
article = get_object_or_404(id=request.POST['article_id'])
# perform some validation,
# like can this user delete this article or not, etc.
# if validation is successful, delete the article
article.delete()
return HttpResponseRedirect('/')
Your template should be like this:
<form action="/url/to/delete/view/" method="POST">
{% csrf_token %}
<input type="hidden" value="{{ article.id }}">
<input type="submit" value="Delete">
</form>

django message framework not show messages

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 !

Django login/logout

I'm trying to create a login and logout page with django. The problem I have is that when I submit the form, it doesn't go the url which I specified. When I click the login button, I want it to go to http://127.0.0.1:8000/home/ but instead, it goes to http://127.0.0.1:8000/?next=/home/.
Below is my login/logout code in my view.py:
def login(request):
def errorHandler(error):
return render_to_response('login.html', {'error' : error})
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username = username, password = password)
if user is not None:
if user.is_active:
authLogin(request, user)
fullName = user.get_full_name
return render_to_response('logged_in.html', {'full_name': fullName})
else:
error = 'Account disabled.'
return errorHandler(error)
else:
error = 'Invalid details entered.'
return errorHandler(error)
return render_to_response('login.html')
#login_required
def logout(request):
authLogout(request)
return render_to_response('logged_in.html')
my login.html:
{% extends "base.html" %}
{% block content %}
{% if error %}
<p><b><font color="red">Error: </font></b>{{ error }}</p>
{% endif %}
<form action="/home/" method="post">
<label for="username">User name:</label>
<input type="text" name="username" value="" id="username">
<label for="password">Password:</label>
<input type="password" name="password" value="" id="password">
<input type="submit" value="Login" />
<input type="hidden" name="next" value="{{ next|escape }}" />
</form>
{% endblock %}
my logged_in.html:
{% extends "base.html" %}
{% block name %}{{ full_name }} is {% endblock %}
{% block content %}
<p><a href='/'>Logout</a></p>
{% endblock %}
url:
(r'^$', 'myapp.views.login'),
(r'^home/$', 'myapp.views.logout'),
Please help
The problem is that you don't actually login the user, the form sends unauthenticated user to /home/, which can't process, because it requires login. :-) So it redirects user to login view, storing the destination in next parameter.
Solution:
<form action="" method="post">
maybe you should try to remove hidden input with name="next"
http://docs.djangoproject.com/en/1.2/topics/auth/#django.contrib.auth.views.login

Categories