Is there a established way that i validate an object in the dispatch without making an extra database call when self.get_object()
is called later in get/post?
Here is what i have so far (slightly altered for this question):
class CourseUpdateView(UpdateView):
def dispatch(self, request, *args, **kwargs):
self.request = request
self.kwargs = kwargs
self.object = self.get_object()
if self.object.is_online:
messages.warning(request, "Sorry this one can't be updated")
return redirect("course:detail", pk=self.kwargs['pk'])
# this is going to call self.get_object again isn't it?
return UpdateView.dispatch(self, request, *args, **kwargs)
You can cache the result of get_object()
.
Here's a trivial example:
class CourseUpdateView(UpdateView):
# [...] your dispatch method
def get_object(self):
# it doesn't matter how many times get_object is called per request
# it should not do more than one request
if not hasattr(self, '_object'):
self._object = super(CourseUpdateView, self).get_object()
return self._object
来源:https://stackoverflow.com/questions/14836913/django-class-based-view-validate-object-in-dispatch