Getting all users from a Group - Django - django

I am trying to get the list of all users from the group "Manager", the post request works
#api_view(['GET','POST'])
def managers(request):
username = request.data['username']
if username:
user = get_object_or_404(User, username=username)
managers = Group.objects.get(name="Manager")
if request.method == 'POST':
managers.user_set.add(user)
elif request.method == 'DELETE':
managers.user_set.remove(user)
return Response({"message": "ok"})
return Response({"message": "error"}, status.HTTP_400_BAD_REQUEST)
I got this error below.
KeyError at /api/groups/manager/users 'username'
Please, can I get a guide?

In case it is a GET request, you can work with:
#api_view(['GET', 'POST', 'DELETE'])
def managers(request):
if request.method == 'GET':
users = User.objects.filter(groups__name='Manager')
serializer = UserSerializer(users, many=True)
return Response({'data': serializer.data})
username = request.data['username']
if username:
user = get_object_or_404(User, username=username)
managers = Group.objects.get(name='Manager')
if request.method == 'POST':
managers.user_set.add(user)
elif request.method == 'DELETE':
managers.user_set.remove(user)
return Response({"message": 'ok'})
return Response({'message': 'error'}, status.HTTP_400_BAD_REQUEST)
With UserSerializer a ModelSerializer for the User model.

For the benefit of others. Thank you Willem Van Onsem
users = User.objects.filter(groups__name='Manager')

Related

Displaying Django Models data in html file

