Django: How to implement user profiles? - python

I'm making a Twitter clone and trying to load profile pages. My logic was to start simple and find all tweets that match a certain author and load those tweets on a page as the user's profile. I really don't know where to start.
urls.py
url(r'^users/(?P<username>\w+)/$', views.UserProfileView.as_view(), name='user-profile'),
models.py
class Howl(models.Model):
author = models.ForeignKey(User, null=True)
content = models.CharField(max_length=150)
views.py
class UserProfileView(DetailView):
"""
A page that loads howls from a specific author based on input
"""
model = get_user_model()
context_object_name = 'user_object'
template_name = 'howl/user-profile.html'
user-profile.html
{% block content %}
<h1>{{user_object.author}}</h1>
{% endblock %}
I'm currently getting an error that says "Generic detail view UserProfileView must be called with either an object pk or a slug." whenever I try something like localhost:8000/users/
I also went on the shell and tried
Howl.objects.filter(author="admin")
But got
ValueError: invalid literal for int() with base 10: 'admin'

Foreign key require model object or primary key of object.
pass the id of object whose username is "admin". use
Howl.objects.filter(author=1)
instead of
Howl.objects.filter(author="admin")
or you can use this one also
user = User.objects.get(username = "admin")
Howl.objects.filter(author=user)

Related

Django: How to retrieve the logged in user's details

I am in the process of learning Django. I am trying to create a simple directory web app. I am able to print out all the users details for the main directory page. However, I want to add a feature that when a person logs into the directory app they are brought to their 'profile' page where they will be able to see all their own details e.g. business name, profile pic.
I know how to retrieve the default fields e.g. username and email. But cannot seem to retrieve the custom fields that I declared myself. Here is my attempts so far...
Models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfileInfo(models.Model):
user = models.OneToOneField(User,on_delete=models.DO_NOTHING)
#additional classes
business_name = models.CharField(max_length=191,blank=True)
trade = models.CharField(max_length=191,blank=True)
portfolio_site = models.URLField(blank=True)
profile_pic = models.ImageField(upload_to='profile_pics',blank=True)
def __str__(self):
return self.user.username
Views.py:
#login_required
def profile(request):
profile = UserProfileInfo.objects.filter(user=request.user)
context = { 'profile': profile }
return render(request, 'dir_app/profile.html',context)
Profile.html:
<div class="container-fluid text-center">
{% for p in profile %}
<h3>{{p.business_name}}</h3>
{% endfor %}
</div>
Since UserProfileInfo is related to User via OneToOneField, you can have one UserProfileInfo per User. So, instead of Filter, you can simply get your desired UserProfileInfo object through your current (logged in) User as follows.
views.py,
profile = UserProfileInfo.objects.get(user=request.user)
Also, before you can get a request.user object, you have to make sure that your user is authenticated and logged in. Otherwise, you might get None in place of a User object and therefore, no associated UserProfileInfo.
Since it is a OneToOneField there is only one Profile object for a User, you thus can obtain this with:
#login_required
def profile(request):
profile = request.user.userprofileinfo
return render(request, 'my_template.html',{'profile': profile})
Then in the template, you render it with:
{{ profile.business_name }}
you can use it directly on template without sending it f:
{{request.user.userprofile}}

Django writing generic update view restricted to certain user

