Django - details of one account showing up on another account - python

I've have a pet registration system where the customer can log into their account and register their animals. However once you have registered the animal and log out and another user logs in that user can see all the pets of all users. I'm not sure what's causing this.
my views.py
def customer_profile(request):
if request.method == "GET":
if request.user.is_authenticated:
get_pets = PetRegistration.objects.filter()
context = {
"pets": get_pets,
}
return render(
request, "registration/customer-profile.html", context=context
)
return redirect("login")
if request.method == "POST":
context = {}
return render(request, "registration/customer-signup.html", context=context)
def pet_register(request):
if request.method == "GET":
if request.user.is_authenticated:
form = PetRegistrationForm()
context = {
"form": form,
}
return render(request, "registration/pet-register.html", context=context)
return redirect("login")
if request.method == "POST":
form = PetRegistrationForm(request.POST, request.FILES)
context = {
"form": form,
}
if form.is_valid():
form = form.save(commit=False)
form.user = request.user
form.save()
return redirect("customer_profile")
return render(request, "registration/pet-register.html", context=context)
model.py
class PetRegistration(models.Model):
user = models.ForeignKey(Account, on_delete=models.CASCADE)
name = models.CharField(max_length=30)
image = models.ImageField(null=True, blank=True)
age = models.CharField(max_length=30)
animal_type = models.CharField(max_length=30)
vaccination_status = models.CharField(choices=STATUS, max_length=20)
def __str__(self):
return self.name

Related

How to update an item in django without creating a new item?

I'm trying to update an item(book) present in the database, Even though I've added instance so that a new item is not created but instead the item is only updated, but unfortunately it's not working as it is supposed to, Instead of updating the item, a new item is being created, am I missing something in here?
models.py
class Book(models.Model):
book_name = models.CharField(max_length= 100)
author_name = models.CharField(max_length=100)
publisher = models.CharField(max_length=100)
published_on = models.DateTimeField(blank=True, null=True)
Language = models.CharField(max_length=100)
image = models.ImageField(blank = True, upload_to='images/')
created = models.DateTimeField(auto_now_add = True)
def __str__(self):
return self.book_name
#property
def imageURL(self):
try:
url = self.image.url
except:
url = " "
return url
views.py
def book_register(request):
if request.method == 'POST':
form = BookForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('/')
else :
return render(request, 'crud_operation/book_form.html', {'form': form})
else:
form = BookForm()
context = {'form':form}
return render(request,'crud_operation/book_form.html',context)
def book_update(request,pk):
book = Book.objects.get(id=pk)
form = BookForm(instance = book)
if request.method == 'POST':
form = BookForm(request.POST, request.FILES, instance=book)
if form.is_valid():
form.save()
return redirect('/')
context = {'form':form}
return render(request, 'crud_operation/book_form.html',context)
urls.py
urlpatterns = [
path('create-book/',views.book_register, name = 'books'),
path('update-book/<int:pk>/',views.book_update, name = 'book_update'),
]
forms.py
class BookForm(ModelForm):
class Meta:
model = Book
fields = '__all__'
widgets = {
'published_on': DateInput(attrs={'type': 'date'})
}

Create #login_required like function for used Form(Modelform). So that User can't access confidential url without login-by typing just url?

I know that I can use #login_required but it is only used when we store user in User But in my case I stored model in form So it is not working for me. Also my created user is not getting authenticated when I use user.is_authenticated So I need custom login_required decorator which can be use to stop anyone from accessing direct url (confidential URl which are only accessed when you Login).
forms.py
class usrForm(forms.ModelForm):
password = forms.CharField(initial=123)
class Meta:
model = Person
fields = ('first_name','last_name','username','email','password','position')
def __init__(self, *args, **kwargs):
super(usrForm,self).__init__(*args,**kwargs)
self.fields['position'].empty_label = "Select"
class usrChange(forms.ModelForm):
class Meta:
model = Person
fields = ('username','password')
widgets= {
'password' : forms.PasswordInput(),
}
class loginForm(forms.ModelForm):
class Meta:
model = Person
fields = ('username','password')
widgets= {
'password' : forms.PasswordInput(),
}
models.py
class Position(models.Model):
title = models.CharField(max_length=50)
def __str__(self):
return self.title
class Person(models.Model):
first_name = models.CharField(max_length=50,default='')
last_name = models.CharField(max_length=50,default='')
username = models.CharField(max_length=50,default='')
password = models.CharField(max_length=50,default='')
email = models.EmailField(max_length=50)
position = models.ForeignKey(Position, on_delete=models.CASCADE)
def __str__(self):
return self.username
views.py
def user_list(request):
context = {'user_list' : Person.objects.all()}
return render(request, "usr_list.html", context)
def user_chnged_list(request):
form = usrForm(request.POST)
if form.is_valid():
form.save()
context = {'user_list' : Person.objects.all()}
return render(request, "usr_list.html", context)
def user_form(request, id=0):
if request.method == "GET":
if id ==0:
form = usrForm(initial={'password': 123}) # register
else:
auser = Person.objects.get(pk=id)
form = usrForm(instance=auser) #update
return render(request, "usr_form.html",{'form': form})
else:
if id == 0:
form = usrForm(request.POST , initial={'password': 123}) # register
else:
auser = Person.objects.get(pk=id) #update
form = usrForm(request.POST,instance=auser)
if form.is_valid():
form.save()
return redirect('login')
def user_delete(request,id):
auser = Person.objects.get(pk=id)
auser.delete()
return redirect('list')
def user_login(request):
form = loginForm()
if request.method == 'POST':
form = loginForm(data=request.POST)
if form.is_valid():
username=form.cleaned_data.get('username')
password=form.cleaned_data.get('password')
i = Person.objects.filter(username=username,password=password).exists()
user = {'user_list' : Person.objects.filter(username=username,password=password)}
if i == True:
j = Person.objects.filter(username=username, position_id = 1).exists()
if j == True:
return redirect('list')
return render(request,"usr_wlc.html", user )
else:
messages.error(request, 'Invalid username or password!')
context = {'form':form}
return render(request,'usr_login.html',context)
def user_detail(request,id):
auser = Person.objects.get(pk=id)
form = usrChange(request.POST,instance=auser)
if form.is_valid():
form.save()
return redirect('login')
def user_logout(request):
return redirect('/')
def user_change(request,id):
auser = Person.objects.get(pk=id) #update
form = usrChange(request.POST,instance=auser)
return render(request, "usr_chnge.html",{'form': form})

django: get() returned more than one Freelancers -- it returned 3

i am trying to assign a freelancer to a particular gig but it shows get() returned more than one Freelancers -- it returned 3!. I have tried getting the logged in freelancer to is trying to create the git like this freelancer = get_object_or_404(Freelancers, user=user) and before i save the form i assign the value like this new_form.creator = freelancer .
views.py
#login_required
def create_gig(request):
user = request.user
freelancer = get_object_or_404(Freelancers, user=user)
if request.method == "POST":
form = CreateGig(request.POST, request.FILES)
if form.is_valid():
new_form = form.save(commit=False)
new_form.user = request.user
new_form.creator = freelancer
new_form.slug = slugify(new_form.title)
new_form.save()
messages.success(request, f'Gig Created Successfully, Would be Live Soon')
return redirect('freelance:listings')
else:
form = CreateGig()
context = {
'form': form
}
return render(request, 'freelance/create.html', context)
models.py
class Gigs(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='gig_user')
creator = models.ForeignKey(Freelancers, on_delete=models.CASCADE, related_name='gig_creator')
title = models.CharField(max_length=1000, null=True, blank=True, verbose_name="Enter what you will do", default=" I will ")
In my code, it is getting a logged-in user instance and then creating the gig by assigning the freelancer to the created form.
#login_required
def create_gig(request):
freelancer = Freelancers.objects.get(user = request.user )
if request.method == "POST":
form = CreateGig(request.POST, request.FILES)
if form.is_valid():
new_form = form.save(commit=False)
new_form.creator = freelancer
new_form.slug = slugify(new_form.title)
new_form.save()
messages.success(request, f'Gig Created Successfully, Would be Live Soon')
return redirect('freelance:listings')
else:
form = CreateGig()
context = {
'form': form
}
return render(request, 'freelance/create.html', context)
You also don't need this line in your view:
new_form.user = request.user

how to exclude admin user from my user list

