我正在使用Django 2.0
我有一个模型Note
并使用通用更新视图来更新注释对象。
URL配置就像
app_name = 'notes'
urlpatterns = [
path('<int:pk>/', NoteUpdate.as_view(), name='update'),
]
可以通过qazxsw poi中的命名空间设置访问
app.urls
我想在加载视图或保存更新值之前在视图中进行一些条件检查。
因为,可以与任何用户共享注释,并且可以使用单个模板来查看和更新注释。我想检查用户是否是该笔记的所有者,或者该笔记是否已与该用户共享并且是否已授予写入权限。
/notes/<pk>
这是我在class NoteUpdate(UpdateView):
template_name = 'notes/new_note.html'
model = Note
fields = ['title', 'content', 'tags']
def get_context_data(self, **kwargs):
context = super(NoteUpdate, self).get_context_data(**kwargs)
"""
check if note is shared or is owned by user
"""
note = Note.objects.get(pk=kwargs['pk'])
if note and note.user is self.request.user:
shared = False
else:
shared_note = Shared.objects.filter(user=self.request.user, note=note).first()
if shared_note is not None:
shared = True
else:
raise Http404
context['note_shared'] = shared_note
context['shared'] = shared
return context
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(self.__class__, self).dispatch(request, *args, **kwargs)
尝试但它在get_context_data()
给KeyError
此外,pk=kwargs['pk']
是检查条件或get_context_data()
的最佳地方?
你不需要从kwargs获取pk,因为你的注释已经作为self.object存在,所以你的代码将是
get_query()
class NoteUpdate(UpdateView):
template_name = 'notes/new_note.html'
model = Note
fields = ['title', 'content', 'tags']
def get_context_data(self, **kwargs):
context = super(NoteUpdate, self).get_context_data(**kwargs)
"""
check if note is shared or is owned by user
"""
note = self.object
if note and note.user is self.request.user:
shared = False
else:
shared_note = Shared.objects.filter(user=self.request.user, note=note).first()
if shared_note is not None:
shared = True
else:
raise Http404
context['note_shared'] = shared_note
context['shared'] = shared
return context
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(self.__class__, self).dispatch(request, *args, **kwargs)
在哪里使用According to this good answer和get_query_set
:
get_query_set() 由ListViews使用 - 它确定要显示的对象列表。默认情况下,它只会为您指定的模型提供所有内容。通过重写此方法,您可以扩展或完全替换此逻辑。关于这个主题的Django文档。
get_context_data
get_context_data() 此方法用于填充字典以用作模板上下文。例如,ListViews将在上面的示例中将get_queryset()的结果填充为author_list。您可能最常重复使用此方法来添加要在模板中显示的内容。
class FilteredAuthorView(ListView):
template_name = 'authors.html'
model = Author
def get_queryset(self):
# original qs
qs = super().get_queryset()
# filter by a variable captured from url, for example
return qs.filter(name__startswith=self.kwargs.name)
然后在您的模板中,您可以引用这些变量。
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
data['page_title'] = 'Authors'
return data