Flask blog, only want one user to be able to post - python

I'm creating a blog using Flask and Python and I have a problem. I only want one user to be able to post. In my HTML for post I tried writing
{% if current_user == default_user1 %}
.....code for creating a new post....
{% else %}
<h2>Only Admin can create new posts</h2>
{% endif %}
In my database I created the user like this
default_user1 = User(username='Admin',
email='default#test.com',
profile='Admin',
password=hashed_password)
db.session.add(default_user1)
But when I try to post something while logged in on default_user1 it says "Only Admin can create post". Do you know what I have done wrong?

2 objects in python need not be similar to each other, even if they have the same content
consider the code
class Abc:
def __init__(self, name):
self.name = name
a = Abc("Arjun")
b = Abc("Arjun")
print(a == b)
this will print False,
solution :
compare via the username
change
{% if current_user == default_user1 %}
to
{% if current_user.username == "Admin" %}

Related

how to use django model object in django templates?

I am not able to use the Django model object in Django templates. I want to iterate using the model user in the template and then play with the ActivityPeriod(model) of that user. Please check my code for the clarity:
Here is my code:
views.py
from .models import User,ActivityPeriod
def call_response(request):
user = User.objects.all()
return render(request, "Test/list.html", {"users":user ,"activityperiod":ActivityPeriod})
Test/list.html
{% for user in users %}
'real_name': {{ user.real_name}}},
'activity_periods': {% with activity=activityperiod.objects.get(id =user) %}
{{ activity.start_time }}
{% endwith %}
{% endfor %}
But i am getting an error:
Could not parse the remainder: '(id' from 'activityperiod.objects.get(id'
What is the correct way? Can anyone please share it with me.
Django template don't understand the filter action of Model. This part shoud be in view.
activity=activityperiod.objects.get(id =user)
You should prepare your data and manipulate them before sending to template (a dictionary may help you). And remember that result of action "User.objects.all()" is a list.
views.py
def call_response(request):
user = User.objects.filter(user=request.user)
activityperiod = activityperiod.objects.get(user=user)
context={'user':user,'activityperiod':activityperiod}
return render(request, "Test/list.html",context})
Test/list.html
'real_name': {{ user.real_name}}
'activity_periods':{{ activityperiod.start_time }}
Your question suggests that you think you can a function in the templates like a normal function (ie activityperiod.objects.get(...)).
You can't, the templating system is not made like this (for security reasons amongst others).
You should do something like, in your models:
def call_response(request):
# ! first() not "all()" (if > 1 user, you'll have problem)!
user = User.objects.first()
activityperiod = activityperiod.objects.get(user=user)
return render(request, "Test/list.html",
{"users":user ,"activityperiod":activityperiod})

Django Check for user in list

I'm creating a django blog app where users can add comments to articles.
I want to remove the post button when the user has already commented.
I have a model named article and another one named comment (with ForeignKey to article)
I tried {% if any request.user in article.comment_set.all} but that doesn't work. I tried to loop over article.comment_set.all but that didn't work either.
Is there a method to do this in the template?
Rather than doing that in template, why don't you do that in view and send it via context. For example:
def view(request):
...
user_exists = article.comment_set.filter(user=request.user).exists()
context = {}
context['user_exists'] = user_exists
return render(request, 'template.html', context)
in template:
{% if user_exists %}
// do something
{% else %}
// do something else
{% endif %}

Django - Show/hide urls in base html dependant on user group?

I want to try and show or hide urls in my navigation page based on user group.
currently i am adding to the top of every view and sending through a value to the template and checking against that, but this doesnt seem too efficient, also if a view does not require auth and that value is not set, will that break the template?
is there a better way to do this?
like a global.py where i could check and set then use it in any template? or something completely different altogether?
view.py
Authorised_user = ''
if request.user.is_authenticated():
Authorised_user = 'IT'
#login_required
def index(request):
return render(request, 'service/index.html', {
'Authorised': Authorised_user,
})
template.html
{% if Authorised == 'IT' or Authorised =='Netwworks' %}
Link
{% endif %}
i do have the user groups in django admin
Based on Get user group in a template
Create user_tags.py / group_tags.py at an appropriate place. e.g. auth_extra/templatetags/user_tags.py
from django import template
register = template.Library()
#register.filter('in_group')
def in_group(user, group_name):
return user.groups.filter(name=group_name).exists()
Then in your template:
{% load user_tags %}
{% if request.user|in_group:"IT"%}
IT only link
{% endif %}
{% if request.user|in_group:"Netwworks"%}
Netwworks only link
{% endif %}
Easiest way around this for me was https://stackoverflow.com/a/17087532/8326187.
Here you don't have to create a custom template tag.
{% if request.user.groups.all.0.name == "groupname" %}
...
{% endif %}
You need to create context_processors.py and create a function say
def foo():
Authorised_user = ''
if request.user.is_authenticated():
Authorised_user = 'IT'
Then in setttings
TEMPLATE_CONTEXT_PROCESSORS = ("path_to_context_processor.foo")
this way you can use foo variable in all the templates without explicitly defining in all the views.
You can also have a look here:https://rubayeet.wordpress.com/2009/10/31/django-how-to-make-a-variable-available-in-all-templates/

display new message to new user App Engine

I'm using Google App engine to allow a user to log in to the site. Once they log in, I create a token for them and use this to check whether the user is logged in. I want to be able to display a different message to first time users and a different one for returning users.
{% ifequal cookie None %}
Log In
<hr></hr>
{% else %}
{% for user in set %}
{% ifequal user.session_ID access_token %}
Logout {{user.user_name}}
<hr></hr>
{% else %}
{%endifequal%}
{% endfor %}
<h3 align="center">
{% endifequal %}
Currently, there are only two choices: signed in and not.
Assuming your user profile entity looks something like this:
class UserProfile(db.Model):
UserID = db.UserProperty()
FirstSession = db.DateTimeProperty(auto_now_add=True)
Try this:
from google.appengine.api import users
user = users.get_current_user()
is_existing_user = UserProfile.all().filter('UserID = ', user).get()
if is_existing_user:
#do something
else:
#do something else
I'd use a boolean variable in the user class for this case:
is_first_time_user = db.BooleanProperty(default=True,verbose_name="is First Time User")
or a function in the user class that the template tag can use.

Custom Django template tag to look up a string username and return it as a user object

I use some third-party template tags in my Django Application (maintained elsewhere) that return a username as a string I can access in my templates like this.
{% for user in gr.user.foll.list %}
{{user}}
Trouble is because {{user}} is returned as a string - I need to convert into a Django User Object, if it exists in the Django DB, or set a varible unRegistered if not so I can do things like:
{ user.get_profile.about }} # get profile information
So I thought I would write my first Django Template Tag so I could use it like this:
{% webapp_user_lookup user %} # my custom tag
{% ifnot unRegistered %}
{{ user.get_profile.about }} # get profile information - would fail with a string
{% endifnot %}
{% endfor %}
The code I use elsewhere to look up a user in a view is:
try:
user = User.objects.get(username__iexact=user)
unRegistered = False
if not other_user.is_active:
unRegistered = True
except:
unRegistered = True
However looking at the Django Template tag examples I'm having trouble understanding how best to structure the custom template tag, to take my string username - and send back the results as an object if they exist, or set a varible if not and the original string. I'd really like to better understand how the structure works, and if I need a 'class' and if so, why. (I'm new to programming).
use a template filter like so:
{{username|get_user}}
in your user_template_tags.py:
from django import template
from django.contrib.auth.models import User
register = template.Library()
########################
def get_user(username):
try:
user = User.objects.get(username__iexact=username)
except User.DoesNotExist:
user = User.objects.none()
return user
register.filter('get_user',get_user)
then in your template you can do something like:
{% with username|getuser as user %}
{% if user %}DO USER STUFF
{% else %}DO UNREGISTERED STUFF
{% endif %}
{% endwith %}

Categories