darl1ne
darl1ne

Reputation: 416

How do I restrict access in django?

I have an application in which all users, after registration, can publish articles, how can I make it so that only those who have the rights for this can publish (something like ordinary users and moderators / editors and how to grant these rights. Below is the attached code:

models.py/blogapp

 class Post(models.Model):
        title = models.CharField(verbose_name=("Заголовок"), max_length=200)
        author = models.ForeignKey(User, on_delete=models.CASCADE)
        header_image = models.ImageField(verbose_name=("Заглавное Изображение"), null=True, blank=True, upload_to="images/" )
        body = RichTextField(verbose_name=("Тело Статьи"), blank=True, null=True)
        #body = models.TextField(blank=True, null=True)
        post_date = models.DateTimeField(auto_now_add=True)
        category = models.CharField(verbose_name=("Категория"), max_length=200)
        snippet = models.CharField(verbose_name=("Фрагмент Статьи"), max_length=200)
        likes = models.ManyToManyField(User, related_name='blog_post')
        updated_on = models.DateTimeField(auto_now= True)
        
    
        def total_likes(self):
            return self.likes.count()
    
    
        def __str__(self):
            return self.title + ' | ' + str(self.author)
    
        def get_absolute_url(self):
            return reverse('article_detail', args=[str(self.id)])

views.py/members

class CreateProfilePageView(CreateView):
    model = Profile
    form_class = ProfilePageForm
    template_name = "registration/create_user_profile.html"
    #fields = '__all__'

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

class EditProfilePageView(generic.UpdateView):
    model = Profile
    template_name = 'registration/edit_profile_page.html'
    fields = ['bio', 'profile_pic', 'website_url', 'instagram_url', 'twitter_url', 'status',  'age']

    success_url = reverse_lazy('home')

class ShowProfilePageView(DetailView):
    model = Profile
    template_name = 'registration/user_profile.html'

    def get_context_data(self, *args, **kwargs):
        #users = Profile.objects.all()
        context = super(ShowProfilePageView, self).get_context_data(*args, **kwargs)

        page_user = get_object_or_404(Profile, id=self.kwargs['pk'])

        context["page_user"] = page_user
        return context

class PasswordsChangeView(PasswordChangeView):
    form_class = PasswordChangingForm
    #form_class = PasswordChangeForm
    success_url = reverse_lazy('password_success')
    #success_url = reverse_lazy('home')

def password_success(request):
    return render(request, 'registration/password_success.html', {})

class UserRegisterView(generic.CreateView):
    form_class = SignUpForm
    template_name = 'registration/registr.html'
    success_url = reverse_lazy('login')


class UserEditView(generic.UpdateView):
    form_class = EditProfileForm
    template_name = 'registration/edit_profile.html'
    success_url = reverse_lazy('home')

    def get_object(self):
        return self.request.user

views.py/blogapp

class HomeView(ListView):
    model = Post
    queryset = Post.objects.filter(draft=False)
    cats = Category.objects.all()
    template_name = 'home.html'
    ordering = ['-post_date']
    paginate_by = 6

    def get_context_data(self, *args, **kwargs):
        cat_menu = Category.objects.all()
        context = super(HomeView, self).get_context_data(*args, **kwargs)
        context["cat_menu"] = cat_menu
        return context

def CategoryListView(request):
    cat_menu = Category.objects.all()
    return render(request, 'category_list.html', {'cat_menu':cat_menu})


def CategoryView(request, cats):
    category_posts = Post.objects.filter(category = cats). order_by('-post_date')
    return render(request, 'categories.html', {'cats':cats.title(), 'category_posts':category_posts})


class ArticleDetailView(HitCountDetailView):
    model = Post
    template_name = 'post_detail.html'
    count_hit = True


    def get_context_data(self, *args, **kwargs):
        cat_menu = Category.objects.all()
        context = super(ArticleDetailView, self).get_context_data(*args, **kwargs)

        stuff = get_object_or_404(Post, id=self.kwargs['pk'])
        total_likes = stuff.total_likes()

        context["cat_menu"] = cat_menu
        context["total_likes"] = total_likes
        return context



class AddPostView(CreateView):
    model = Post
    form_class = PostForm
    template_name= 'add_post.html'
    #fields = '__all__'

class AddCommentView(CreateView):
    model = Comment
    form_class = CommentForm
    template_name= 'add_comment.html'

    def form_valid(self, form):
        form.instance.post_id = self.kwargs['pk']
        return super().form_valid(form)

    def get_success_url(self):
        return reverse_lazy('article_detail', kwargs={'pk': self.kwargs['pk']})

class AddCategoryView(CreateView):
    model = Category
    template_name= 'add_category.html'
    fields = '__all__'


class UpdatePostView(UpdateView):
    model = Post
    template_name = 'update_post.html'
    form_class = EditForm
    #fields = ['title', 'body']

class DeletePostView(DeleteView):
    model = Post
    template_name = 'delete_post.html'
    success_url = reverse_lazy('home')

If you need any more code, I will attach it, thanks, and forgive my english)

Upvotes: 0

Views: 130

Answers (1)

Ankit Tiwari
Ankit Tiwari

Reputation: 4690

Hello asd you can add flags like this in your Profile Model like this

class Profile(models.Model):
    user = models.ForeignKey(User,on_delete=models.PROTECT)
    is_moderator = models.BooleanField(default=False)
    is_editor = models.BooleanField(default=False)#you can add many more as you want

and you can validate user in template or in views like this in views.py

def check_user(request):
    moderator_profile = Profile(user_id=request.user.id,is_moderator=True)
    editor_profile = Profile(user_id=request.user.id,is_editor=True)
    if user_profile:
        return redirect('url_for_moderator')
    elif editor_profile:
        return redirect('url_for_editor')

OR

you can pass data to the template and give certain functionality for certain user like this

in your views.py

def get_post(request):
    user_profile = Profile.objects.filter(user=request.user.id)
    return render(request,"post.html",{"user_profile":user_profile})

and inside post.html

{% if user_profile.is_editor or user_profile.is_moderator %}
<button>Edit</button>
{% endif %}

if you don't like this way you can do it in better way check this post https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html

Upvotes: 1

Related Questions