Thomas K
Thomas K

Reputation: 1117

Django : Call a view from a template

How to call a view in my layout (template) ?

For example : I've a form on every pages of my website. I need to generate CSRF token for each pages but I don't want to put the generation code on every view.

Thank you.

Upvotes: 0

Views: 630

Answers (2)

keithxm23
keithxm23

Reputation: 1280

In Django, once you reach the template, I don't believe you can call something to the effect of Zend's Action Helper. Obviously, you could do an AJAX call to an exposed url in Django and retrieve the necessary data. In that case you can provide the csrf token to the ajax calls as follows..

$.ajaxSetup({data: {csrfmiddlewaretoken: '{{ csrf_token }}' },});

I'm not a hundred percent sure but you can implement something like Zend's Action Helper in a decorator (which could be applied to multiple views of your choice before processing the request) or in a context processor (which is applied to all views' processed request).

Upvotes: 1

M Somerville
M Somerville

Reputation: 4610

If your form is just HTML, then simply have a template containing the HTML and include that from other templates (or have it in your base template). To generate a CSRF token, you simply use {% csrf_token %} in the template, as explained at https://docs.djangoproject.com/en/dev/ref/contrib/csrf/

If you want to generate the HTML of a Django form, then you could add a context processor - explained at https://docs.djangoproject.com/en/dev/ref/templates/api/#subclassing-context-requestcontext - that generates the form and then that will be available to all templates.

def form_processor(request):
    form = Form()
    return { 'form': form.as_p() }

Template:

<form>{% csrf_token %}{{ {{ form }}</form>

Upvotes: 0

Related Questions