programing tip

Django CSRF 쿠키가 설정되지 않음

itbloger 2020. 11. 13. 07:52
반응형

Django CSRF 쿠키가 설정되지 않음


잠시 동안 문제가 발생했습니다. CSRF 쿠키가 설정되지 않았습니다. 아래 코드를보세요

파이썬

def deposit(request,account_num):
if request.method == 'POST':
    account = get_object_or_404(account_info,acct_number=account_num)
    form_=AccountForm(request.POST or None, instance=account)
    form = BalanceForm(request.POST)
    info = str(account_info.objects.filter(acct_number=account_num))
    inf=info.split()
    if form.is_valid():
    #cd=form.cleaned_data
        now = datetime.datetime.now()
        cmodel = form.save()
        cmodel.acct_number=account_num
        #RepresentsInt(cmodel.acct_number)
        cmodel.bal_change="%0.2f" % float(cmodel.bal_change)
        cmodel.total_balance="%0.2f" %(float(inf[1]) + float(cmodel.bal_change))
        account.balance="%0.2f" % float(cmodel.total_balance)
        cmodel.total_balance="%0.2f" % float(cmodel.total_balance)
        #cmodel.bal_change=cmodel.bal_change
        cmodel.issued=now.strftime("%m/%d/%y %I:%M:%S %p")
        account.recent_change=cmodel.issued
        cmodel.save()
        account.save()
        return HttpResponseRedirect("/history/" + account_num + "/")
    else:
        return render_to_response('history.html',
                          {'account_form': form},
                          context_instance=RequestContext(request))

여기 HTML에 코드가 있습니다.

HTML

<form action="/deposit/{{ account_num }}/" method="post">

<table>
<tr>
{{ account_form.bal_change }}
&nbsp;
<input type="submit" value="Deposit" />
</tr>
{% csrf_token %}
</table>
</form>

Im 붙어서 이미 쿠키를 지우고 다른 브라우저를 사용했지만 여전히 csrf 쿠키가 설정되지 않았습니다.


CSRF_COOKIE_SECURE = True설정되어 있고 사이트에 안전하지 않게 액세스하는 경우에도 발생할 수 있습니다 .


from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt 
def your_view(request):
    if request.method == "POST":
        # do something
return HttpResponse("Your response")

당신이 사용하는 경우 HTML5를 API를 가져 오기 A가 사용자와 점점 기록으로 POST 요청을하기 위해 Forbidden (CSRF cookie not set.)기본적으로 있기 때문에 수, fetch페이지를로드가 아닌 다른 사용자 인 생각 장고의 결과로, 세션 쿠키를 포함하지 않는다 .

credentials: 'include'가져 오기 옵션 전달하여 세션 토큰을 포함 할 수 있습니다 .

var csrftoken = getCookie('csrftoken');
var headers = new Headers();
headers.append('X-CSRFToken', csrftoken);
fetch('/api/upload', {
    method: 'POST',
    body: payload,
    headers: headers,
    credentials: 'include'
})

From This You can solve it by adding the ensure_csrf_cookie decorator to your view

from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def yourView(request):
 #...

if this method doesn't work. you will try to comment csrf in middleware. and test again.


I came across a similar situation while working with DRF, the solution was appending .as_view() method to the View in urls.py


This problem arose again recently due to a bug in Python itself.

http://bugs.python.org/issue22931

https://code.djangoproject.com/ticket/24280

Among the versions affected were 2.7.8 and 2.7.9. The cookie was not read correctly if one of the values contained a [ character.

Updating Python (2.7.10) fixes the problem.


I was using Django 1.10 before.So I was facing this problem. Now I downgraded it to Django 1.9 and it is working fine.


This also occurs when you don't set the form action.
For me, it was showing this error when the code was:

<form class="navbar-form form-inline my-2 my-lg-0" role="search" method="post">

When I corrected my code into this:

<form class="navbar-form form-inline my-2 my-lg-0" action="{% url 'someurl' %}" role="search" method="post">

my error disappeared.


try to check if your have installed in the settings.py

 MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',)

In the template the data are formatted with the csrf_token:

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

Problem seems that you are not handling GET requests appropriately or directly posting the data without first getting the form.

When you first access the page, client will send GET request, in that case you should send html with appropriate form.

Later, user fills up the form and sends POST request with form data.

Your view should be:

def deposit(request,account_num):
   if request.method == 'POST':
      form_=AccountForm(request.POST or None, instance=account)
      if form.is_valid(): 
          #handle form data
          return HttpResponseRedirect("/history/" + account_num + "/")
      else:
         #handle when form not valid
    else:
       #handle when request is GET (or not POST)
       form_=AccountForm(instance=account)

    return render_to_response('history.html',
                          {'account_form': form},
                          context_instance=RequestContext(request))

Check that chrome's cookies are set with default option for websites. Allow local data to be set (recommended).


Method 1:

from django.shortcuts import render_to_response
return render_to_response(
    'history.html',
    RequestContext(request, {
        'account_form': form,
    })

Method 2 :

from django.shortcuts import render
return render(request, 'history.html', {
    'account_form': form,
})

Because render_to_response method may case some problem of response cookies.


I had the same error, in my case adding method_decorator helps:

from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator

method_decorator(csrf_protect)
def post(self, request):
    ...

Make sure your django session backend is configured properly in settings.py. Then try this,

class CustomMiddleware(object):
  def process_request(self,request:HttpRequest):
      get_token(request)

Add this middleware in settings.py under MIDDLEWARE_CLASSES or MIDDLEWARE depending on the django version

get_token - Returns the CSRF token required for a POST form. The token is an alphanumeric value. A new token is created if one is not already set.


I have just met once, the solution is to empty the cookies. And may be changed while debugging SECRET_KEY related.


Clearing my browser's cache fixed this issue for me. I had been switching between local development environments to do the django-blog-zinnia tutorial after working on another project when it happened. At first, I thought changing the order of INSTALLED_APPS to match the tutorial had caused it, but I set these back and was unable to correct it until clearing the cache.


In your view are you using the csrf decorator??

from django.views.decorators.csrf import csrf_protect

@csrf_protect def view(request, params): ....

참고URL : https://stackoverflow.com/questions/17716624/django-csrf-cookie-not-set

반응형