How to display other user's profile - django

Please, I am creating a web app, when a user log in, he/she can see other users, and can click on the user's username to view that user's profile. But I am finding it difficult to display other users profile except the currently logged in user. Kindly help me on how to go about this. I would prefer a function based view.
views
def profile(request, username):
context = {
'userprofile': User.objects.get(username=username),
}
return render_to_response('profile.html',context)
profile.html
Name: {{ userprofile.get_full_name }}
Username: {{ userprofile.username }}
urls
url(r'^/profile/(?P<username>\w+)/$', auth(profile), {}, name='chat_history')
what I don't know is how apply this url on a username. As in this:
home.html
{% if messages %}
{% for message in messages %}
{% if message.sender == user %}
<p> {{ message.sender }} >
{{ message.receiver }} : <br/>
{{ message.message }}
<sub>{{ message.creation_date }}</sub>
</p>
{% endif %}
{% endfor %}
{% else %}
{% trans 'No chat history of you and this user' %}
{% endif %}
Have got no idea what 'xxxxx' should be

Probably importing User model from django.contrib.auth and passing it to your views could help.

Related

How to pass db info to html template to query db in Flask [duplicate]

I'm working with flask and have a html page that contains of user name(user.html) which took from table, Now How can I see more detail by clicking on each of users(which route to profile)?
I don't use login for app So I don't want to use g
app.py
# am I doing it right?
#app.route('/profile/<int:id>')
def profile(id=None):
detail = Contacts.query.get(id)
return render_template('profile.html', detail= detail , id=id)
user.html
{% extends "layout.html" %}
{% block content %}
<h2>show user</h2>
{% for contact in contact %}
# I got error when I click on each user name to see their 'profile'
#I guess because of id How can Solve it?
#error BuildError: ('profile', {}, None)
<strong>name:</strong><a href={{url_for('profile')}}>
{{ contact.name}}</a><br>
{% endfor %}
{% endblock %}
profile.html
{% extends "layout.html" %}
{% block content %}
<h2>show user profile</h2>
# how can I make it specific for each row of table(each user)?
{% for detail in Contacts %}
<strong>name:</strong> {{ detail.name}} <br>
<strong>email:</strong> {{ detail.email }} <br>
<strong>age:</strong> {{ detail.age}} <br>
<br>
{% endfor %}
{% endblock %}
model.py
class Contacts(db.Model):
__tablename__ = "Contacts"
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(50))
email = db.Column(db.String(50))
age = db.Column(db.Integer)
submit = SubmitField("Submit")
I noticed two things in your code:
# this
<a href={{url_for('profile')}}>
# should be
<a href={{url_for('profile', id=contact.id)}}>
# otherwise Flask can't find the route, because it needs an id
And the other one:
{% for detail in Contacts %}
There is no such thing as a Contacts variable in your template, because your view function does not send it. Just get rid of the loop and use detail directly, because it's what you sent to the template.

Django. How display only loggedin user comments?

