Search code examples
pythondjangoweb-deployment

Django limit acces to data for owner


i'm trying to make query for user in Django, but still every user can see all data from data base. I've tried with filters, q objects, but none of these helped me.

Here is my model:

class Book(models.Model):
    def __str__(self):
        return f'{self.bookIdent} - belonging to: {self.user}'

    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    bookIdent = models.CharField(max_length=255)
    bookshelf = models.ForeignKey(BookShelf, default='', on_delete=models.CASCADE)

    @classmethod
    def total_info(cls):
        return cls.objects.aggregate(book_counter=Count('id'))

    class Meta:
        verbose_name_plural = "Books"

And my views:

@login_required(login_url="/login/")
def index(request):

    context = {'segment': 'index'}
    html_template = loader.get_template('dashboard.html')

    context.update(dict(Book.total_info()))
    context['Book'] = set_pagination(request,Book.objects.all().
        filter(user=request.user), item_numer=10)

    return HttpResponse(html_template.render(context, request)) 

I would like to make query that only user from book class could see his books.

Template:

                    <div class="col-xl-3 col-md-6">
                        <div class="card card-stats">

                            <div class="card-body">
                                <div class="row">
                                    <div class="col">

                                        <h5 class="card-title text-uppercase text-muted mb-0">Book quantity:</h5>

                                        <span class="h2 font-weight-bold mb-0">

                                            {{ book_counter|default:0 }}

                                        </span>

                                    </div>

Solution

  • In your views.py, you can do

    books = Book.objects.filter(user=request.user)
    context['book_counter'] = books.count()