This is my frontend code of header.html where I am typing to display the currently logged-in user's profile picture after the user authenticates. It works when my current user is on the home page or its profile but as soon as it moves to another's profile it starts displaying that profile's picture. I want to make it such like where ever logged in user move he/she should always see their profile picture
<div><b>Bondly</b></div>
{% if user.is_authenticated %}
<div>
-------> <img src="{{user_profile.img_profile.url}}" />
</div>
{% endif %}
</header>
Here are code of my views.py
def profile(request, pf):
user_object = User.objects.get(username=pf)
user_profile = models.Profile.objects.get(usr=user_object)
print(request.user.__doc__)
posts = models.Post.objects.filter(user=pf)
postsNum = len(posts)
follor = request.user.username
if models.Followers.objects.filter(follower=follor, user=pf).first():
text = "Following"
else:
text = "Follow"
followers = len(models.Followers.objects.filter(user=pf))
following = len(models.Followers.objects.filter(follower=pf))
context = {
'user_object': user_object,
"user_profile": user_profile,
"posts": posts,
'postsNum': postsNum,
"text": text,
"followers": followers,
"following": following
}
return render(request, 'profile.html', context)
and my models.py
class Profile(models.Model):
"""docstring for Profile."""
usr: str = models.ForeignKey(User, on_delete=models.CASCADE)
id_usr: int = models.IntegerField()
Fname:str = models.TextField(blank=True,null=True)
Mname:str = models.TextField(blank=True,null=True)
Lname:str = models.TextField(blank=True,null=True)
Fhone:int = models.IntegerField(blank=True,null=True)
bio: str = models.TextField(blank=True)
img_profile = models.ImageField(
upload_to='ProfileIMG', default="blankprofile.png")
location: str = models.CharField(max_length=250)
def __str__(self):
return self.usr.username
You can simply use request.user to get logged in users data from your models in any template. The way you are currently loading user image is different, as it will load data of the user only when user data is passed in context for the template
{% if request.user.is_authenticated %}
<div>
<img src="{{ request.user.profile.img_profile.url }}" />
</div>
{% endif %}
Related
I've been trying to loop through the social login account photos of the users and myself on the app that I'm doing. Currently, I have a different model for the contributors on the app that is shown on the homepage and on a separate page.
The models of my pages app is
class Volunteers(models.Model):
name = models.CharField(max_length=100)
image = models.ImageField(upload_to="volunteers/")
def __str__(self):
return self.name
class Meta:
verbose_name = "volunteer"
verbose_name_plural = "volunteers"
The profile page has
{% if object == request.user %}
...
<img class="rounded-circle account-img center-align" src="{{ user.socialaccount_set.all.0.get_avatar_url }}">
...
{% endif %}
Since cookiecutter-django has a default users model, I imported the views of the model to my pages app to try and see if it will show on the home page.
The default cookiecutter-django model for the users is
class User(AbstractUser):
# First Name and Last Name do not cover name patterns
# around the globe.
name = CharField(_("Name of User"), blank=True, max_length=255)
def get_absolute_url(self):
return reverse("users:detail", kwargs={"username": self.username})
The view on the pages app is
from pages.users.models import User
def home(request):
...
users = User.objects.all()
...
context = {"users": users }
return render(request, pages/home.html, context)
The for loop on the template is
{% for u in users %}
...
<img src="{{ u.user.socialaccount_set.all.0.get_avatar_url }}" class="img-responsive" alt="{{u.name}}">
...
{% endif %}
The console is showing the html templates but not the images.
Did I do anything wrong? Or how do I implement it properly?
How to fix This Error I'm Trying To Fix This Error But I Get Again And Again
i want to detect user who fill the form for example test fill the form but when i write the code down below i get this error
Any Help Will Be Appreciated!
ERROR
user_register_model matching query does not exist.
ERROR SCREENSHOT
Here is my Views.py
def buy_form(request):
if request.method == 'POST':
usr_buy = user_buy_form(request.POST)
if usr_buy.is_valid():
usr_buys = usr_buy.save(commit=False)
user_register_obj = user_register_model.objects.get(user=request.user)
usr_buys.users = user_register_obj
usr_buys.save()
else:
return print(usr_buy.errors)
else:
usr_buy = user_buy_form()
context = {'usr_buy':usr_buy}
return render(request,'user_buy.html',context)
Here is my Models.py
class user_register_model(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
join_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.user.username
class user_buy(models.Model):
users = models.ForeignKey(User,on_delete=models.CASCADE)
title = models.CharField(max_length=200)
payment_method = models.CharField(max_length=500)
price = models.IntegerField()
Trade_limits = models.IntegerField()
Location = models.CharField(max_length=1000)
def __str__(self):
return self.users.user.username
Here is my Forms.py
class user_buy_form(forms.ModelForm):
class Meta():
model = user_buy
fields = '__all__'
exclude = ('users',)
Here is my user_buy.html
{% extends 'base.html' %}
{% block body_block %}
<form class="form-control" method="POST">
{% csrf_token %}
{{usr_buy.as_p}}
<input type="submit" class="btn btn-primary" value="Submit">
</form>
{% endblock %}
I didn't see any points here to create the user_register_model.If you are trying to add the currently logged in user you can do this:
request.user will give you the currently logged in user so for this the user must be logged in.
#login_required
def buy_form(request):
if request.method == 'POST':
usr_buy = user_buy_form(request.POST)
if usr_buy.is_valid():
usr_buys = usr_buy.save(commit=False)
usr_buys.users = request.user
usr_buys.save()
return redirect('some_path') # redirect to some path after saving the form
Class names should normally use the CapWords convention.
I think the request.user is not present in the user_register_model model thats why it is giving matching query doesnot exist error, first create it in the user_register_model and then query it.
In this my views I get users by their exact name example www.mysite.com/usuario1
and so far it's working, but I need it in the photos section to get only the photos of that user1
and that user1 is not logged into the system.
how do I pull only the photos of the user1?
models.py
class Photo(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=255, blank=True)
file = StdImageField( upload_to='photos/', blank=False, variations={
'large': (600, 400),
'thumbnail': (100, 100, True),
'medium': (300, 200),
})
uploaded_at = models.DateTimeField(auto_now_add=True)
class Negocio(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
views.py
def profile_detail(request, username):
if User.objects.get(username__iexact=username):
user_details = User.objects.get(username__iexact=username)
photos_list = Photo.objects.filter(user=request.username.pk)
return render(request, "profile.html", {
"user_details": user_details, 'photos': photos_list
})
else:
return render("User not found")
profile.html
{% for photo in photos %}
<img src="{{ photo.file.medium.url}}"class="img-thumbnail" width="200" height="200">
{% endfor %}
Well, you get the user, but then you don't pass it to your Photo filter - instead you pass the logged-in user there. Just use the user you got:
photos_list = Photo.objects.filter(user=user_details)
Note, your first line will fail if the user does not exist, because the query will raise a DoesNotExist exception. A better way to do it would be:
def profile_detail(request, username):
user_details = get_object_or_40o4(User, username__iexact=username)
photos_list = Photo.objects.filter(user=user_details)
return render(request, "profile.html", {
"user_details": user_details, 'photos': photos_list
})
which will automatically show a 404 (not found) page if the username does not exist.
You don't need a queryset for the photos, you can access them through the User instance using the related_name, if you don't set a related_name you can just append _set to the model name like this:
photos_list = user_details.photo_set.all()
But you don't really need the queryset at all in your view, in your template you can do this:
{% for photo in user_details.photo_set.all %}
<img src="{{ photo.file.medium.url}}"class="img-thumbnail" width="200" height="200">
{% endfor %}
I will really need your help over here. I think I have read all the relevant responses to my problem but I cannot figure out how it works.
I would like to choose from the html form in django some users that belong to a specific group.
I created my model "Task", which is below:
class Task(models.Model):
Taskdetails = models.CharField(max_length=500, null=True)
asset = models.ForeignKey('Asset', null=True)
failure = models.ForeignKey('Failure', null=True)
Created_task_date = models.DateTimeField(default=timezone.now, null=True)
employee = models.ForeignKey("auth.User", null = True)
def __str__(self):
return str(self.id)
The django form is:
class TaskForm (ModelForm):
class Meta:
model = Task
fields = ('Taskdetails', 'asset', 'failure', 'employee',)
The view is:
def task_new(request):
if request.method == "POST":
task_form = TaskForm(request.POST)
subtask_form=SubtaskForm(request.POST)
task_form.employee = User.objects.filter(groups__name='supervisor')
if task_form.is_valid() and subtask_form.is_valid():
task = task_form.save()
subtask = subtask_form.save(commit=False)
task.Created_task_date = timezone.now()
task_form.employee = User.objects.filter(groups__name='supervisor')
task.save()
subtask.task=task
subtask.Created_subtask_date = timezone.now()
subtask.save()
return redirect('great_job')
else:
task_form = TaskForm()
subtask_form = SubtaskForm()
return render(request, 'TaskTrace/task_new.html', {'task_form': task_form, 'subtask_form':subtask_form})
And the relative html is
{% block content %}
<div>
<h1>New Task</h1>
<form method="POST" class="task-form">
{% csrf_token %}
Equipment with failure: {{ task_form.asset }}<br><br>
Failure Description: {{ task_form.failure }} <br><br>
Task Details: {{ task_form.Taskdetails }} <br><br>
Employee: {{ task_form.employee }}
<button type="submit" class="save btn btn-default">Open</button>
</form>
</div>
{% endblock %}
I created in the django-admin 3 users. Two of them belongs to a the group "supervisor". I would like to be shown in the template only these two users that belong to this particular group. On the contrary, all the users are thrown in the form.
Can anyone please help me to move forward? I have stuck for 3 days in this particular point.
Thanks in advnance!
On your view when creating the form you have to do something like this:
task_form = TaskForm()
task_form.fields["employee"].queryset = User.objects.filter(group__name="supervisor")
I have a fairly simple DetailView:
class TrackDetails(DetailView):
model = Track
And in my urls.py:
url(r'^(?P<slug>[-\w]+)/$', TrackDetails.as_view(), name='track-details'),
The model:
class Track(models.Model):
....
# Variables
track_type_choices = [
('ORG', 'Original'),
('RMX', 'Remix'),
('CLB', 'Collab'),
('LIV', 'Live'),
]
# Model Fields
user = models.ForeignKey(User, unique=False)
title = models.CharField(max_length=100)
desc = models.TextField(max_length=7500)
track_type = models.CharField(max_length=3,
choices=track_type_choices,
default='ORG')
track_type_content = models.CharField(max_length=100,blank=True)
created = models.TimeField(auto_now=True,auto_now_add=False)
upload = models.FileField(upload_to=generate_user_folder_tracks,storage=OverwriteStorage(),validators=[is_mp3])
albumart = models.ImageField(upload_to=generate_user_folder_art,storage=OverwriteStorage(),validators=[is_square_png])
private = models.BooleanField(default=False)
downloadable = models.BooleanField(default=False)
likes = models.ManyToManyField(User, related_name="likes",blank=True)
dislikes = models.ManyToManyField(User, related_name="dislikes",blank=True)
plays = models.BigIntegerField(default=0)
slug = models.SlugField(max_length=50,unique=True)
The model displayed in the view has a "user" field connected to the user model, I want to use this in the url, so that instead of writing "www.domain.com/slug/" I would write "www.domain.com/user/slug" to access the view of the instance.
Additionally, I have extended the User model with a field called "Display_name", I'd like to show this field instead of the username in my template (track_detail.html):
{% include '__header.html' %}
{% load static from staticfiles %}
<div id="track_container">
<div id="track_titleinfo">
<div id="track_artist" class="text">{{ object.user }}</div>
<div id="track_title" class="text">{{ object.title }}</div>
{% if object.track_type == 'ORG' %}
{% else %}
<div id="track_type" class="text">({{object.track_type_content}})</div>
{% endif %}
</div>
</div>
{% include '__footer.html' %}
<img src="/static/users/{{ object.user }}/art/{{ object.slug }}.png" alt="">
The div with the ID "track_artist" displays the raw username (In this case, enitoni), I'd like it to display the display_name (In this case "Ekchö") from the userprofile class of the user who owns the Track instance:
class UserProfile(models.Model):
user = models.OneToOneField(User)
display_name = models.CharField(max_length=50, default="null")
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
To include the username in the detail view, you first need to add it to your url patterns.
url(r'^(?P<username>[-\w]+)/(?P<slug>[-\w]+)/$', TrackDetails.as_view(), name='track-details'),
Then, since you are using DetailView, you need to override get_object so that you use the username and slug to fetch the object.
from django.shortcuts imporg get_object_or_404
class TrackDetails(DetailView):
model = Track
def get_object(self, queryset=None):
return get_object_or_404(
Track,
user__username=self.kwargs['username'],
slug=self.kwargs['slug'],,
)
Displaying the display_name of the user in the template is a separate problem. If you have a user, you can follow the one to one key backwards to the profile with user.userprofile. Therefore, in your template you can show the display_name with.
{{ object.user.userprofile.display_name }}
To access username and slug first pass in the two keywords:
url(r'^/(?P<username>\d+)/(?P<slug>[-\w]+)/$', get_userpage, name='track-details'),
Then check if Track.objects.filter(slug=slug, username=username) returns anything:
def get_userpage(request, username, slug):
"""Render user page"""
user = User.objects.get(username=username)
track_song = Track.objects.filter(slug=trackslug, user=user).first()
if track_song:
# return song page for user
else:
# try to return user
track_user = Track.objects.filter(user=user).first()
if track_user:
# return user page
# if nothing returned above
# return 404
Previous suggestions:
you can you use get_object_or_404(Track, slug=slug) in your view to return the correct response.
you could also redirect a user to their unique combination of username and slug using:
redirect('track-username-slug', username=myusername slug=myslug, permanent=True)
where track-username-slug is your named url