How to compare django object and string in templates - python

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.

Related

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?

How do I use request.user in template

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

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.

Django and Jinja2 randomize form fields display

I have the following situation:
forms.py
REASONS = [
{'code': 1, 'reason': 'I want to unsubscribe'},
{'code': 2, 'reason': 'I hate this site'}]
Myform(forms.Form):
magic_field = forms.CharField(required=True)
def __init__(self):
# Depending on the REASONS list add the fields to the form
for key in REASONS:
self.fields['reason_{}'.format(key['code'])] = forms.BooleanField(
label=_(key['reason']),
widget=widgets.CheckboxInput())
What I want is to have the order the reasons rendered in randomized order.
template.html
<form method="POST" action="{% url unsubscribe %}">
{% if some_event %}
{{ form.magic_field }}
{% endif %}
{{ form.reason_1 }} # <-- randomize this order
{{ form.reason_2 }} # <-- randomize this order
</form>
why dont you shuffle the REASONS first and then use a {% for %} loop in the template?
Something like:
REASONS = [
{'code': 1, 'reason': 'I want to unsubscribe'},
{'code': 2, 'reason': 'I hate this site'}]
Myform(forms.Form):
def __init__(self):
random.shuffle(REASONS) # use some magic method to shuffle here
for key in REASONS:
...
<form method="POST" action="{% url unsubscribe %}">
{% for field in form %} #cf https://docs.djangoproject.com/en/dev/topics/forms/#looping-over-the-form-s-fields
{{ field }}
{% endfor %}
</form>
Hope this helps
Edit
You could create a filter or a function (i'd use a function) something like
{% if some_event %}
{{ form.magic_field }}
{% endif %}
{% for field in form %}
{% if is_reason_field(field) %}
{{ field }}
{% endif %}
{% endfor %}
on your helpers.py something like: (I don't know how exactly do this)
#register.function
def is_reason_field(field):
# i'm not sure if field.name exists, you should inspect the field attributes
return field.name.startswith("reason_"):
hmm now that I see it, you could do this directly in the template since you are using jinja2

Unable to retrieve user information from django templates

i want to use loged in user information in my base template
{% if request.user.username %}
Logout
{% else %}
Login
{% endif %}
from django.template import RequestContext
def top(request):
return render_to_response('top.html',{}, context_instance=RequestContext(request))
If you're just wanting to check if they're logged in to display the login or logout links, I would use is_authenticated instead
{% if user.is_authenticated %}
Logout
{% else %}
Login
{% endif %}
If you are wanting to use information from the user, you can use the variables in the user class {{ user.username }}
{% if user.is_authenticated %}
Hi, {{ user.first_name }}, Logout
{% else %}
Login
{% endif %}
I use code with this structure in my base.html and it works well. I don't have anything in the template_content_processor - it works in the template on its own.

Categories

Resources