How do I use request.user in template - python

I am trying display different text to user on an empty tag. I was able to implement this correctly in other template, but I do not clearly understand why it is not displaying correctly in another template. For example, if user A login, I want only user A to see 'Find people to follow' , while other users to see 'No users'.
def following_view(request, username):
p = FriendRequest.objects.filter(from_user__username=username)
all_profile_user=[]
button_status_list=[]
for user_obj in p:
u = user_obj.to_user
all_profile_user.append(u)
friend = Profile.objects.filter(user=request.user, friends__id=user_obj.id).exists()
button_status = 'none'
if not friends:
button_status = 'not_friend'
if len(FriendRequest.objects.filter(from_user=request.user).filter(to_user=u)) == 1:
button_status = 'cancel_request_sent'
button_status_list.append(button_status)
context={'profile_and_button_status':zip(p, button_status_list), 'u':all_profile_user, 'following':p,}
{% for data in profile_and_button_status %}
#Button codes here
{% empty %}
#why this doesn't display
{% if data.user != request.user %}
No users
{% endif %}
{% if data.user == request.user %}
Find people to follow
{% endif %}
{% endfor %}

You can try like this:
{% for friend_request, status in profile_and_button_status %}
#Button codes here
#why this doesn't display
{% if friend_request.to_user != user %}
No users
{% else %}
Find people to follow
{% empty %}
No users
{% endfor %}
But I would suggest a better approach, which is to calculate these in views instead of template. Like this:
from django.db.models import Case, When, Value, CharField, F
def following_view(request, username):
friend_requests = FriendRequest.objects.filter(
from_user__username=username
).annotate(
button_status=Case(
When(to_user__in=request.user.profile.friends.all(), then=Value('none')),
When(
from_user=request.user, to_user=F('to_user'),
then=Value('cancel_request_sent')
),
default=Value('not_friend'),
output_field=CharField()
)
)
return render(request, 'template.html',context={'friend_requests':friend_requests})
# template
{% for friend_request in friend_requests %}
{{ friend_request.button_status }}
{% empty %}
No users
{% endfor %}
I am using conditional expression here.
Update(based on comments)
It should be simple. You should send data if request.user.username and username is same. For example:
# view
context={'checking_own_friend_list': request.user.username == username,... # rest of the contexts
# template
{% for data in profile_and_button_status %}
{% empty %}
{% if checking_own_friend_list %}
Find people to follow
{% else %}
No user
{% endfor %}

You are using a for loop instead of an if statement. It should be
{% for data in profile_and_button_status %}
# Button codes here
{% empty %}
# why this doesn't display
{% if data.user != request.user %}
No users
{% endif %}
{% if data.user == request.user %}
Find people to follow
{% endif%}
{% endfor %}

Related

If else condition error in django template

I write a simple django condition but it not working
{% if request.user == "sami" %}
sami
{% else %}
khan
{% endif %}
Requset.user is an object.
You need to write
{% if request.user.username == "sami" %}
or
{% if request.user.name == "sami" %} whatever is in your model

django regroup with duplicate nametuple

I have code for regroup in django template, like below:
{% regroup clients by title.0 as clients_list %}
{% for client in clients_list %}
{{ client.grouper }}
{% for item in client.list %}
{% if item.client_link %}
{{ item.title }}
{% else %}
{{ item.title }}
{% endif %}
{% endfor %}
{% endfor %}
Sometime I have duplicate nametuple in my results for the same letter, for example - 'd':
GroupedResult(grouper='d', list=[<Client: decompany_1>]) GroupedResult(grouper='d', list=[<Client: decompany_2>])
so in result I have two headers with letter 'd'
Someone know, how to avoid this?
edit
views.py
class ClientsListView(ListView):
model = Client
template_name = 'clients/clients_list.html'
context_object_name = 'clients'

Django plain-text email template generates \n after template tags

Interesting issue here: I have plain-text emails sent by my Django app, with the following code:
email_context = dict()
email_context['to'] = user.display_name
email_context['new'] = user_data['new']
email_context['for_reminder'] = user_data['for_reminder']
plaintext = get_template('email/notification.txt')
text_content = plaintext.render_to_string(email_context)
html = get_template('email/notification.html')
html_content = html.render(email_context)
email = EmailMultiAlternatives(
subject='Assignments',
body=text_content,
to=[user.email],
reply_to=[settings.DEFAULT_FROM_EMAIL],
)
# email.attach_alternative(html_content, "text/html")
email.send()
the 'email/notification_base.txt' template looks like such:
Dear {{ to }},
{% if new %}
You have been assigned to the following NEW cases:
{% block new %}
{% endblock %}
{% endif %}
{% if for_reminder %}
You still have the following previously assigned cases, which need your attention:
{% block for_reminder %}
{% endblock %}
{% endif %}
Thank you for your assistance.
Sincerely,
The Team
the 'email/notification.txt' template just extends base:
{% extends 'email/notification_base.txt' %}
{% load common_tags %}
{% load common_filters %}
{% block new %}
{% for dispute in new %}
Case #: {{ dispute.case_id.no}}
Assignment date: {{ dispute.assignment_date }}
{% endfor %}
{% endblock %}
{% block for_reminder %}
{% for dispute in for_reminder %}
Case #: {{ dispute.case_id.no }}
Assignment date: {{ dispute.assignment_date }}
{% endfor %}
{% endblock %}
My problem with it is, that the email it generates and sends to the addressee, actually gets rendered with a NEWLINE in every spot where the template had {% something %} tags. This results in a very unevenly formatted email text. As an example, if both blocks were missing the email would look like:
Dear Someone,
Thank you for your assistance.
Sincerely,
The Team
Are there any ways around this problem?

trying to let users add new topics to page, but page only returns the bullet points, NO topic names. works fine in admin backend but defeats purpose

Working thru my 1st python/Django project. Need to let users add new topics to a blog page, but page only returns the bullet points, NO topic names. Works fine on admin back end which of course defeats purpose of user entry"
{% extends 'blog/base.html' %}
{% block content %}
<p>Add a new topic:</p>
<form action="{% url 'blog:new_topic' %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name='submit'>add topic</button>
</form>
{% endblock content %}
```
```
{% extends 'blog/base.html' %}
{% block content %}
<p>BlogPosts</p>
<ul>
{% for topic in blogposts %}
<li>
{{ topic }}
</li>
{% empty %}
<li>Nothing's yet been posted</li>
{% endfor %}
</ul>
Add a new topic:
{% endblock content %}
````
{% extends 'blog/base.html' %}
{% block content %}
<p>Topic: {{ topic }}</p>
<p>Entries:</p>
<ul>
{% for entry in entries %}
<li>
<p>{{ entry.date_added|date:'M d, Y H:i' }}</p>
<p>{{ entry.text|linebreaks }}</p>
</li>
{% empty %}
<li>
There are no entries for this post yet.
</li>
{% endfor %}
</ul>
{% endblock content %}
````
Here are the views:
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponseRedirect
from django.urls import reverse
from .models import BlogPost
from .forms import BlogPostForm
def index(request):
"""The home page for Road Ahead project."""
return render(request, 'blog/index.html')
def blogposts(request):
"""Show all blogposts (in reverse order)."""
blogposts = BlogPost.objects.order_by('-date_added')
context = {'blogposts': blogposts}
return render(request, 'blog/blogposts.html', context)
def topic(request, topic_id):
"""Show a single post and all its entries."""
topic = BlogPost.objects.get(id=topic_id)
entries = topic.entry_set.order_by('date_added')
context = {'topic': topic, 'entries': entries}
return render(request, 'blog/topic.html', context)
def new_topic(request):
"""Add a new topic."""
if request.method != 'POST':
# No data submitted; create a new blank form.
form = BlogPostForm()
else:
# Post data submitted; process data.
form = BlogPostForm(data=request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('blog:blogposts'))
context = {'form': form}
return render(request, 'blog/new_topic.html', context)
````
{% extends 'blog/base.html' %}
{% block content %}
<p>Topic: {{ topic }}</p>
<p>Entries:</p>
<ul>
{% for entry in entries %}
<li>
<p>{{ entry.date_added|date:'M d, Y H:i' }}</p>
<p>{{ entry.text|linebreaks }}</p>
</li>
{% empty %}
<li>
There are no entries for this post yet.
</li>
{% endfor %}
</ul>
{% endblock content %}
Besides the index and base=parent html pages, I have 3 other pages all copied above: blogposts, which lists all bulleted blog topics, topic, which displays topic name and entries, new_topic, which is supposed to allow user topic entry. New_topic appears to be the issue here-I can enter a new topic, and I've not gotten any error messages to troubleshoot, but all I get are bullet points, no topic name. Again it's possible to add topics and content on the back end; not what I want though. Thanks
What is your question, exactly?
Because as it stands, it looks like you're just trying to get us to do your programming for you.

How to compare django object and string in templates

i want to know how to compare an object with a string in templates. Do in need to do it in views.py or in my html templates.
my views.py
permission = permission_group_sas.objects.all()
context_dict = {
'permission':permission,
# 'groups':groups,
}
return render_to_response(template, RequestContext(request, context_dict))
my html
{% for user in user.groups.all %}
{% for value in permission %}
<h4>1. {{ user.name }}
<p>2. {{ value.group }}</p></h4>
{% if value.group == user.name %}
OK!!
{% endif%}
{% endfor %}
{% endfor %}
value.group is an object and user.name is a string. So the word OK!! does not appear in my screen What is the correct way to do it. Thank you.

Categories

Resources