raeraygoaway
raeraygoaway

Reputation: 3

How to edit my views.py so that unauthorized users can see posts made public?

I have added a 'public' attribute to my models.py to allow users to make their posts public. I am trying to modify my views.py so that public posts are visible to unauthorised users.

Here is my code:

views.py

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import Http404

from .models import BlogPost
from .forms import BlogPostForm

def check_post_owner(request, post):
    if post.owner != request.user:
        raise Http404

@login_required()
def index(request):
    """Home Page for blogs"""
    posts = BlogPost.objects.filter(owner=request.user).order_by('date_added')
    context = {'posts': posts}
    return render(request, 'blogs/index.html', context)

models.py

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class BlogPost(models.Model):
    """A blog post"""
    title = models.CharField(max_length=30)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    public = models.BooleanField(default=False)

    def __str__(self):
        return self.title

Upvotes: 0

Views: 43

Answers (2)

bmons
bmons

Reputation: 3392

remove the login required decorator and try this way

def index(request):
    """Home Page for blogs"""
    if request.user.is_authenticated:
        posts = BlogPost.objects.filter(owner=request.user).order_by('date_added')
    else:
        posts = BlogPost.objects.filter(public=True).order_by('date_added')
    return render(request, 'blogs/index.html', {'posts': posts})

Upvotes: 1

sefailyasoz
sefailyasoz

Reputation: 69

you can filter the BlogPost by (public=True) that should work. so it should be like

posts = BlogPost.objects.filter(owner=request.user, public=True).order_by('date_added')

Upvotes: 0

Related Questions