Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Django Login Required Mixin

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']
like image 762
Bronwyn Sheldon Avatar asked Nov 11 '17 23:11

Bronwyn Sheldon


1 Answers

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
like image 61
anjaneyulubatta505 Avatar answered Sep 20 '22 11:09

anjaneyulubatta505