Search code examples
pythondjangodjango-allauth

Displaying specific posts using django


I have a post application in django where different staff members can create post. I now want to be able display each posters post when they log in and not include others post.

model

class Post(models.Model):
    """docstring for Post."""
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) #blank=True, null=True)#default=1
    title = models.CharField(max_length = 120)
    slug = models.SlugField(unique= True)
    draft = models.BooleanField(default = False)
    publish = models.DateField(auto_now=False, auto_now_add=False)
    content = models.TextField()
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    #objects = PostManager()

    def __str__(self):
        return self.title

View

def index(request):
    results = Post.objects.all().filter(draft=False)#.filter(publish__lte=timezone.now())
    que = request.GET.get("q")
    if que:
        results =results.filter(
            Q(title__icontains=que)|
            Q(content__icontains=que)).distinct()
    paginator = Paginator(results, 8) # Show 25 contacts per page
    pages ="page"
    page = request.GET.get('page')
    try:
        query = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        query = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        query = paginator.page(paginator.num_pages)
    context = {
        "objects": query,
        "pages": pages
    }
    template = 'index.html'
    return render(request,template,context)

and additional code would be uploaded on request. Thanks


Solution

  • User will see only own posts

    results = Post.objects.all().filter(draft=False).filter(publish__lte=timezone.now())
    results = results.filter(user=request.user)