hello i am user python and Django.
i will follow this question(Can I have a Django form without Model) but for my task i need images. i will try to run my code and i have this error Forbidden (403) : any idea how to fix that ?
Forbidden (403)
CSRF verification failed. Request aborted.
You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.
If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests.
views.py
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template import RequestContext
from blog.forms import MyForm
# Create your views here.
def form_handle(request):
form = MyForm()
if request.method=='POST':
form = MyForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
#now in the object cd, you have the form as a dictionary.
a = cd.get('a')
return render_to_response('blog/calc.html', {'form': form}, RequestContext(request))
urls.py
from django.conf.urls import url
from . import views
forms.py
from django import forms
class MyForm(forms.Form): #Note that it is not inheriting from forms.ModelForm
a = forms.ImageField()
#All my attributes here
urls.py
urlpatterns = [
url(r'^$',views.form_handle, name='form_handle'),
]
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="POST">{% csrf_token %}
{{form.as_p}}
<button type="submit">Submit</button>
</form>
</body>
</html>
You are adding a csrf token to the form, but not providing it in the view function. Try this:
from django.views.decorators.csrf import csrf_protect
# Create your views here.
@csrf_protect
def form_handle(request):
form = MyForm()
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.