Using Django Login Required Mixin

16,073

Solution 1

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

Solution 2

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

#settings.py

LOGIN_URL = 'login'

Solution 3

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

Share:
16,073

Related videos on Youtube

Bronwyn Sheldon
Author by

Bronwyn Sheldon

Updated on June 04, 2022

Comments

  • Bronwyn Sheldon
    Bronwyn Sheldon about 2 years

    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']