I want display comments from loggedin user, I tried this:
{% for c in request.user.game.comment_set.all %}
....
{% endfor %}
but doesn't work.
#edit.
Example:
User1 have comment1, comment2, User2 have comment3.
so if I log in to User1 account, I want see only comment1, comment2
The easiest way is to find user's comments in view and then pass them into your template.
views.py
user_comments = Comment.objects.filter(user=request.user)
return render(request, 'your_template.html', {'comments': user_comments)
your_template.html
{% for comment in comments %}
{{ comment.message }}
{% endfor %}

Can't get user in template using django.contrib.auth

What am i doing wrong? I just want the username of the user. I am logged so i don't know why it's not working.
views.py
from django.contrib.auth.models import User
def check_user(request):
data = dict()
user = User.objects.all()
data['user'] = user
return render(request, 'check_user.html', data)
urls.py
url(r'^check_user/$', views.check_user, name='check_user'),
check_user.html
{{ request.user.is_authenticated }}
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
And i'm getting this:
CallableBool(True)
Welcome, new user. Please log in.
when i should get:
Welcome, admin. Thanks for logging in.
If i use: {% if request.user.is_authenticated %} instead of {% if user.is_authenticated %} i'm getting this:
Welcome, . Thanks for logging in.
Your problem is in your view, you don't need to create data['user']. Because in template, Django already pass the template variable {{ user }}.
So in your view remove this data dict, and keep the current context, without modification.
def check_user(request):
return render(request, 'check_user.html', {})
And your template will work. (don't need to change something)
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
<p>Welcome, new user. Please log in.</p>
{% endif %}
https://docs.djangoproject.com/en/dev/topics/auth/default/#authentication-data-in-templates
user is queryset object in your template, in other words it is list of users, not single user.
If you need current user use this:
{% if request.user.is_authenticated %}
<p>Welcome, {{ request.user.username }}. Thanks for logging in.</p>
instead of
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}. Thanks for logging in.</p>
UPDATE
As Wilfried said in his answer and comment, it is not good practice to override variable user in template. So if you need list of users in view it would be better to rename context variable to users:
users = User.objects.all()
data['users'] = users

Django - Retrieve Unauthenticated User object

As the titles states, I have a need for users to retrieve User information of different users, whether or not they're authenticated.
I have a 'profile' template with some logic to either display static user information (for public) or editable user information (for the user it belongs to).
PROBLEM: The condition in my template is returning "true" - the User object appears to be authenticated BUT it's not. If I navigate from that page (profile) no user logged in.
I'm fairly new to Django. Am I not retrieving the User object correctly in my view.py?
views.py
def GetProfileById(request, userid):
try:
user = User.objects.get(pk=userid)
except User.DoesNotExist:
return HttpResponseRedirect('/')
try:
user_profile = user.get_profile()
except Exception:
return HttpResponseRedirect('/')
context = {'user': user, 'user_profile': user_profile}
return render_to_response('profile.html', context, context_instance=RequestContext(request))
profile.html
{% if user.is_authenticated %}
<form id="form-about" class="form-horizontal" action="{% url update-user-profile %}" method="POST">
{% csrf_token %}
<p>{{ about_form.first_name }}</p>
<p>{{ about_form.last_name }}</p>
<p>{{ about_form.birthday }}</p>
<p>{{ about_form.profession }}</p>
<button class="btn btn-primary" type="submit">Save</button>
</form>
{% else %}
<p><b>Name:</b> {{ user.first_name }} {{ user.last_name }}</p>
<p><b>DOB:</b> {{ user_profile.birthday }}</p>
<p><b>Profession:</b> {{ user_profile.profession }}</p>
<p><b>Member since:</b> {{ user.date_joined|date:'Y-M-d' }}</p>
<p><b>Last login:</b> {{ user.last_login|date:'Y-M-d # H:i' }}</p>
{% endif %}
It seems like, what you're trying to do is, if a user is currently logged in, you want to show a form that lets them update a profile.
So the problem is:
In your view, you're setting user to a User object from the database.
This object does not represent or contain information about whether the current user is logged in. It's just the record from the database.
You want to check request.user, which represents the User object for the user who requested the web page.
So in your template, change:
{% if user.is_authenticated %}
to:
{% if request.user.is_authenticated %}
I believe you're confusing user and request.user. The former is the user being displayed, the latter is the user that is currently logged in, or an AnonymousUser if no one is logged in.
You want to display that form if the user that is currently logged in and the user being displayed are the same, right? Then just change
{% if user.is_authenticated %}
To
{% ifequal user request.user %}

conflict between User and user.socialaccount in django-allauth

I have done this tutorial as it explained here:
and here
but there is some points that i can not understand.
When i log in using a facebook account i can get access also easily to my admin page and i want it to be happened (because it is not secure), so is there a way to fix that ?
If i want to bring that registred user to another template, i can do it only whith direct_to_template method in my url dispatcher, here is an example:
url(r'^tags$', direct_to_template, {'template' : 'user.html' }),
is there another way to do it.
Finally to be more clear, here is some snippets of my project:
urls.py
urlpatterns = patterns('',
#All Auth URLS
url(r'^accounts/', include('allauth.urls')),
url(r'^accounts/profile/', direct_to_template, { 'template' : 'profile.html' }),
#nav urls
url(r'^$','fb.views.home', name="home"),
url(r'^tags$', direct_to_template, {'template' : 'tags.html' }),
views.py
def home(request):
return render_to_response("base.html", locals(), RequestContext(Context))
base.html
.....
{% block body %}
{% block content %}
{% if user.is_authenticated %}
{{ user.username }} <p> you are logged in </p>
<p><a href="/accounts/logout/" >Logout </a></p>
{% else %}
<p> you are not authenticated : </p>
<a href="/accounts/facebook/login/" >Login with Facebook </a>
{% endif %}
{% endblock content %}
{% endblock body %}
...
profile.html
...
{% block content %}
{% if user %}
<h1>Welcome, {{user.first_name}}</h1>
<p>Following is the Extra information that facebook has provided to allauth:</p>
{% for account in user.socialaccount_set.all %}
<p>First Name: {{ account.extra_data.first_name }}</p>
<p>Last Name: {{ account.extra_data.last_name }}</p>
<p>Profile Link: {{ account.extra_data.link }}</p>
{% endfor %}
{% endif %}
Go to tags
{% endblock content %}
{% endblock body %}
tags.html
{{user.socialaccount_set.all.0.get_avatar_url}} <br/>
{{user.socialaccount_set.all.0.uid}} <br/>
{{user.socialaccount_set.all.0.get_provider_account }} <br/>
Finally thanks in advance for your help .
The secrect is:
After logging in, the user was hiding in the request object, so view shoukd be like this:
def home(request):
user = request.user
return render_to_response("base.html", locals(), RequestContext(Context))
Now, the problem is resolved, but i wonder why the Context User object was anounymous.
i am asking this question because that last user object woiuld have the same value of the request user in a simple authentication