Reputation: 4139
Is there a way to access the model instance that is going to be presented in a generic.DetailView in views.py before the template gets rendered? Something like the hypothetical function here:
class MyModelDetailView(LoginRequiredMixin, generic.DetailView):
model = MyModel
template_name_suffix = '_details'
def do_some_initial_stuff(model_instance):
# do stuff to model_instace,
# like assigning fields, creating context variables based on existing fields, etc.
Ultimately, I would like have a user click a button for a specific model instance in one template, then get directed to this generic.DetailView template where the model is presented with some of its field values changed and some other stuff (eg. the model may have a field that acknowledges that the this user clicked the button in the previous template). Suggestions on the most efficient way to do this would be appreciated. Thanks :)
Upvotes: 5
Views: 5024
Reputation: 946
If you want to make certain changes only if a button is clicked in the previous view then you can make use of the Django sessions. Add the needed value to the sessions dict.
request.session['button_clicked'] = True
For making changes in the current context of view it can be done by overriding get_context_data().
Like:
class MyModelDetailView(LoginRequiredMixin, generic.DetailView):
model = MyModel
template_name_suffix = '_details'
def get_context_data(self):
context = super(MyModelDetailView, self).get_context_data()
# Object is accessible through self.object or self.get_object()
if request.session.pop('button_clicked', False):
myobject = self.object
# The alteration you make on myobject wont be saved until you save it using myobject.save()
# Alter the object using myobject and alter the context varible like this:
context['object'] = myobject
context['myvar'] = "My Variable"
# Then return
return context
More about Django Sessions: https://docs.djangoproject.com/en/1.11/topics/http/sessions/
Upvotes: 4