Django:CSRF验证失败

发布于 2024-12-01 13:28:10 字数 2160 浏览 2 评论 0原文

不知道如何解决这个问题:/。

视图.py:

# coding: utf-8
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views.generic.simple import direct_to_template
from django.core.mail import send_mail
from django.template import Context, loader
from django.conf import settings
from sklep.models import Produkt
from sklep.forms import ZamowienieForm
from django.core.context_processors import csrf

def koszyk(request):
    koszyk = request.session.get('koszyk', [])
    produkty = list(Produkt.objects.filter(pk__in=koszyk))

    if request.method == 'POST':
        formularz = ZamowienieForm(request.POST)

        if formularz.is_valid():
            dane = formularz.cleaned_data
            tresc = loader.get_template('sklep/zamowienie.txt').render(Context({'produkty': produkty, 'dane': dane}))

            send_mail('Potwierdzenie zakupu', tresc, settings.EMAIL_SKLEPU, [dane['email']])
            send_mail(u'Zamówienie', tresc, dane['email'], [settings.EMAIL_SKLEPU])

            del request.session['koszyk']

            return HttpResponseRedirect(reverse('sklep_koszyk'))
    else:
        formularz = ZamowienieForm()

    if koszyk:
        kontekst = {'koszyk': produkty, 'formularz': formularz}
    else:
        kontekst = {'koszyk': []}

    return direct_to_template(request, 'sklep/koszyk.html', extra_context = kontekst)

def koszyk_dodaj(request, id_produktu):
    koszyk = request.session.get('koszyk', [])
    if int(id_produktu) not in koszyk:
        koszyk.append(int(id_produktu))
    request.session['koszyk'] = koszyk
    return HttpResponseRedirect(reverse('sklep_koszyk'))

表单.py

# coding: utf-8
from django import forms
from django.contrib.localflavor.pl.forms import PLPostalCodeField

class ZamowienieForm(forms.Form):
    email = forms.EmailField()
    imie_nazwisko = forms.CharField(label=u'Imię i nazwisko', max_length=60)
    adres = forms.CharField(max_length=100)
    kod_pocztowy = PLPostalCodeField()
    miasto = forms.CharField(max_length=60)
    uwagi = forms.CharField(widget=forms.Textarea, required=False)

Don't know how to resolve this problem :/.

views.py:

# coding: utf-8
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views.generic.simple import direct_to_template
from django.core.mail import send_mail
from django.template import Context, loader
from django.conf import settings
from sklep.models import Produkt
from sklep.forms import ZamowienieForm
from django.core.context_processors import csrf

def koszyk(request):
    koszyk = request.session.get('koszyk', [])
    produkty = list(Produkt.objects.filter(pk__in=koszyk))

    if request.method == 'POST':
        formularz = ZamowienieForm(request.POST)

        if formularz.is_valid():
            dane = formularz.cleaned_data
            tresc = loader.get_template('sklep/zamowienie.txt').render(Context({'produkty': produkty, 'dane': dane}))

            send_mail('Potwierdzenie zakupu', tresc, settings.EMAIL_SKLEPU, [dane['email']])
            send_mail(u'Zamówienie', tresc, dane['email'], [settings.EMAIL_SKLEPU])

            del request.session['koszyk']

            return HttpResponseRedirect(reverse('sklep_koszyk'))
    else:
        formularz = ZamowienieForm()

    if koszyk:
        kontekst = {'koszyk': produkty, 'formularz': formularz}
    else:
        kontekst = {'koszyk': []}

    return direct_to_template(request, 'sklep/koszyk.html', extra_context = kontekst)

def koszyk_dodaj(request, id_produktu):
    koszyk = request.session.get('koszyk', [])
    if int(id_produktu) not in koszyk:
        koszyk.append(int(id_produktu))
    request.session['koszyk'] = koszyk
    return HttpResponseRedirect(reverse('sklep_koszyk'))

forms.py

# coding: utf-8
from django import forms
from django.contrib.localflavor.pl.forms import PLPostalCodeField

class ZamowienieForm(forms.Form):
    email = forms.EmailField()
    imie_nazwisko = forms.CharField(label=u'Imię i nazwisko', max_length=60)
    adres = forms.CharField(max_length=100)
    kod_pocztowy = PLPostalCodeField()
    miasto = forms.CharField(max_length=60)
    uwagi = forms.CharField(widget=forms.Textarea, required=False)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

云淡风轻 2024-12-08 13:28:10

问题可能出在您的模板 sklep/koszyk.html 中。在 html 页面的表单内部,您需要包含 {% csrf_token %}文档提供了有关此功能的更多信息。

The problem is probably in your template sklep/koszyk.html. Inside of the form on the html page you need to include {% csrf_token %}. The documentation has more information about this feature.

遮云壑 2024-12-08 13:28:10

另外,要添加 murgatroid99 所说的内容,您需要在调用该页面时包含 csrf(request)。我通常会执行 locals().update(csrf(request)) 然后使用 locals() 作为全局字典参数调用页面。

Also, to add to what murgatroid99 said, you need to include the csrf(request) when you are calling that page. I usually do a locals().update(csrf(request)) then call the page with locals() as the global dictionary parameter.

比忠 2024-12-08 13:28:10

Django 要求 POST 请求使用 CSRF 令牌,以防止跨站点请求伪造 。您可能必须在表单内的模板中包含 {% csrf_token %} 。如果您知道自己在做什么(例如 api 调用),您还可以使用 @csrf_exempt 装饰器。

有关此问题的更多详细信息,请参阅有关 CSRF 保护的 Django 文档

Django requires for POST request a CSRF token to protect against Cross Site Request Forgeries. You probably have to include {% csrf_token %} in your template inside the form. If you know what you are doing (for example api calls) you can also use the @csrf_exempt decorator.

For more details about the issue have a look at the Django documentation about CSRF Protection

跨年 2024-12-08 13:28:10

假设您的模板已包含 {% csrf_token%},请确保在您的 project/settings.py 文件中添加以下行:

 CSRF_TRUSTED_ORIGINS = [
    'http://localhost:8000',
    'http://*youripaddress*',   
    ]

ALLOWED_HOSTS = [
    'localhost',
    'http://*youripaddress*',
    ]

CORS_ORIGIN_WHITELIST = [
    'http://localhost:8000',
    'http://*youripaddress*',
    ]

默认情况下,Django 在生成项目时包含 ALLOWED_HOST 选项,但是需要手动添加受信任列表和白名单选项。

Assuming your templates contain {% csrf_token%} already, make sure to add these lines in your project/settings.py file:

 CSRF_TRUSTED_ORIGINS = [
    'http://localhost:8000',
    'http://*youripaddress*',   
    ]

ALLOWED_HOSTS = [
    'localhost',
    'http://*youripaddress*',
    ]

CORS_ORIGIN_WHITELIST = [
    'http://localhost:8000',
    'http://*youripaddress*',
    ]

By default Django includes ALLOWED_HOST option when generating a project, however trusted list and whitelist options need to be added manually.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文