17

I have a class based view which I would like to make accessible only when a user is logged in, and I would like to redirect unauthenticated users back to the index page

This is the view in question:

class ArtWorkCreate(CreateView, LoginRequiredMixin):
    login_url = '/login/'
    redirect_field_name = 'login'
    model = ArtWork
    fields = ['userID','title','medium','status','price','description']

This is the related Model

class ArtWork(models.Model):
    userID= models.ForeignKey(MyUser, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    medium = models.CharField(max_length=50)
    price = models.FloatField()
    description = models.TextField(max_length=1000)
    status = models.CharField(max_length=4, default="SALE")

    def __str__(self):
        return self.title

And this is the related URL

 url(r'artwork/add/$', ArtWorkCreate.as_view(), name='artwork-add'),

and this is the URL I would like to redirect to where the user is NOT logged id

  url(r'^index/$', views.index, name='index'),

My goal is to make the form only accessbile to logged in user where they can only add an artwork item under their own name

and lastly this is the model form

class ArtWorkForm(ModelForm):
    class Meta:
        model = ArtWork
        fields = ['title','medium','status','price','description']
Bronwyn Sheldon
  • 181
  • 1
  • 1
  • 4
  • Possible duplicate of [Best way to make Django's login\_required the default](https://stackoverflow.com/questions/2164069/best-way-to-make-djangos-login-required-the-default) – Withnail Nov 12 '17 at 00:40
  • Not the solution, but you should put the mixins before the CreateView (or other class based view) – schrodingerscatcuriosity Nov 12 '17 at 01:03
  • (https://docs.djangoproject.com/en/1.11/topics/auth/default/#the-loginrequired-mixin)[https://docs.djangoproject.com/en/1.11/topics/auth/default/#the-loginrequired-mixin] – schrodingerscatcuriosity Nov 12 '17 at 01:08

3 Answers3

26

We should inherit the LoginRequiredMixin first. because python will consider the method dispatch from the first inherited class(in this case).

from django.contrib.auth.mixins import LoginRequiredMixin

class ArtWorkCreate(LoginRequiredMixin, CreateView):
    login_url = '/index/'
    redirect_field_name = 'index'
    model = ArtWork
jwinn
  • 1,135
  • 3
  • 14
  • 30
anjaneyulubatta505
  • 10,713
  • 1
  • 52
  • 62
5

Just Define a Login url on the settings.py file (also remove the login url on the class)

#settings.py

LOGIN_URL = 'login'
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
0

login_url is URL that users who don’t pass the test/authentication will be redirected to.

redirect_field_name attribute should be set to URL the user should be redirected to after a successful login.

Source:https://docs.djangoproject.com/en/3.0/topics/auth/default/#django.contrib.auth.mixins.AccessMixin.get_login_url

Sandesh
  • 9
  • 1
  • 2