Reputation: 33655
How do I achieve the following....
Every time the points object is displayed in a template it must always be filtered by the current user. So, within the model I tried the code below.
Is this possible? how can I achieve the above?
Models.py
from django.db import models
from django.contrib.auth.models import User
POINTS_PENDING, POINTS_ADDED, POINTS_DEDUCTED, ORDER_PROCESSING = range(4)
STATUS_OPTIONS = (
(POINTS_PENDING, ('Pending')),
(POINTS_ADDED, ('Added')),
(POINTS_DEDUCTED, ('Deducted')),
(ORDER_PROCESSING, ('Processing')),
)
class PointsManager(models.Manager):
def points_list(self,User):
list = Points.objects.filter(points_user=User).exclude(status=ORDER_PROCESSING)
return list
class Points (models.Model):
user = models.ForeignKey(User)
points = models.IntegerField(verbose_name=("Points"), default=0)
created = models.DateTimeField(("Created at"), auto_now_add=True)
updated = models.DateTimeField(verbose_name=("Updated at"), auto_now=True)
objects = PointsManager()
Upvotes: 14
Views: 26867
Reputation: 11097
Another option is to create a mixin:
class OwnershipPermissionMixin(LoginRequiredMixin):
def get_queryset(self, *args, **kwargs):
request = args[0] if args else kwargs.get('request') or self.request
query = super().get_queryset(*args, **kwargs)
return query.filter(user=request.user)
And make the views (admin or classic) inherits from it. Then each time the queryset is evaluated, it will filter for owned objects only.
Upvotes: 0
Reputation: 55972
you could ensure that your views have a user by using
@login_required
decorator
then you could could query for points by user in your view
user_points = Points.objects.filter(user=request.user)
or using the reverse FK lookup
request.user.points_set.all()
Upvotes: 14