I am building a small blog using django.I want to build a function that allow post author to delete and update their own posts.
Then I find django has LoginMixin for generic view,but it only block those who don't login.
My article Model is like below
class Article(models.Model):
author = models.ForeignKey(User)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=50)
context = models.TextField()
genre_choice = (('O','Others'),('P','Programming'),('L','Learning'),('E','Entertainment'))
genre = models.CharField(max_length=2,choices=genre_choice,default='O')
def __str__(self):
return "{} - {}".format(self.title,self.author)
def get_absolute_url(self):
return reverse("article-detail",args=str(self.id))
This is the generic article detail view.
class ArticleDetail(DetailView):
model = Article
I firstly want to add something like this in the detail template:
{% if article.author == user.username%}
<!-- Some a tag that directs to the update view -->
{% endif %}
Then I realize that this just hides the a tag ,it can't stop other users to touch the update url simply change the url.
Is there anyway in django can restricted the update and delete permissions to the original user by simply using generic view?Even if they directly enter the update url,they will be rejected.
Override get_queryset in your UpdateView, so that the user can only access items that they authored. Use the LoginRequiredMixin to ensure that only logged-in users can access the view.
from django.contrib.auth.mixins import LoginRequiredMixin
class UpdateArticle(LoginRequiredMixin, UpdateView):
model = Article
def get_queryset(self):
queryset = super(UpdateArticle, self).get_queryset()
queryset = queryset.filter(author=self.request.user)
return queryset
In the template, I would compare the author_id with the user's primary key to decide whether to show the link or not.
{% if article.author_id == user.pk %}
One option is to create your own mixin/decorator to check if the logged user is the author, if not then reload/show a message etc.
I believe a safer way now would be to use built-in mixin UserPassesTestMixin. In particular, you can inherit it in your class and change its test_func() to check for the author. Don't forget to also inherit LoginRequiredMixin to make sure the user is logged in:
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
class UpdateArticle(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Article
def test_func(self):
thisArticle = self.get_object()
if self.request.user == thisArticle.author:
return True
return False
If a user who is not the author attempts to update the article, '403 Forbidden' Error is returned which is just what you want in such a situation.

Calling Model function in template not working

I'm trying to get the category of a skill in a template.
From the post I read, I can't directly get information from a foreign key in a template.
Instead, I add a function on CharacterSkill models to get the Skill category
Models.py
class Character(models.Model):
name = models.CharField(max_length=70)
class Skill(models.Model):
name = models.CharField(max_length=70)
cat1 = '01'
SKILLSET_CHOICE = ((cat1:'cat1'))
skillset_choice = models.CharField(
max_length=2,
choices = SKILLSET_CHOICE,
default='',
blank=True,
null=True,
)
class CharacterSkill(models.Model):
character = models.ForeignKey(Character, on_delete=models.CASCADE)
skill = models.ForeignKey(Skill, on_delete=models.CASCADE)
def skillcategory(self):
return Skill.objects.get(id = self.skill).skillset_choice
Template
skillsetchoice {{item.skillcategory}}
But I get an error :
Exception Type: TypeError
Exception Value:
int() argument must be a string or a number, not 'Skill'
I tried to inpect value with the shell console where I can get back the category id but when I use it in template, nothing is working
Hope you can help me!
This has nothing to do with calling it from the template.
self.skill is already an instance of Skill. There is no need to query that model explicitly.
def skillcategory(self):
return self.skill.skillset_choice
And in fact this method is pretty pointless; you certainly can do it directly in the template:
skillsetchoice {{ item.skill.skillset_choice }}
Replace self.skill with self.skill.id (in older versions of Django your code would work by the way):
def skillcategory(self):
return Skill.objects.get(id = self.skill.id).skillset_choice
But this is much better:
def skillcategory(self):
return self.skill.skillset_choice
But do you really need this method? You can use:
{{ item.skill.skillset_choice }}
If you want to display cat1, then (get_foo_display):
{{ item.skill.get_skillset_choice_display }}

Django form to display user attributes

I'm having an odd problem that I can't remedy: Django is not displaying any of the user's attributes except for the username when using a form that includes a foreign key attribute between two models.
The associated username is showing up correctly, but none of the other attributes are (first name, last name, email, etc).
Similarly, the debugging print statement that I've placed in the views.py is correctly printing the user's attributes in the terminal output.
Why aren't any of the user's attributes showing up in the html template?
models.py
class UnitGroup(models.Model):
unit_name = models.CharField(max_length=150, verbose_name='Unit Name')
class UnitUser(models.Model):
user = models.OneToOneField(User)
unit = models.ForeignKey(UnitGroup)
ROLES = ((0, 'Admin'), (1, 'Member'))
role = models.IntegerField(null=True, blank=True, verbose_name='Role', choices=ROLES)
def __string__(self):
return self.user.first_name
forms.py
class UserGroupForm(forms.ModelForm):
class Meta:
model = UnitUser
fields = '__all__'
views.py
from units.forms import UnitForm, UnitDetailsForm, UserGroupForm
from units.models import UnitGroup, UnitDetails, UnitUser
from django.contrib.auth.models import User
def edit_members(request):
if request.user.is_authenticated() \
and request.method == 'GET' \
and 'unit' in request.GET:
unit_group = request.GET['unit']
unit_users = UnitUser.objects.filter(unit=unit_group)
unit_forms = []
for i in unit_users:
# debug
print(i.user.first_name)
print(i.user.last_name)
unit_forms.append(UserGroupForm(instance=i))
return render(request, 'units/edit-members.html', {'unit_forms': unit_forms})
edit-members.html
{% for form in unit_forms %}
user: {{ form.user }} <br>
first name: {{ form.user.first_name }}
{% endfor %}
Your UserGroupForm is a model-form, based on the UnitUser model.
The fields of the form are based on the fields of the model.
Since UnitUser doesn't contain details about the user, but merely a single reference to the user model, the user model itself is only represented via a single field. The string representation of a user model is the username. I would think that's the reason you see the username in your form.
In short: Your model-form considers the user just as a single field and will use the string representation of the value of that field as init-value.
If you want to display further attributes of the user in your form, you might have to construct a specific form for that purpose.

Foreign key to User table in django

I'm using django's built-in contrib.auth module and have setup a foreign key relationship to a User for when a 'post' is added:
class Post(models.Model):
owner = models.ForeignKey('User')
# ... etc.
Now when it comes to actually adding the Post, I'm not sure what to supply in the owner field before calling save(). I expected something like an id in user's session but I noticed User does not have a user_id or id attribute. What data is it that I should be pulling from the user's authenticated session to populate the owner field with? I've tried to see what's going on in the database table but not too clued up on the sqlite setup yet.
Thanks for any help...
You want to provide a "User" object. I.e. the same kind of thing you'd get from User.objects.get(pk=13).
If you're using the authentication components of Django, the user is also attached to the request object, and you can use it directly from within your view code:
request.user
If the user isn't authenticated, then Django will return an instance of django.contrib.auth.models.AnonymousUser. (per http://docs.djangoproject.com/en/dev/ref/request-response/#attributes)
Requirements --> Django 3, python 3
1) For add username to owner = models.ForeignKey('User') for save that, in the first step you must add from django.conf import settings above models.py and edit owner = models.ForeignKey('User') to this sample:
class Post(models.Model):
slug = models.SlugField(max_length=100, unique=True, null=True, allow_unicode=True)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE)
2) And for show detail Post, special owner name or family or username under the post, you must add the following code in the second step in views.py:
from django.shortcuts import get_object_or_404
.
.
.
def detailPost(request,slug=None):
instance = get_object_or_404(Post, slug=slug)
context = {
'instance': instance,
}
return render(request, template_name='detail_post.html', context=context)
3) And in the third step, you must add the following code for show user information like user full name that creates a post:
<p class="font-small grey-text">Auther: {{ instance.owner.get_full_name }} </p>
now if you want to use user name, you can use {{ instance.owner.get_username }}
or if you want to access short name, you can use {{ instance.owner.get_short_name }}.
See this link for more information.

Categories