0

So basically I want non logged in users to be sent to the login page when they attempt to access pages like the create post or profile page. I know how this is done with function based views, but I am curious how I could do this in CBV's.

class CreatePostView(LoginRequiredMixin,CreateView):
    # ... view here

I was wondering how I would redirect users if not logged in

Would I need another function to do this, or is there something in Django that allows this to happen? Thanks :)

jeremy_lord
  • 469
  • 7
  • 23
  • check this https://stackoverflow.com/questions/37596791/redirect-anonymous-users-to-log-in-dont-show-them-anything – Nalin Dobhal Sep 23 '19 at 08:29
  • `class CreatePostView(LoginRequiredMixin,CreateView):` will automatically redirect anonymous users to the login page. Just set [`LOGIN_REDIRECT_URL`](https://docs.djangoproject.com/en/2.2/ref/settings/#login-redirect-url) in settings, or set `login_url` in the view. – Alasdair Sep 23 '19 at 09:28

1 Answers1

0

you can do this in your views.py

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = posts
    fields = ['Title','Post_content']

    def form_valid(self, form):
        form.instance.Name = self.request.user
        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.Name:
            return True
        return False
Marcell Erasmus
  • 866
  • 5
  • 15
Mugoya Dihfahsih
  • 425
  • 3
  • 11