How to put csrf_token inside django form view

Viewed 41

I am new in django and have faced a strange problem. If I create django template and insert {% csrf_token %} inside, it works well, but if I put @csrf_protect decorator to view, it gives me Forbidden 403 (CSRF verification failed. Request aborted). As I understand from django documentation, I can`t use both CsrfViewMiddleware and @csrf_protect.

So here is the question:

Is it possible to do csrf verification inside a view or should I always write templates in such situations?

@csrf_protect 
def create_group(request):
    if request.method == "POST":
        Group.objects.create(**{key: request.POST[key] for key in request.POST})
        return HttpResponseRedirect(reverse("groups:groups"))
    elif request.method == "GET":
        pass
    return HttpResponse(create_group_form)
create_group_form = """
    <form method="POST">
      <label for="course">Course:</label><br>
      <input type="text" id="course" name="course"><br><br>
      <label for="length_in_months">Length in months:</label><br>
      <input type="number" id="length_in_months" name="length_in_months" min=1 max=12 required><br><br>
      <label for="price">Price:</label><br>
      <input type="number" id="price" name="price" min=1000 max=50000 required><br><br>
      <label for="number_of_students">Number of students:</label><br>
      <input type="number" id="number_of_students" name="number_of_students" min=3 max=30 required><br><br>
      <label for="lesson_duration">Lesson duration:</label><br>
      <input type="number" id="lesson_duration" name="lesson_duration" min=1 max=5 required><br><br>
      <label for="website">Website:</label><br>
      <input type="url" id="website" name="website"><br><br>
      <input type="submit" value="Submit">
    </form> """
1 Answers

It's better to use CsrfViewMiddleware as an overall protection. If you forget to add the decorator to your views, it'll create security issues. You must use it on the views that assign CSRF tokens to the output and the ones that accept data from the POST form. So, as the best practice its better to use CSRF token in template unless we have a specific requirement.

Related