I am trying to do what I think is a simple task:
Using FormView, I want to pass a url to the rendered page that is used to display an image next to the form. In the usual views, there is a context that you use to pass variables, but the FormView seems to be missing an easy way to do that. I have tried adding my variable in the get_context_data method, but I still can’t find the passed data in the template.
get_context_data is your means of adding data to the context when using the generic views.
If you post your get_context_data method and the snippet of the template where you’re trying to reference it, we might be able to help.
Also, when you post code snippets, please insert them between lines containing only 3 backticks - ```. (Make sure you use the backtick - ` and not the apostrophe - '.) That means you would have one line with the 3 backticks, your code, and then one more line with just the 3 backticks. That allows this forum software to format your code nicely:
# The line above this is just ```
def function(parm):
return parm
# The line after this is just ```
Sometimes you get so deep into the rabbit hole that it is completely dark. My last project with Django was somewhere around version 1.4, so it’s almost like a new platform. I just started using generic views and FormView is especially challenging. My confusion was how the context is retrieved in the template. So here is my get_context_data snippet:
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
context['image_url'] = self.request.GET['image']
return context
The ‘image’ is a parameter passed through the URL that calls this view. So this all worked fine.
In the template, the context is passed as a dictionary with keys of “form”, and “image_url”. Once I understood that it was just a matter of using a tag like {{ image_url }} to get the url.
Thank you for your quick response. I really love Django even though it is a harsh master at times.
Sounds like you’ve got it working, great!
One tip I’ll offer (no extra charge) - if you ever have questions about your context or what’s being rendered in a template, you’ll find that the Django Debug Toolbar is a fantastic tool and resource.
Ken
Oh, my. I just about forgot about that tool. Thanks.