TransWikia.com

Django differentiating between user and template condtion

Stack Overflow Asked by mozadded on October 22, 2020

Let’s say you are creating a blogsite and you want to add a special feature that the original author of blog can give permission to edit that article to other authors.
Authors can create and publish their own blog and edit others’ blog if they are assigned to edit by original author.
So that blog can be viewed by all but the edit button can only be accessed by the author and the editors of that article. What will be your method?

I tried to create some models named Author, Editor, Blog. Now, I created an one to one relationship between user and author as well as author and editor, then created a many to many relationship between blog and editor and a many to one relationship between blog and author.

Then I created a view of blogs objects and rendered it to the template and in template I put a if condition to check if the logged in user is that blog’s author or editor, but this condition is not working.

models.py ->

class Author(models.Model):

user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, 
         blank=True)
name = models.CharField(max_length=36, blank=True, null=True)
email = models.EmailField(null=True, blank=True)
username = models.CharField(max_length=13, unique=True)
date_created = models.DateTimeField(auto_now_add=True)


def __str__(self):
    return self.username



 class Editor(models.Model):

 name = models.OneToOneField(Author, on_delete=models.CASCADE, null=True, 
        blank=True)

class Blog(models.Model):

title = models.CharField(max_length=150, null=True, blank=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True, 
           blank=True)
editor = models.ManyToManyField(Editor, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
article = models.TextField(blank=True, null=True)
genre = models.ManyToManyField(Genre, blank=True)


def __str__(self):
    return self.title

views.py ->

def blog(request, pk):


if request.user.is_authenticated:
    blogs = Blog.objects.get(id=pk)
    

context = {'blogs':blogs}
return render(request, 'blog/blog.html', context)

template ->

{% if request.user.author == blogs.author or blogs.editor %}
   <a href="#" class="btn btn-warning">Edit</a>
{% endif %}

you can suggest me other ideas to do it as well.

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP