0

Why in the presence of {% csrf_token%} I get is the following error?

Forbidden (403) CSRF verification failed. Request aborted.

This is an example view that I use, so long.

view.py

def editModel(self,request, offset):
        if 'user' in request.session :
             user = request.session['user']
            if request.method == 'POST':
                if 'editModel' in request.POST:
                    offset = int(offset)
                    fields = ProfilModel.objects.filter(name=user)
                    workingModelsFiles = WorkingWithModelsFiles()
                    listModel = workingModelsFiles.getCurrentModel(user, offset)
                    modelView = self.listModels(user)[offset-1]
                    loadModels = "document.getElementById('x3dElement" + str(offset) + "').runtime.showAll();"
                    params = {'id ': offset,
                              'userName' : request.session['user'],
                              'surname' : fields[0].surname,
                              'listModel': listModel,
                              'model': modelView,
                              'bodyLoadModels': loadModels
                              }
                    params.update(csrf(request))
                    return render_to_response('editModel.html', params)

            else:
                offset = int(offset)
                fields = ProfilModel.objects.filter(name=user)
                workingModelsFiles = WorkingWithModelsFiles()
                listModel = workingModelsFiles.getCurrentModel(user, offset)
                modelView = self.listModels(user)[offset-1]
                loadModels = "document.getElementById('x3dElement" + str(offset) + "').runtime.showAll();"
                params = {'id ': offset,
                          'userName' : request.session['user'],
                          'surname' : fields[0].surname,
                          'listModel': listModel,
                          'model': modelView,
                          'bodyLoadModels': loadModels
                          }
                params.update(csrf(request))
                return render_to_response('editModel.html', params)
        else:
            return HttpResponseRedirect("/login/")

It is present in the template {% csrf_token %} yet again gives me an error on csrf

template.html

......
<div class="tab_container">
            <div id="tab1" class="tab_content">
                <table class="tablesorter" cellspacing="0"> 
                <tbody> 
                <form action="{% url 'edit_model' listModel.0.id_model  %}"  method="post" >
                {% csrf_token %}
                    {% for item in listModel %} 
                        <tr>
                            <td rowspan="3" style="width: 300px;"> {{ model | safe }} </td>
                            <td> Name Model: <i><input class="text_field" type="text" id='id_Model' name="Model" value="{{ item.modelName }}" /> </i> </td>
                        </tr>

                        <tr>
                            <td>  Author:  <i> <input class="text_field" type="text" id='id_Author' name="Author" value="{{ item.author }}" /> </i> </td>
                        </tr>
                        <tr>
                            <td> <input type="submit" name="editModel" value="Edit" /> </td>
                        </tr>
                    {% endfor %}
                </form>
                </tbody> 
                </table>
            </div><!-- end of #tab1 -->
.......

settings.py

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
Krasimir
  • 1,806
  • 2
  • 18
  • 31
  • make sure `MIDDLEWARE_CLASSES contains` `'django.middleware.csrf.CsrfViewMiddleware',` in your settings.py – Crazyshezy Jan 12 '13 at 16:38
  • Have you tried using `render_to_response` with `RequestContext` to do csrf_token processing instead of doing it manually using `params.update(csrf(request))`? – zaphod Jan 12 '13 at 17:01

1 Answers1

0

Have you tried to use a RequestContext instead of params.update(csrf(request))? Like:

params = {'id ': offset,
          'userName' : request.session['user'],
          'surname' : fields[0].surname,
          'listModel': listModel,
          'model': modelView,
          'bodyLoadModels': loadModels
          }
ctx = RequestContext(request, params)
return render_to_response('editModel.html', context_instance=ctx)
nimiq
  • 181
  • 2
  • 13
  • Again the same mistake. Interestingly, in the html-a is following.
    . Tag between the
    nothing and everything after
    – Krasimir Jan 12 '13 at 17:10
  • I think you are displayin gthe form in the wrong way. Should be something like:
    {% csrf_token %} {{ form.as_p}}
    – nimiq Jan 12 '13 at 17:14
  • Take a look here: https://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs#displaying-a-form-using-a-template – nimiq Jan 12 '13 at 17:17
  • Even if you can not see I just want to send me to a page which I will then – Krasimir Jan 12 '13 at 17:21
  • Ok I see. But why don't you use a regular form in Django style? Is there a reason or just cause you don't know how? If you don't know, you should read it here, it is pretty cool: https://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs#displaying-a-form-using-a-template – nimiq Jan 12 '13 at 17:25
  • Because this class use another form class and did not want to have many fields and I want to do it right. Elsewhere work, but it just does not work and do not know where the problem is. – Krasimir Jan 12 '13 at 17:29
  • And if you still want to use your custom form you have to suppress the csrf check for that view using a decorator. In the view: from django.views.decorators.csrf import srf_exempt Then before the method you call in the action of the form @csrf_exempt See: http://stackoverflow.com/questions/1650941/django-csrf-framework-cannot-be-disabled-and-is-breaking-my-site – nimiq Jan 12 '13 at 17:29
  • I do not want to exclude csrf. I do not think the solution is to turn off csrf. Your solution satisfies me because I have other forms that work this way, and why this is broken I do not know. – Krasimir Jan 12 '13 at 18:12