how to exclude admin users from my user list? the below image shows the problem. I don't want to show the admin user in the friend list of a user.
I don't want to show the main_admin user on this user list as it is my admin user of the site
views.py
from django.shortcuts import render, redirect, get_object_or_404
from .models import Profile
from feed.models import Post
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from django.conf import settings
from django.http import HttpResponseRedirect
from .models import Profile, FriendRequest
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
import random
User = get_user_model()
#login_required
def users_list(request):
users = Profile.objects.exclude(user=request.user)
sent_friend_requests = FriendRequest.objects.filter(from_user=request.user)
sent_to = []
friends = []
for user in users :
friend = user.friends.all()
for f in friend:
if f in friends:
friend = friend.exclude(user=f.user)
friends += friend
my_friends = request.user.profile.friends.all()
for i in my_friends:
if i in friends:
friends.remove(i)
if request.user.profile in friends:
friends.remove(request.user.profile)
random_list = random.sample(list(users), min(len(list(users)), 10))
for r in random_list:
if r in friends:
random_list.remove(r)
friends += random_list
for i in my_friends:
if i in friends:
friends.remove(i)
for se in sent_friend_requests:
sent_to.append(se.to_user)
context = {
'users': friends,
'sent': sent_to
}
return render(request, "users/users_list.html", context)
# def queryset(self, request):
# if request.user.is_superuser:
# return User.objects.filter(is_superuser=False)
# return User.objects.all()
def friend_list(request):
p = request.user.profile
friends = p.friends.all()
context = {
'friends': friends
}
return render(request, "users/friend_list.html", context)
#login_required
def send_friend_request(request, id):
user = get_object_or_404(User, id=id)
frequest, created = FriendRequest.objects.get_or_create(
from_user=request.user,
to_user=user)
return HttpResponseRedirect('/users/{}'.format(user.profile.slug))
#login_required
def cancel_friend_request(request, id):
user = get_object_or_404(User, id=id)
frequest = FriendRequest.objects.filter(
from_user=request.user,
to_user=user).first()
frequest.delete()
return HttpResponseRedirect('/users/{}'.format(user.profile.slug))
#login_required
def accept_friend_request(request, id):
from_user = get_object_or_404(User, id=id)
frequest = FriendRequest.objects.filter(from_user=from_user, to_user=request.user).first()
user1 = frequest.to_user
user2 = from_user
user1.profile.friends.add(user2.profile)
user2.profile.friends.add(user1.profile)
if FriendRequest.objects.filter(from_user=request.user, to_user=from_user).first():
request_rev = FriendRequest.objects.filter(from_user=request.user, to_user=from_user).first()
request_rev.delete()
frequest.delete()
return HttpResponseRedirect('/users/{}'.format(request.user.profile.slug))
#login_required
def delete_friend_request(request, id):
from_user = get_object_or_404(User, id=id)
frequest = FriendRequest.objects.filter(from_user=from_user, to_user=request.user).first()
frequest.delete()
return HttpResponseRedirect('/users/{}'.format(request.user.profile.slug))
def delete_friend(request, id):
user_profile = request.user.profile
friend_profile = get_object_or_404(Profile, id=id)
user_profile.friends.remove(friend_profile)
friend_profile.friends.remove(user_profile)
return HttpResponseRedirect('/users/{}'.format(friend_profile.slug))
#login_required
def profile_view(request, slug):
p = Profile.objects.filter(slug=slug).first()
u = p.user
sent_friend_requests = FriendRequest.objects.filter(from_user=p.user)
rec_friend_requests = FriendRequest.objects.filter(to_user=p.user)
user_posts = Post.objects.filter(user_name=u)
friends = p.friends.all()
# is this user our friend
button_status = 'none'
if p not in request.user.profile.friends.all():
button_status = 'not_friend'
# if we have sent him a friend request
if len(FriendRequest.objects.filter(
from_user=request.user).filter(to_user=p.user)) == 1:
button_status = 'friend_request_sent'
# if we have recieved a friend request
if len(FriendRequest.objects.filter(
from_user=p.user).filter(to_user=request.user)) == 1:
button_status = 'friend_request_received'
context = {
'u': u,
'button_status': button_status,
'friends_list': friends,
'sent_friend_requests': sent_friend_requests,
'rec_friend_requests': rec_friend_requests,
'post_count': user_posts.count
}
return render(request, "users/profile.html", context)
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been created! You can now login!')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
#login_required
def edit_profile(request):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'Your account has been updated!')
return redirect('my_profile')
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form,
}
return render(request, 'users/edit_profile.html', context)
#login_required
def my_profile(request):
p = request.user.profile
you = p.user
sent_friend_requests = FriendRequest.objects.filter(from_user=you)
rec_friend_requests = FriendRequest.objects.filter(to_user=you)
user_posts = Post.objects.filter(user_name=you)
friends = p.friends.all()
# is this user our friend
button_status = 'none'
if p not in request.user.profile.friends.all():
button_status = 'not_friend'
# if we have sent him a friend request
if len(FriendRequest.objects.filter(
from_user=request.user).filter(to_user=you)) == 1:
button_status = 'friend_request_sent'
if len(FriendRequest.objects.filter(
from_user=p.user).filter(to_user=request.user)) == 1:
button_status = 'friend_request_received'
context = {
'u': you,
'button_status': button_status,
'friends_list': friends,
'sent_friend_requests': sent_friend_requests,
'rec_friend_requests': rec_friend_requests,
'post_count': user_posts.count
}
return render(request, "users/profile.html", context)
#login_required
def search_users(request):
query = request.GET.get('q')
object_list = User.objects.filter(username__icontains=query)
context = {
'users': object_list
}
return render(request, "users/search_users.html", context)
Models.py
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils import timezone
from django.db.models.signals import post_save
from django.conf import settings
from autoslug import AutoSlugField
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
slug = AutoSlugField(populate_from='user')
bio = models.CharField(max_length=255, blank=True)
friends = models.ManyToManyField("Profile", blank=True)
def __str__(self):
return str(self.user.username)
def get_absolute_url(self):
return "/users/{}".format(self.slug)
def post_save_user_model_receiver(sender, instance, created, *args, **kwargs):
if created:
try:
Profile.objects.create(user=instance)
except:
pass
post_save.connect(post_save_user_model_receiver, sender=settings.AUTH_USER_MODEL)
class FriendRequest(models.Model):
to_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='to_user', on_delete=models.CASCADE)
from_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='from_user', on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return "From {}, to {}".format(self.from_user.username, self.to_user.username)
Here as you can see main_admin is my superuser and I don't want it to appear in the add new friend list, so please help me out to solve this problem as I'm new to django, Thank you
You just have to exclude the admin from the returned friends list :
def friend_list(request):
p = request.user.profile
friends = p.friends.exclude(user__is_staff=True)
context = {
'friends': friends
}
return render(request, "users/friend_list.html", context)
p.friends.all().exclude(is_superuser=True)
Make sure your user class parameter is using (AbstractUser).

