我试图创建一个web应用程序,用户可以在更新帖子时看到其他帖子。因此,我想在同一个模板中同时使用ListView和UpdateView。你知道吗
我的视图.py地址:
from django.shortcuts import render
from .models import Entry
from django.views.generic import ListView
from django.views.generic.edit import UpdateView
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
class index(LoginRequiredMixin, ListView):
template_name = 'diary/index.html'
context_object_name = 'entries'
def get_queryset(self): # def get_queryset(self, request):
return Entry.objects.filter(author=self.request.user)
class EntryUpdate(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Entry
fields = ['title', 'content']
template_name = 'diary/update.html'
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
else:
return False
我不知道我是否应该创建另一个视图,或者有一个内置的功能,所以,如果你们能帮助我,这将是非常有帮助的。你知道吗
任何帮助都将不胜感激!你知道吗
编辑:
我的ListView代码视图.py地址:
class index(LoginRequiredMixin, ListView):
template_name = 'diary/index.html'
context_object_name = 'entries'
def get_queryset(self):
return Entry.objects.filter(author=self.request.user)
我的更新视图视图.py地址:
class EntryUpdate(LoginRequiredMixin, MultipleObjectMixin,UserPassesTestMixin, UpdateView):
model = Entry
fields = ['title', 'content']
template_name = 'diary/update.html'
def get_queryset(self):
return Entry.objects.filter(author=self.request.user)
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
else:
return False
错误,我得到:
'EntryUpdate' object has no attribute 'object_list'
您可以在UpdateView中尝试
MultipleObjectMixin
。你知道吗您可以使用此mixin
get_queryset()
定义并访问模板中的object_list
。查看the documentation了解更多信息编辑
当然,这里有一个简短的代码示例:
以及模板:
demo/templates/demo/title_update_form_with_list.html
这就是我在模板中得到的(我的数据库中有10个“标题”,每个标题都带有随机字符):
编辑2 关于您编辑的问题,您的视图中缺少“object\u list”的定义,这是
MultipleObjectMixin
所要求的。你知道吗请注意,在我的代码示例
views.py
中,我用填充object_list
的查询定义了object_list
。我相信您收到的错误是因为mixin希望收到object_list
。你知道吗请尝试添加:
如果我没弄错的话,
get_queryset()
方法负责UpdateView
的对象检索,而object_list
与ListView
相关。你知道吗请尝试将
object_list
添加到您的视图中,并检查它是否解决了问题。你知道吗相关问题 更多 >
编程相关推荐