display new message to new user App Engine - python

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.

Related

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

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

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/

How to flashing a message with link using Flask flash?

I'm creating a web app using Flask to deal with GoogleOpenID, these codes are almost finished, except the flashing message contains a link:
#oid.after_login
def create_or_login(resp):
user = db_session.query(User).filter_by(email=resp.email).first()
if user is not None:
flash('Successfully signed in', 'success')
else:
user = User(nickname=resp.fullname, source=GOOGLE, email=resp.email)
db_session.add(user)
db_session.commit()
flash(flashing_message, 'success')
g.user = user
session['nickname'] = user.nickname
return redirect(oid.get_next_url())
It works well when flashing_message is like this: 'Successfully registered, please click here'
But when flashing_message is 'Successfully registered, please click here', it doesn't work (flashes nothing) without throwing any Error. Strangely, sentences between flash() and return doesn't work either (did not set session['nickname] or g.user).
The other answers here focus on changing your template to allow all flash messages to be marked as safe, which may not be what you want.
If you just want to mark certain flashed messages as safe, wrap the text passed to flash() in Markup(). (Flask API Docs for Markup)
For example, instead of:
flash('Successfully registered, please click here')
Wrap the string in Markup() like this:
flash(Markup('Successfully registered, please click here'))
As always, you will need to import Markup from the flask package something like:
from flask import Markup
You need to render a template after calling flash() which should then get the message using get_flashed_messages().
You need to adjust your code to call a template after calling flash(). flash sends the message to next request which can be extracted by the template. The template can look something like:
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message | safe }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
In your view code, I would add a render_template right after the flash() call. Something like:
flash('success')
return render_template('whatever.html')
Escaping HTML is the default behavior, so pass it through the safe filter to display the HTML unescaped:
{{ message|safe }}
I am not sure if it is correct, but the way I solved this was by declaring another variable in the function that was a string of HTML and then passing it through a render_template() function.
And in the template passed it through the safe filter.
For example, (roughly based on) the code you have provided:
#oid.after_login
def create_or_login(resp):
user = db_session.query(User).filter_by(email=resp.email).first()
if user is not None:
flash('Successfully signed in', 'success')
else:
user = User(nickname=resp.fullname, source=GOOGLE, email=resp.email)
db_session.add(user)
db_session.commit()
flash(flashing_message, 'success')
link = "Link" ## ADDED HTML WITH LINK ##
g.user = user
session['nickname'] = user.nickname
return render_template('some_layout.html',
link=link ## PASS THE LINK TO THE TEMPLATE ##
)
Then in the template I added an extra if statement inside the get_flashed_messages() if:
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
... Code that was already here ...
{% if link %} ## PASSED THE LINK TO THE TEMPLATE HERE ##
{{ link | safe }}
{% endif %}
{% endif %}
{% endwith %}

Checking for permission in django template not working

I want to verify user permission in template. If a user has permission he/she will be able to access the template. After writing the below code and I granted the user permission, when I view the page it will fall on the {% else %} statement. showing that the user don't have permission. How can I go about this?
#CREATED A GROUP IN DJANGO ADMIN CALLED 'Premium'
Class Paid(models.Model):
#models here
class Meta:
permissions=(
("view_film","Can view film"),
)
view
def eyo(request):
return render_to_response('eyo.html',context_instance=RequestContext(request))
template
{% block content %}
{% if perms.paid.can_view_film %}
<form action='https://www.test.com/checkout' method='post'>
<input name='submit' type='submit' value='Checkout' />
</form>
{% else %}
<p> yo broke! </p>
{% endif %}
Are you passing perms in your template?
Are you setting perms.paid.can_view_film either explicitly in your view or via the admin interface?
Is the user a part of a group that has the perms.paid.can_view_film permission?
Are you sure the app name is 'paid'? That's supposed to be the app name, not the model name.
Django Perms
I'm doing some conditional rendering based on permissions in a Django project I'm currently working on. A small example of this is a particular icon. Basically if a user has a delete permission, they see one icon, if they don't, they see another. This is how it's done in my templete:
{% if perms.List.can_delete_list %}
<li><span class="fui-search"></span></li>
{% else %}
<li><span class="fui-new"></span></li>
{% endif %}
If the logged in user has can_delete_list, they view one thing. If not, they view something else. Does this help?

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