簡體   English   中英

如何在django中獲取當前用戶的帖子

[英]How to get post of only current user in django

我希望所有用戶只能看到他們自己的列表,我從 django 收到錯誤,我不知道為什么。 我還想在我無法做到的同一頁面上創建視圖和列表視圖。 我也需要幫助。 謝謝你

這是我的 model.py:-

from django.db import models
from django.contrib.auth import get_user_model
from django.conf import settings
from django.urls import reverse
# Create your models here.


class simpleList(models.Model):
    title = models.CharField(max_length=250)
    author = models.ForeignKey(
        get_user_model(),
        on_delete=models.CASCADE,
    )

    def __str__(self):
        return self.title

這是我的 views.py:-

from django.shortcuts import render
from django.views.generic import ListView, CreateView
from .models import simpleList
from django.urls import reverse_lazy
# Create your views here.


def ListListView(request):
    current_user = request.author
    user_list = simpleList.objects.filter(user=current_user)
    return render(render, 'templates/list_list.html', {'userlist': user_list})


class CreateList(CreateView):
    model = simpleList
    template_name = 'create_list.html'
    fields = ('title', )
    success_url = reverse_lazy('create_list')

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

這是我的 urls.py:-

from django.urls import path
from .views import ListListView, CreateList

urlpatterns = [
    path('', ListListView, name='list_list'),
    path('create/', CreateList.as_view(), name='create_list'),
]

我從 django 控制台得到的錯誤:-

AttributeError at /lists/
'WSGIRequest' object has no attribute 'author'

試試這個:

def ListListView(request):
    current_user = request.user
    user_list = simpleList.objects.filter(author=current_user)
    return render(render, 'templates/list_list.html', {'userlist': user_list})

您的問題出現在這 2 行中:

 current_user = request.author
 user_list = simpleList.objects.filter(user=current_user)

請求字典沒有作者姓名。

應該是request.user:

 current_user = request.user
 user_list = simpleList.objects.filter(author=current_user)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM