Can you construct csrf from request object - csrf constructor exception?
<p>I am following an example of user registration and my code looks like this</p>

<pre><code>from django.views.decorators import  csrf
def register_user(request):
    args={}
    args.update(csrf(request)) #----&gt;Crashes here
    args["form"] = UserCreationForm()
    return render_to_response("register.html",args)
</code></pre>

<p>I get an exception at the statement </p>

<pre><code>args.update(csrf(request))
</code></pre>

<p>stating that the </p>

<pre><code>module object is not callable.
</code></pre>

<p>Any suggestions on what I might be doing wrong ?</p>

<p>There are two way to CSRF protect your django websites :</p>

<h1>1 - Using the middleware, the simplest way :</h1>

<p>The <code>django.middleware.csrf.CsrfViewMiddleware</code> automatically adds a CSRF token to the context.</p>

<p>This middleware is enabled by default in your <code>settings.py</code> file and you can directly use this token in your template.</p>

<p><strong>With this solution you have nothing to do but using the {% csrf_token %} tag in your template as bellow.</strong></p>

<h1>2 - Using the <code>csrf_protect</code> decorator :</h1>

<p>If you deactivate the middleware (which is not recommended), you can still use the <code>csrf_protect</code> decorator (It seems it's the solution you're trying, but not with its correct import as Danielle pointed out).</p>

<p>But your problem seems to be that you don't use it as you should.</p>

<p>It's a <strong>decorator</strong>, i-e a function that returns a modified version of a function passed as parameter. Here you're passing it a request object.</p>

<p>With Python, you canuse a decorator this way :</p>

<pre><code>@decorator
def function([...]):
    [...]
</code></pre>

<p>So your view should look like :</p>

<pre><code>@csrf_token
def your_view(request, *args, **kwargs):
    # Your view code
</code></pre>

<h1>Using the <code>{% csrf_token %}</code> tag :</h1>

<p>After using one of these solutions, you can directly use the <code>{% csrf_token %}</code> tag in your template since the csrf token should be in your context at template rendering (thanks to either the middleware or the <code>csrf_protect</code> decorator) :</p>

<pre><code>&lt;form&gt;
  {% csrf_token %}
  {{ form.as_p }}
  &lt;input type="submit" value="Submit" /&gt;
&lt;/form&gt;
</code></pre>

<p>Here is more about CSRF protections with Django :</p>

<p><a href="https://docs.djangoproject.com/en/1.10/ref/csrf/" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/csrf/</a></p>

<p>and here is more about decorators with Python :</p>

<p><a href="https://wiki.python.org/moin/PythonDecorators" rel="nofollow">https://wiki.python.org/moin/PythonDecorators</a></p>

python django