Checking if a user is the author - python

It seems logic that any author of an article, can delete his own post. But I don't really know how to check if a user is the current author of a post.
Here is my code :
{% extends 'base.html' %}
{% block title %} Details | {{article.title}} {% endblock title %}
{% block content %}
<div class="starter-template" style="text-align: center; margin: 2% 0">
<h1>{{object.title.capitalize}}</h1>
<p>{{object.body}}</p>
<p style="font-style: italic">{{object.author}}</p>
<p>{{object.date}}</p>
{% if object.author == user.username %}
<p>
Delete
Edit
</p>
{% endif %}
</div>
{% endblock content %}
"object.author == user.username " is returning False. Why is that ?
Thanks :)

You can check like below. Please add your models to view relations.
{% object.author.user == user %}

{% if object.author == user %}

Related

Python Django {% if usuario.username == user %} not work :(

I need some help.
I want to list all user avoid the login user.
if I print user= juan
if I print usuario.username=juan
There have the same string
{% if usuario.username == user %}
Nothing
{% else %}
<tr><td>
{{usuario.username}}
<img src="{% static 'assets/img/icono_writeMSJ.png' %}" height="30px">
</td>
</tr>
{% endif %}
if i change for example
{% if usuario.username == 'juan' %}
Nothing
{% else %}
<tr><td>
{{usuario.username}}
<img src="{% static 'assets/img/icono_writeMSJ.png' %}" height="30px">
</td>
</tr>
{% endif %}
this work fine, why?? :(
user is an object. Stringify it. That should work
{% if usuario.username == user|stringformat:"s" %}
======== excluded current logged-in user ========
========= in HTML ==============
<h3>All Users list</h3>
{% if user.is_authenticated %}
<ul>
{% for i in all_users %}
<li>{{i.username}}</li>
{% endfor %}
</ul>
{% else %}
<h4>Please login first</h4>
======= in views.py ===========
def HomeView(request):
all_users = User.objects.all().exclude(id=request.user.id).values('username')
return render(request,'index.html',{'all_users':all_users})
Finally, the problem was that user is an objet. For that reason a can't compare from that way.
{% if usuario.username == user %}
the correct way is
{% if usuario.username == user.username %}

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?

adding form styling to django forms

I am currently in the process of adding a theme to the admin of django one issue I have found it adding styling to the forms is that it is very difficult and I can't find much useful documentation on it. The only real thing I need to do is add classes to the form elements so that they match the theme I am using is this possible and if so how would you go about doing it the code I am currently using is very basic and the basic code included in the standard theme does anybody know how to add classes to these standard bits of code bellow is what I have.
{% if is_popup %}
<input type="hidden" name="_popup" value="1" />
{% endif %}
{% if save_on_top %}
{% block submit_buttons_top %}
{% submit_row %}
{% endblock %}
{% endif %}
{% if errors %}
<p class="errornote">
{% blocktrans count counter=errors|length %}
Please correct the error below.
{% plural %}
Please correct the errors below.
{% endblocktrans %}
</p>
{{ adminform.form.non_field_errors }}
{% endif %}
{% block field_sets %}
{% for fieldset in adminform %}
{% include "admin/includes/fieldset.html" %}
{% endfor %}
{% endblock %}
{% block after_field_sets %}{% endblock %}
{% block inline_field_sets %}
{% for inline_admin_formset in inline_admin_formsets %}
{% include inline_admin_formset.opts.template %}
{% endfor %}
{% endblock %}
{% block after_related_objects %}{% endblock %}
{% block submit_buttons_bottom %}
{% submit_row %}
{% endblock %}
There are a lot of ways to do this, but certainly one way would be to overwrite all the widgets in your ModelAdmin rather than in the template. That could look something like this:
from django.db import models
from django.contrib import admin
from django.forms.extras.widgets import TextInput
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': TextInput(attrs={'class':'my-widget-class'},)},
}
You'd have to go through and do that for each widget, but then they'd have the appropriate classes -- at least for that modelAdmin.

Control flow in Django template language

I have the following code, written inside a Django template.
{% if user.is_authenticated %}
<div style="float: right;">
{% for rel in RELATIONS %}
{% if rel.group_id == g.id %}
Unsubscribe
{% endif %}
{% else %}
Enrol
{% endfor %}
</div>
{% endif %}
The purpose of the code is to check if there is a match and then print out the unsubscribe tag. If there is not match print out the subscribe tag.
The reason I am having trouble doing this is because you in Django templates, I read that you can't have variables (i.e. a True or False).
UPDATE: (The question)
I want to only print out the Unsubscribe/subscribe button once. Print out the unsubscribe button only if there is a match inside the for loop. Otherwise print out the subscribe button if there is no match (i.e. no match at all for rel.group_id == g.id )
UPDATE 2:
While doing some research earlier I found this: https://code.djangoproject.com/ticket/3481
This might add some context to my problem.
Thank you for your help.
Seems like your if/else/endif are mixed up. Try
{% if user.is_authenticated %}
<div style="float: right;">
{% for rel in RELATIONS %}
{% if rel.group_id == g.id %}
Unsubscribe
{% else %}
Enrol
{% endif %}
{% endfor %}
</div>
{% endif %}
UPDATE
You want to check if g is in relations and make your decission based upon that.
The way I usually solve this is to create a function in my view that does this check and passes that allong to the view. Have a look here.

Checking if authenticated in Django template inheritance

I have the following code in a template and am having difficulty showing when a user is logged in. I will be able to login, but when I revisit the page, it shows that I'm still not authenticated.
{% extends "base.html" %}
{% load catalog_tags %}
{% block site_wrapper %}
<div id = "main">
Skip to main content
<div id = "banner">
<div class="bannerIEPadder">
<div class="cart_box">
{% cart_box request %}
</div>
</div>
</div>
<div style="float:right;">[search box goes here]</div>
<div id="navigation">
<div class="navIEPadder">
<!--navigation tabs at the top of each page -->
{% comment %}{% include "tags/navigation.html" %} {% endcomment %}
{% category_list request.path %}
</div>
</div>
<div id="middle">
<div id="sidebar">
<!--<div class="sidebarIEPadder">[search box goes here]</br>
{% comment %}{% category_list request.path %}{% endcomment %}
</div>-->
</div>
<div id="content">
<!-- <a name = "content"></a>-->
<div class="contentIEPadder">
{% block content %}{% endblock %}
</div>
</div>
</div>
<div id="footer">
<div class="footerIEPadder">
{% footer_links %}
</div>
</div>
</div>
{% endblock %}
And here's the file it references. Since this will be an extension of all templates, is there something I need to consider?
###category_list.html
<!--<h3>Categories</h3>-->
<!--<ul id="categories">-->
<ul>
{% with active_categories as cats %}
{% for c in cats %}
<li>
{% comment %}
{% ifequal c.get_absolute_url request_path %}
{{c.name}}
{% else %}
{% endcomment %}
<div>{{c.name}}</div>
{% comment %}{% endifequal %}{% endcomment %}
</li>
{% endfor %}
<div class="fr">
<ul>
<li>
{% if user.is_authenticated %}
Logout
{% else %}
Login
{% endif %}
</li>
</div>
{% endwith %}
</ul>
<div class="cb"></div>
Am I missing something here?
You need to pass a RequestContext to the template. The easiest way to do this is to import django.shortcuts and use the render method in your view:
return render(request, "my_template.html")
Is django.contrib.auth.context_processors.auth in your TEMPLATE_CONTEXT_PROCESSORS setting.py?
Do you use requestContext rendering template?
Check that sessions are enabled: MIDDLEWARE_CLASSES should contains 'django.contrib.sessions.middleware.SessionMiddleware'

Categories

Resources