简体   繁体   中英

Blog on Django, querysets for fetch logged in user's posts

I'm building a blog on Django and know i have to make a personal page for see all the posts published by the user we're logged in now. I'm using some querysets so. Her my code

my models.py

from django.db import models
from django.conf import settings
from django.utils import timezone

class Post(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

def publish(self):
    self.published_date = timezone.now()
    self.save()

def __str__(self):
    return self.title

Here my forms.py

from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User

from .models import Post

class CreateUserForm(UserCreationForm):
    class Meta:
        model = User
        fields = ['username','email','password1','password2','user_permissions','is_staff','date_joined']

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'text', 'author']

And that's the view which is gonna filter the posts in base of the logged user

from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.utils import timezone

from .forms import CreateUserForm
from .models import Post
from .forms import PostForm

def user_data(request, pk):
   user_data = User.objects.get(pk=pk)
   posts = user_data.post_set.filter(author=user_data)
   context = {'user_data':user_data, 'posts':posts}
   return render(request, 'account/user_data.html', context)




#So it returns me just the user data like name, email or date_joined but not his posts

This should give you posts of logged in users from your view

def user_data(request, pk):
   posts=Post.objects.filter(author=request.user)
   context = {'posts':posts}
   return render(request, 'account/user_data.html', context)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM