class FolderUpdate(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
"""
This class is responsible for updating folder's name
and also showing links it contains. Additional data
is prepared in the get_context_data method.
"""
model = Folder
fields = ['title']
template_name = 'folders/folder_update_form.html'
raise_exception = True
def get(self, request, **kwargs):
"""
Add key 'folder_pk' to session dictionary to
pass to the LinkToArchive view for handling
in reverse function
"""
request.session['folder_pk'] = kwargs['pk']
return super().get(request, **kwargs)
def post(self, request, pk):
messages.info(request, 'Папка переименнована')
return super().post(request, pk)
def test_func(self):
obj = self.get_object()
return obj.linky_user_id == self.request.user.pk
def get_context_data(self):
"""
Add link objects to context for showing
in folder_update_form.html template
"""
links = self.object.link_set.filter(is_archived=False)
context = super().get_context_data()
context['links'] = links
return context
def get_success_url(self):
return reverse('folder_update', args=[self.kwargs['pk']])
FolderUpdate
. Вот это представление:class LinkToArchive(LoginRequiredMixin, UserPassesTestMixin, View):
"""
This view gets all links from a particular folder by
'folder_pk' session key passed from FolderUpdate view,
validate checkbox data from 'folder_update_form.html' page,
send links to archive and redirect to FolderUpdate view
"""
raise_exception = True
def post(self, request):
folder_pk = request.session['folder_pk']
link_qs = Link.objects.filter(folder_id=folder_pk)
form = LinkCheckBoxForm(link_qs, request.POST)
if form.is_valid():
send_link_to_archive(form.cleaned_data)
messages.info(request, 'Отправленно в архив')
else:
messages.warning(request, 'Что-то пошло не так')
return redirect(
reverse('folder_update', args=[folder_pk])
)
def test_func(self):
folder_pk = self.request.session['folder_pk']
user = Folder.objects.get(pk=folder_pk).linky_user
return self.request.user == user
FolderUpdate
должно работать с той же папкой которую обрабатывало представление LinkToArchive
. Вот для этого я и передаю folder_pk
в сессии. Возможно непонятно объяснил, но может комментарии в коде помогу. В любом случае спасибо за потраченное на меня время.