How to check if request user is in a models class
Lets say you have a class with name Car_club and in the class is members, which is a manytomany field to the User.
Then you want to limit some part of the page for only members.
class Car_club(models.Model):
members = models.ManyToManyField(User, on_delete=CASCADE
Lets say in the html there is parts where only the members of that class should see, how to manage that?
Updated
views.py
def car_clubs(request):
car_clubs = Car_clubs.objects.all()
team_members = user.Car_club_set.all()
context = {
'car_clubs': car_clubs,
'team_members': team_members,
}
return render(request, 'cars.html', context)
First what user.Car_club? I can get user from get_user_model, but then i get;
Type object 'User' has no attribute 'Car_club_set'?
Solution 1:
team_members is not needed to send via context
def car_clubs(request):
car_clubs = Car_clubs.objects.all()
context = {
'car_clubs': car_clubs,
}
return render(request, 'cars.html', context)
in your template (cars.html):
{% for car_club in car_clubs %}
{% if request.user in car_club.members.all %}
<p>{{car_club}}</p>
{% for member in car_club.members.all %}
<p>{{member}}</p>
{% endfor %}
{% endif %}
{% endfor %}
and you get the list of members for club_car, only if the user is in the members of that club.
or if wanna make the limit in view:
def car_clubs(request):
car_clubs = Car_clubs.objects.filter(members__id=request.user.id)
context = {
'car_clubs': car_clubs,
}
return render(request, 'cars.html', context)
this will return onlys the car_clubs that the user is in.