2017-10-13 100 views
0

新用戶註冊無法完成。 我views.py新用戶註冊無法完成

def regist(request): 
    regist_form = RegisterForm(request.POST or None) 
    context = { 
     'regist_form': regist_form, 
    } 
    return render(request, 'registration/regist.html', context) 

@require_POST 
def regist_save(request): 
    regist_form = RegisterForm(request.POST) 
    if regist_form.is_valid(): 
     user = form.save() 
     login(request, user) 
     context = { 
      'user': request.user, 
     } 
     return redirect('detail') 

    context = { 
     'regist_form': regist_form, 
    } 
    return render(request, 'registration/regist.html', context) 

在regist.html中寫道forms.py

class RegisterForm(UserCreationForm): 
    class Meta: 
     model = User 
     fields = ('username', 'email','password1','password1',) 
    def __init__(self, *args, **kwargs): 
     super(RegisterForm, self).__init__(*args, **kwargs) 
     self.fields['username'].widget.attrs['class'] = 'form-control' 
     self.fields['email'].widget.attrs['class'] = 'form-control' 
     self.fields['password1'].widget.attrs['class'] = 'form-control' 
     self.fields['password2'].widget.attrs['class'] = 'form-control' 

<div class="heading col-lg-6 col-md-12">
   
 
     <h2>New account registration</h2> 
 
    
 
     <form class="form-horizontal" action="regist_save/" method="POST">
   
 
      <div class="form-group-lg">
   
 
      <label for="id_username">username</label> 
 
      
  {{ regist_form.username }}
   
 
      </div>
  
   
 
      <div class="form-group-lg">
   
 
      <label for="id_email">email</label> 
 
      
   {{ regist_form.email }} 
 
      </div> 
 
      <div class="form-group-lg">
   
 
      <label for="id_password">password</label>
   
 
      {{ regist_form.password1 }}
   
 
      </div>
  
   
 
      <div class="form-group-lg"> 
 
      <label for="id_password">password(conformation)</label>
   
 
      {{ regist_form.password2 }} 
 
      <p class="help-block">{{ regist_form.password2.help_text }}</p>
   
 
      </div>
  
   
 
      <div class="form-group-lg"> 
 
      <div class="col-xs-offset-2"> 
 
      <button type="submit" class="btn btn-primary btn-lg">SUBMIT</button>
   
 
      <input name="next" type="hidden"/>
   
 
      </div> 
 
      </div> 
 
      {% csrf_token %}
   
 
     </form>
   
 
</div>

沒有錯誤發生,當我把提交按鈕,它發送detail.html,所以它沒問題。但是當我看到adm在現場,沒有用戶註冊。 我真的不明白爲什麼會發生這種情況。我不明白什麼是錯的。我讀Django教程,所以我認爲這種編寫代碼的方式是可以的。我該如何解決這個問題?我應該怎麼寫?

回答

0

您的表單變量是regist_form,但您正試圖保存form嘗試將user = form.save()更改爲user = regist_form.save()

你也需要爲新的用戶密碼,你可以用commit=False此:

user = regist_form.save(commit=False) 
password = regist_form.cleaned_data.get('password') 
user.set_password(password) 
user.save() 
login(request, user)