I'm using Django 2.0
I have a model Note
and using generic update view to update the note object.
The URL configuration is like
app_name = 'notes'
urlpatterns = [
path('<int:pk>/', NoteUpdate.as_view(), name='update'),
]
which is accessbile via it's namespace setup in app.urls
/notes/<pk>
I want to make some condition check in the view before loading the view or saving updated value.
Since, a note can be shared with any user and there is single template to view and update the note. I want to check for whether the user is owner of the note or whether the note has been shared with the user and has write permission granted.
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)
This is what I tried in get_context_data()
but it is giving KeyError
at pk=kwargs['pk']
Also, get_context_data()
is the best place to check for conditions or get_query()
?