Multiple views for webpage depending on authentication status in Django - django

I am currently working on a developing a web application that people can use to browse through book reviews, but if they login they can post comments on the book reviews, or post their own reviews of books.
While I have implemented posting new reviews. I am do not understand how to modify the method in my views.py file that renders a book review such that if the user is logged in, in shows all previous comments, a form for the user to post a comment and a logout button, and if the user is not logged in it simply shows the book review and a log in button.

You can tell if your user is logged in or not in your views like this:
if request.user.is_authenticated():
# logged in logic
return render_to_response("loggedin_templates.html")
else:
# not logged in logic
return render_to_response("not_loggedin_templates.html")
Or you can tell them in the templates like this:
{% if user.is_authenticated %}
<span>{{ user.username }}</span>
{% else %}
<li>login
{% endif %}

Related

Check if current user is logged in using any django social auth provider

I would like to check if a user is logged in via social authentication or using the django default authentication.
something like
if user.social_auth = true?
Ok after doing some research i came up with this solution to make sure if a user is authenticated using any social provider or just the default django auth. Check here for moreinfo..
{% if user.is_authenticated and not backends.associated %}
#Do or show something if user is not authenticated with social provider but default auth
{% elif user.is_authenticated and backends.associated %}
#Do or show something if user is authenticated with social provider
{% else %}
#Do or show something if none of both
{% endif %}
i was searching on that and the solution is user.social_auth.exists()
it will return True if the user exists in the database else it will return false.
from social_auth.models import UserSocialAuth
try:
UserSocialAuth.objects.get(user_id=user.id)
except UserSocialAuth.DoesNotExist:
print "user is logged in using the django default authentication"
else:
print "user is logged in via social authentication"
You may to add a method to User model.
From Python:
user.social_auth.exists()
will return True if user is social, False otherwise.
From template:
{% if not backends.associated %}
<code if user is NOT social>
{% else %}
<code if user is social>
{% endif %}
The backends context variable is automatically set in Django templates when you include the python-social-auth app in your Django project's config.
Currently, the django-social-auth is deprecated. You can use python-social-auth instead.
In that case, you should use:
user.social_auth.filter(provider='BACKEND_NAME')
For instance, if current user is authenticated by Google Account:
if user.is_authenticated:
if user.social_auth.filter(provider='google-oauth2'):
print 'user is using Google Account!'
else:
print 'user is using Django default authentication or another social provider'
you can query all the users that are using social authentication as follow, from UserSocialAuth app:
from social_django.models import UserSocialAuth
if user in [u.user for u in UserSocialAuth.objects.all()]:
#dosomething
I have same problem to recognize social logged-in users by python-social-auth and I should specify a separate tab for them in navigation bar to complete their profile page. Of course if a user has logged-in through social auth, no password has been set for him\her in DB. So I used has_usable_password() method (django.contrib.auth) for this propose. For exp:
{% if user.has_usable_password %}
<a class="dropdown-item" href="{% url 'password_change' %}">Change password</a>
{% elif not user.has_usable_password %}
<a class="dropdown-item" href="{% url 'set_pass' %}">Set password</a>
Obviously this tip will helpful as long as the user doesn't set password.

django-facebook like and share button for contents. template example

I am trying to get django-facebook work with my website .
I have this model
class Photo(models.Model):
name = models.CharField(max_length=100)
photo=models.ImageField(upload_to=/upload)
catagory= models.CharField(max_length=100,choices=Choice_c)
the template is
{% for p in photos %}
{% thumbnail p.photo as im %}
{% endthumbnail %}
{%endfor%}
the view for photos is
def home(request):
photos=Photo.objects.all()
return render_to_response(‘home.html’, {‘photos’:photos,},context_instance=RequestContext(request))
Now my question is how can I have facebook “like” and “share” button for contents i.e photo using django-facebook .
I have tried the facebook like code from facebook developers site but
it chooses all the photos if I iterate and all photos get liked which is
normal because I am iterating all of them.
Can you give a simple example how I can get individual likes for the photos by using django facebook.
Thanks in advance,

How to know if a user is facebook logged in? Django

As the title indicates, I would like to know how to do to distinguish a user that is logged in with facebook from a user that is logged in by mail. I'm using django-facebook.
It seems that
request.user.is_authenticated()
is for every kind of authentification.
Any help would be welcome,
I think you can check if request.user has a FacebookProfile:
{% if request.user.facebookprofile %}user has facebook profile{% endif %}
Or in python:
if request.user.facebookprofile_id:
print 'has facebookprofile'

Django Context contains not defined field when using RequestContext

Hi I'm writing a django project, and I write template code like this:
<ul id="nav">
<li>Home</li>
<li>Users</li>
{% if user %}
<li>Settings</li>
<li>Log Out</li>
{% else %}
<li>Log In</li>
<li>Sign Up</li>
{% endif %}
</ul>
Now in login view I write like this:
def login(request):
if user_logged_in(request):
return redirect('/')
if request.method == 'GET':
form = LogInForm()
return render_to_response(LOGIN_PATH, {'form':form}, context_instance=RequestContext(request))
But when I run the server, no user is logged in, and visit login page, it shows Settings and Log Out(there is a user object in context), but it shouldn't!
If I remove RequestContext, say return render_to_response(LOGIN_PATH, {'form':form}), it will be OK. And
return render_to_response(LOGIN_PATH, {'form':form, 'user':None}, context_instance=RequestContext(request))
is OK too. But I don't want to do it.
I know it's dirty design, well... I'm looking for suggestions and solutions. Many thanks~!
{% if user.is_authenticated %}
your tag just checks for a user object, not for an authenticated one.
check here for more informations on what you can do with an auth user :)
The default setting for TEMPLATE_CONTEXT_PROCESSORS includes "django.contrib.auth.context_processors.auth". This context processor adds a user to cotnext, which will be anonymous if the user is not provided in request so.
If you want to be able to know whether or not the user is authenticated in template the #Samuele Mattiuzzo answer is what you should use, but if you don't want, for any reason, to include the user in context, then you need to modify the default TEMPLATE_CONTEXT_PROCESSORS setting without the auth context processor.
For more information read the docs or the code.

Showing the logged-in user inside base.html (django)

Is there a way to access the logged in user's firstname inside the base.html file?
I'm trying to do this, because i want to display who is currently logged in on the navigation bar, but it won't access the user's information, nor will it correctly check if the user is authenticated.
html inside base.html
Hi there,
{% if user.is_authenticated %}
{{user.first_name}}
{% else %}
Stranger
{% endif %}
request.user gives you the user object that is currently logged in. So you have full access to all the attributes and methods the User class has. To get the first_name, you can do {{ request.user.first_name }}. To get the full name you use {{ request.user.get_full_name }}.
If you use [RequestContext][1], by default you get user instance in your templates so you can use it as for its attributes as {{user.first_name}} and others. The user will be same a currently authenticated user which is also available in request.user in the views.
The RequestContext by default adds some default template contexts defined in TEMPLATE_CONTEXT_PROCESSORS in your settings.py.
In your view, you can use it as
#your view code
....
#send response by rendering the template and use Requestcontext while rendering template
return render_to_response('polls/detail.html', {'poll': p},
context_instance=RequestContext(request))
Reference - Django Tutorial 04