im currently in the process of building a diary app in django. I have created multiple users (e.g User A and User B). However, when user A logs in, user A can see User B's entries.
How can i lock it down, so only User B can see User B's entries and when User A logs in, User A can have a personal entry view? (do i need to create a different view?)
views.py for my diary app:
from django.urls import reverse_lazy
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView,
)
from .models import Entry
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
# Create your views here.
class ELV(ListView):
model = Entry
queryset = Entry.objects.all().order_by("-date_created") #takes all the entries and orders it by date
template_name = 'entries\entry_list.html'
class EDV(DetailView):
model = Entry
template_name = 'entries\entry_detail.html'
class ECV(CreateView):
model = Entry
fields = ["title", "content"]
success_url = reverse_lazy("entry-list")
template_name = 'entries\entry_form.html'
class EUV(UpdateView):
model = Entry
fields = ["title", "content"]
template_name = 'entries\entry_update_form.html'
def get_success_url(self):
return reverse_lazy(
"entry-detail",
kwargs={"pk": self.object.pk}
)
class EntryDeleteView(DeleteView):
model = Entry
success_url = reverse_lazy("entry-list")
template_name = 'entries\entry_delete.html'
Does it have anything to do with user sessions? - i'm not sure, please help!
CodePudding user response:
Yes, you can do this easily. But before this you have to add an extra field in your Entry
model.
# models.py
from django.contrib.auth import get_user_model
User = get_user_model()
class Entry(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='entries', default=None)
# your other remaining fields
and make sure to run makemigrations
and migrate
commands after adding the new field. And in your views.py
file, add a get_queryset(self)
# Create your views here.
class ELV(ListView):
model = Entry
template_name = 'entries\entry_list.html'
def get_queryset(self):
return Entry.objects.filter(user=self.request.user).order_by("-date_created")
PS: And it's a good idea to add a LoginRequiredMixin
to make sure only the authenticated
got the access you ListView
from django.contrib.auth.mixins import LoginRequiredMixin
class ELV(LoginRequiredMixin, ListView):
# ...
Here is docs link
CodePudding user response:
I also needed to add this bit to my entry create view (ECV), once done, worked like a charm!
def form_valid(self, form):
form.instance.user = self.request.user
return super(ECV, self).form_valid(form)