The variable is defined inside get_context_view()
since it requires an id
to access correct database object:
class FooView(TemplateView):
def get_context_data(self, id, **kwargs):
---
bar = Bar.objects.get(id=id)
---
def post(self, request, id, *args, **kwargs):
# how to access bar?
# should one call Bar.objects.get(id=id) again?
What would be the way to pass bar
variable to post()
?
Tried to save it as FooView's field and access it via self.bar
, but this doesn't do the trick. self.bar
is not seen by post()
You should reverse it. If you need bar
in post()
, you need to create it there:
class FooView(TemplateView):
def get_context_data(self, **kwargs):
bar = self.bar
def post(self, request, id, *args, **kwargs):
self.bar = Bar.objects.get(id=id)
...
post()
is called before get_context_data
, that's why post
doesn't see it if you define it in get_context_data
.
I know its late, but I faced this same problem few days ago. However here is my solution.
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['foos'] = self.object.filter()
return context
def post(self, request, *args, **kwargs):
context = super().post(request, *args, **kwargs)
foos = self.get_context_data().get('foos')
# do stuff here
return context
As knbk said, my solution was the dispatch method, there I define the variables that I will use in get_context_data and in post methods, that worked for me as a way to share data here my example
def dispatch(self, request, *args, **kwargs):
self.some_data = '123'
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super(MyTestCreateView, self).get_context_data(**kwargs)
print('test get_context_data', self.some_data)
def post(self, request, *args, **kwargs):
print('test post', self.some_data)
return super().post(request, *args, **kwargs)
Classy CBV I hope it helps
If the variable is defined in your CBV (Class Based View), it can directly be called in your template.
Views.py
class SomeRandomView(FormView):
username = 'SomeValue'
Template.html
<p>Username is {{view.username}}<p>
Sidenote: You can even call the methods in your view class directly within the template file which is after version 1.5 Django if I could recall correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With