I want to display data taken from my Django models in my html file. So in the code bellow instead of a 0 I want the donation model data. Can someone please help? Thank you! also if anyone knows a easier way please tell me. i can update my question again if anyone needs more details.
Views.py
from django.forms import ModelForm
# Create your views here.
def index(request,*args, **kwargs):
return render(request, "index.html", {} )
#login_required(login_url='/login/')
def myview(request,id):
data= userdetails.objects.get(id=id)
return render(request,'dashboard.html',{'data':data}
def register(request ):
if request.user.is_authenticated:
return redirect('/dashboard/')
else:
form = CreateUserForm()
if request.method == "POST":
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your account has been successfully created, {username} ')
return redirect('loginpage')
context = {'form': form}
return render(request, "register.html", context )
def loginpage(request):
if request.user.is_authenticated:
return redirect('/dashboard/')
else:
if request.method == 'POST':
username = request.POST.get('username')
password =request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('/dashboard')
else:
messages.error(request, 'Username OR password is incorrect')
context = {}
return render(request, 'login.html', context)
def logoutuser(request):
logout(request)
return HttpResponseRedirect('/login/')
#login_required(login_url='/login/')
def donate(request):
if request.method == "POST":
title = request.POST['donationtitle']
phonenumber = request.POST['phonenumber']
category = request.POST['category']
quantity = request.POST['quantity']
location = request.POST['location']
description = request.POST['description']
ins = Donation(title = title, phonenumber = phonenumber, category = category, quantity = quantity, location = location, description = description, user=request.user, )
ins.save()
return render(request,'donate.html')
Error:
File "C:\Users\jbtai\coding\GoodDeedWeb\home\views.py", line 30
def register(request ):
^
You need a view that handle that:
def myview(request):
id = request.user.id
data= userderails.objects.get(id=id)
return render(request,'dashboard.html',{'data':data}
Then in your template 'dashboard.html' you could show details:
{{data.donations}}
{{data.points}}
use this url for that view instead of the old one
path('dashboard/',views.myview, name = 'dashboard' ),

Send mail inside action django-rest-framework

I am using the Django REST framework and I'm trying to send a mail with sendgrid inside an action.
Here is my code:
#action(detail=True, methods=['GET', 'POST', 'DELETE'])
def invite(se1f, request, pk=None):
workspace = self.get_object()
if request.method == 'GET':
users = workspace.users.all()
serialized = UserSerializer(users, many=True)
return Response(status=status.HTTP_200_OK, data=serialized.data)
elif request.method == 'POST':
id = request.data.get('id', None)
if id:
#user = User.objectsoget(id=id)
user = get_object_or_404(User, id=id)
workspace.users.add(user)
return Response(status=status.HTTP_200_OK)
send_mail('Subject here', 'Here is the message.', 'from#examp1e.com', ['from#examp1e.com'],
fail_silently=False)
call send_mail() before the return statement.
#action(detail=True, methods=['GET', 'POST', 'DELETE'])
def invite(self, request, pk=None):
workspace = self.get_object()
if request.method == 'GET':
users = workspace.users.all()
serialized = UserSerializer(users, many=True)
return Response(status=status.HTTP_200_OK, data=serialized.data)
elif request.method == 'POST':
id = request.data.get('id', None)
if id:
#user = User.objectsoget(id=id)
user = get_object_or_404(User, id=id)
workspace.users.add(user)
send_mail('Subject here', 'Here is the message.', 'from#examp1e.com', ['from#examp1e.com'],fail_silently=False)
return Response(status=status.HTTP_200_OK)

How to perform more than one operation in django function view

I'm trying to perform 2 operation with in a single function view. But it perform only first operation. Which operation i mentioned first only that operation is executed second operation is not executed. Any other way to solve this problem.
def home_view(request):
if 'username' in request.session:
if 'username' in request.session:
username = request.session['username']
business_objs = AddBusiness.objects.all().values()
return render(request, 'home/index.html', {'business_objs': business_objs})
elif request.method == 'GET':
username = request.session['username']
form = ProfileForm(request.POST)
if form.is_valid():
profile_info = Profile.objects.filter(username=username).values()
for i in profile_info:
profiledict = i
return render(request, 'home/index.html',
{'profile_first_name': profiledict['first_name'],
'profile_last_name': profiledict["last_name"],
'profile_phone_number': profiledict['phone_number'],
'profile_email': profiledict['email'], 'profile_address': profiledict['address'],
'profile_image': profiledict['image']})
return redirect('/home/')
return redirect('/home/')
else:
return redirect('/login/')
I think you can try like this:
def home_view(request):
if 'username' in request.session:
if 'request.method == 'GET':
username = request.session['username']
business_objs = AddBusiness.objects.all().values()
return render(request, 'home/index.html', {'business_objs': business_objs})
elif request.method == 'POST':
username = request.session['username']
form = ProfileForm(request.POST)
if form.is_valid():
profile_info = Profile.objects.filter(username=username).values()
for i in profile_info:
profiledict = i
return render(request, 'home/index.html',
{'profile_first_name': profiledict['first_name'],
'profile_last_name': profiledict["last_name"],
'profile_phone_number': profiledict['phone_number'],
'profile_email': profiledict['email'], 'profile_address': profiledict['address'],
'profile_image': profiledict['image']})
return redirect('/home/')
return redirect('/home/')
else:
return redirect('/login/')
In that way, you will be able to handle both GET and POST request using this function based view. More information can be found in documentation.

'AnonymousUser' object has no attribute '_meta' when trying to update user

In my app I am getting an error when trying to update a user info.
my code is the following:
def CandidateSignIn(request, uidb64, token):
try:
uid = force_text(urlsafe_base64_decode(uidb64))
user = MyUser.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
if user is not None and account_activation_token.check_token(user, token):
user.is_active = True
user.save()
login(request, user)
registered = False
if request.method == "POST":
form = TeamMembersFormUpdate(data=request.POST, instance=request.user)
if form.is_valid():
user = form.save()
user.set_password(user.password)
user.save()
#registered = True
return HttpResponseRedirect(reverse('registration:HRlogin'))
else:
print("Error!")
else:
form = TeamMembersFormUpdate()
return render(request,'candidateSignIn.html',
{'form':form,
'registered':registered})
and apparently I am getting the error from the line
form = TeamMembersFormUpdate(data=request.POST, instance=request.user)
do you have any idea on how to solve this ?
You are logging the user in at line
11: login(request, user)
but the middleware will not be updated unless you return from the view you are in so you are getting the same anonymous user instance
so you just replace the request.user with 'user' that you got in the line 4
It will do thing right
...
if request.method == "POST" and user:
form = TeamMembersFormUpdate(data=request.POST, instance=user)
#rest here
#if you have no such user
else:
form = TeamMembersFormUpdate()
return render(request,'candidateSignIn.html',
{'form':form,
'registered':registered})

how to handle multiple requests in django at same time

if multiple users logs in and query for something at the same time, then how can i recognize which user queried for which thing.
i tried to make a group chat system. the idea is just to make a wall on which all users will post but the problem is how can i know which user requested to post if there r multiple users at same time.
my views.py-
def login(request):
if request.method == 'POST':
post = request.POST
u = user.objects.get(username = post['username'])
if post['password'] == u.password:
request.session['username'] = u.username
return redirect('wall')
else:
return render(request, 'wall/login_page.html')
def wall(request):
if request.method == 'POST':
post = request.POST
if 'logout' in post:
del request.session['username']
return redirect('home')
elif 'post' in post:
posted_by = request.session.get('username', '')
post_content = post['post_text']
post_id = posted_by+''+datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
p = user_post(posted_by = posted_by, post_content = post_content, post_id = post_id)
p.save()
return redirect('wall')
else:
if 'username' in request.session:
posts = user_post.objects.all()
return render(request, 'wall/wall_page.html', {'posts': posts})
else:
return redirect('error')
thanks in advance
request has a user attribute that indicates which user made the request (which may be the AnonymousUser if you don't require logins).