2017-05-13 73 views
0

當我嘗試註冊,我得到一個錯誤:Django的csrf_token失蹤錯誤

Forbidden (403) CSRF verification failed. Request aborted.

我的代碼:

@csrf_protect 
def register(request): 
    if request.method == 'POST': 
     form = RegistrationForm(request.POST, request.FILES) 
     if form.is_valid(): 
      first_name = form.cleaned_data.get("firstname") 
      last_name = form.cleaned_data.get("lastname") 
      username = form.cleaned_data.get("username") 
      password = form.cleaned_data.get("password") 
      user = User.objects.create_user(username=username,password=password) 
      user.first_name = first_name 
      user.last_name = last_name 
      user.set_password(password) 
      user.is_active = True 
      user.save() 
      return HttpResponseRedirect('/home/') 
    else: 
     form = RegistrationForm() 
    return render_to_response('registration/registerHome.html',dict(form=form, 
     context_instance=RequestContext(request))) 

我form.py

class RegistrationForm(forms.Form): 
    """ 
    A registration form to create normal user. 
    """ 
    firstname = forms.RegexField(regex=r'^\[a-zA-Z]+$', 
     widget=forms.TextInput(attrs={ 'required':True, 
      'max_length':30, 
      'autocomplete':'off', 
      'class':'form-control input-sm', 
      'placeholder':'First Name' }), 
     error_messages={ 'invalid': _("Only alphabets are allowed.") } 
     ) 
    lastname = forms.RegexField(regex=r'^\[a-zA-Z]+$', 
     widget=forms.TextInput(attrs={ 'required':True, 
      'max_length':30, 
      'autocomplete':'off', 
      'class':'form-control input-sm', 
      'placeholder':'Last Name' }), 
     error_messages={ 'invalid': _("Only alphabets are allowed.") } 
     ) 
    username = forms.RegexField(regex=r'^\w+$', 
     widget=forms.TextInput(attrs={'required':True, 
      'max_length':30, 
      'autocomplete':'off', 
      'class':'form-control input-sm', 
      'placeholder':'username'}), 
     error_messages={ 'invalid': _("Only [a-z A-Z 0-9 _] are allowed.") } 
     ) 
    password = forms.CharField(widget=forms.PasswordInput(attrs={ 
      'required':True, 
      'max_length':30, 
      'autocomplete':'off', 
      'class':'form-control input-sm', 
      'placeholder':'password', 
      'render_value':False }) 
      ) 

    def clean_username(self): 
     try: 
      user = User.objects.get(username__iexact=self.cleaned_data['username']) 
     except User.DoesNotExist: 
      return self.cleaned_data['username'] 
     raise forms.ValidationError(_("Username already exists.")) 

    class Meta: 
     model = User 

我template.html

<form action="." method="post" role="form" id="register-form"> 
          {% csrf_token %} 
          {{ form.as_p }} 
          <input type="submit" value="submit" /> 
         </form> 

有人請幫助我,爲什麼我得到一個錯誤。我試圖解決這個問題1周,但仍然出現錯誤。請幫幫我。

+0

你確定CsrfViewMiddleware在你的設置文件中添加? – dentemm

+0

是的。 'django.middleware.csrf.CsrfViewMiddleware',在setting.py – ecoder

回答

1

您應該使用render並添加else

然後做像

def register(request): 
    if request.method == 'POST': 
     form = RegistrationForm(request.POST, request.FILES) 
     if form.is_valid(): 
      first_name = form.cleaned_data.get("firstname") 
      last_name = form.cleaned_data.get("lastname") 
      username = form.cleaned_data.get("username") 
      password = form.cleaned_data.get("password") 
      user = User.objects.create_user(username=username,password=password) 
      user.first_name = first_name 
      user.last_name = last_name 
      user.set_password(password) 
      user.is_active = True 
      user.save() 
      return HttpResponseRedirect('/home/') 
     else: 
      return render(request, 'registration/registerHome.html',dict(form=form))) 
    else: 
     form = RegistrationForm() 
    return render(request, 'registration/registerHome.html',dict(form=form))) 
+0

我試過了。但是現在form.is_valid()不起作用。我的意思是, form = RegistrationForm(request.POST) if form.is_valid():不正確。 – ecoder

+0

不工作意味着什麼?任何錯誤或者如果它返回False,嘗試在其他條件下打印'form.errors'。 – itzMEonTV

+0

靜態錯誤:RegistrationFrom沒有屬性錯誤。 我的意思是,from.error有錯誤。 – ecoder

0

嘗試類似這樣的事情。我記得前一段時間我有同樣的問題,並宣佈c字典,並將其傳遞給render_to_response解決了我的問題。

@csrf_protect 
def register(request): 
    if request.method == 'POST': 
     # do your post stuff here 
     pass 
    else: 
     c = {} 
     c['form'] = RegistrationForm() 
     c['context_instance'] = RequestContext(request) 
     return render_to_response('registration/registerHome.html',c) 
+0

獲取相同的錯誤。 – ecoder

0

使用https://docs.djangoproject.com/en/1.11/topics/http/shortcuts/#render

from django.shortcuts import render 
@csrf_protect 
def register(request): 
    if request.method == 'POST': 
     form = RegistrationForm(request.POST, request.FILES) 
     if form.is_valid(): 
      first_name = form.cleaned_data.get("firstname") 
      last_name = form.cleaned_data.get("lastname") 
      username = form.cleaned_data.get("username") 
      password = form.cleaned_data.get("password") 
      user = User.objects.create_user(username=username,password=password) 
      user.first_name = first_name 
      user.last_name = last_name 
      user.set_password(password) 
      user.is_active = True 
      user.save() 
      return HttpResponseRedirect('/home/') 
    else: 
     form = RegistrationForm() 
    return render(request, 'registration/registerHome.html',dict(form=form))) 
+0

錯誤消失,但未註冊用戶。 – ecoder

+0

可能是表單中的錯誤,而且它在模板中不顯示。嘗試在else塊之後打印錯誤,即'print form.errors' – psorab

+0

是的。現在它正在工作。謝謝:) – ecoder

0

你並不需要,只要使用@csrf_protect裝飾作爲CSRF中間件是中間件added.The給你所有的觀點毛毯保護嘗試 - 加裝飾是多餘的。 Django文檔建議在裝飾器上使用中間件,因爲它提供了更好的保護。

刪除裝飾器後嘗試。

+0

我嘗試過,但沒有任何改進。 – ecoder