【发布时间】:2017-12-22 15:00:35
【问题描述】:
我正在使用Django 2.0
我有一个模型 Note 并使用通用更新视图来更新注释对象。
网址配置是这样的
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() 中尝试过的,但它在 pk=kwargs['pk']
KeyError
另外,get_context_data() 是检查条件的最佳位置还是get_query()?
【问题讨论】:
标签: django django-generic-views django-2.0