我在用着Django 2.0
我有一个模型Note
并使用通用更新视图来更新注释对象。
URL配置就像
app_name = 'notes'
urlpatterns = [
path('<int:pk>/', NoteUpdate.as_view(), name='update'),
]
可以通过它的命名空间设置访问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()
是检查条件的最佳地点还是get_query()
?