How to edit user's profile page on django?

My django project has multiple functions, one of them lets the user update its profile(User model"first_name, username and email" Profile model" bio and profile picture") this used to perfectly work until I added a follow sistem, it is like the whole Profile and User model doesnt exist anymore so when trying to edit those fields, the code returns a AttributeError: 'User' object has no attribute 'profile' error, saying this line of code on the views.py file is wrong form1 = UpdateProfileForm(request.POST or None, request.FILES, instance=request.user.profile), I think I am missing something on there or there is probably there is something wrong.
views.py
def profile(request, username=None):
profile, created = Profile.objects.get_or_create(user=request.user)
user = User.objects.get(username=username)
if username:
post_owner = get_object_or_404(User, username=username)
user_posts = Profile.objects.filter(user_id=post_owner)
is_following = Following.objects.filter(user=request.user, followed=user)
following_obj = Following.objects.get(user=user)
follower = following_obj.follower.count()
following = following_obj.followed.count()
else:
post_owner = request.user
user_posts = Profile.objects.filter(user=request.user)
args1 = {
'post_owner': post_owner,
'user_posts': user_posts,
'follower': follower,
'following': following,
'connection': is_following,
}
return render(request, 'profile.html', args1)
def edit_profile(request):
profile, created = Profile.objects.get_or_create(user=request.user)
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
form1 = UpdateProfileForm(request.POST or None, request.FILES, instance=request.user.profile)
if form.is_valid and form1.is_valid:
form.save()
form1.save()
return redirect('profile')
else:
form = EditProfileForm(instance=request.user)
form1 = UpdateProfileForm(instance=request.user)
args = {
'form': form,
'form1': form1,
}
return render(request, 'profile-edit.html', args)
models.py
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank=True, default='default.png')
bio = models.CharField(max_length=400, default=1, null=True)
connection = models.CharField(max_length = 100, blank=True)
follower = models.IntegerField(default=0)
following = models.IntegerField(default=0)
def __str__(self):
return f'{self.user.username} Profile'
class Following(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
followed = models.ManyToManyField(User, related_name="followed")
follower = models.ManyToManyField(User, related_name="follower")
#classmethod
def follow(cls, user, another_account):
obj, create = cls.objects.get_or_create(user = user)
obj.followed.add(another_account)
print("followed")
#classmethod
def unfollow(cls, user, another_account):
obj, create = cls.objects.get_or_create(user = user)
obj.followed.remove(another_account)
print("unfollowed")
def __str__(self):
return f'{self.user.username} Profile'
forms.py
class EditProfileForm(UserChangeForm):
class Meta:
model = User
fields = (
'first_name',
'username',
'email',
)
exclude = ('password',)
class UpdateProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = (
'bio',
'profile_pic',
)
If you need to see more code please let me know;)
Try this:
def edit_profile(request):
profile, created = Profile.objects.get_or_create(user=request.user)
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
form1 = UpdateProfileForm(request.POST or None, request.FILES, instance=request.user.profile)
if form.is_valid() and form1.is_valid():
form.save()
form1.save()
return redirect('profile')
else:
form = EditProfileForm(instance=request.user)
form1 = UpdateProfileForm(instance=profile)
args = {
'form': form,
'form1': form1,
}
return render(request, 'profile-edit.html', args)
The solution I found temporarily to solve this problem is to just changed Profile's user object to OneToOneField and Following's user model to ForeignKey.

Categories

Resources