2013-11-15 86 views
0

我想創建一個註冊視圖。在這裏,我的代碼:Django註冊視圖

from django.shortcuts import get_object_or_404, render, redirect 
from django.contrib.auth import authenticate, login as auth_login 
from django.contrib.auth.models import User 

# create a function to resolve email to username 
def get_user(email): 
    try: 
     return User.objects.get(email=email.lower()) 
    except User.DoesNotExist: 
     return None 

def signup(request): 
    if request.method == "GET": 
     return render(request, 'accounts/signup.html') 
    if request.method == "POST": 
     email = request.POST['email'] 
     last_name = request.POST['last_name'] 
     first_name = request.POST['first_name'] 
     password = request.POST['password'] 
     password2 = request.POST['password2'] 
     user = get_user(email) 
     if password == password2: 
      if user is None: 
       user = User.objects.create_user(last_name, email, password) 
       user.first_name = first_name 
       user.save() 
       user = authenticate(username=user, password=password) 
       #login 
       return redirect('/') 
      else: 
       #messages 
       return render(request, 'accounts/signup.html') 
     else: 
      #messages 
      return render(request, 'accounts/signup.html') 

我需要你做得更好,因爲如你所見,他有點混亂。

我不知道是否最好使用像django註冊這樣的插件來完成這個任務?

非常感謝!

+0

它看起來很不錯。您可以使用基於類的視圖:https://docs.djangoproject.com/en/dev/topics/class-based-views/。 –

+0

爲什麼不使用表單?它會讓你的生活變得如此簡單。 Django註冊,IMO可能是一個不錯的選擇,因爲它會減少你必須管理的大量代碼 – karthikr

+0

這可能是有用的:http://justcramer.com/2008/08/23/logging-in-with -email-地址合的django / –

回答

3

首先你在你的應用程序的forms.py中做一個表單類。在那裏你定義你的領域,如'電子郵件','first_name',...你在表單類中覆蓋clean方法,然後在視圖中使用它。

class RegistrationForm(forms.Form): 
    username = forms.EmailField(max_length=30, widget=forms.TextInput(attrs=attrs_dict)) 
    password1 = forms.PasswordField() 
    password2 = forms.PasswordField() 
    first_name = forms.CharField(max_length=100) 
    # rest of the fields 

    def clean(self): 
     cleaned_data = super(RegistrationForm, self).clean() 
     username = cleaned_data.get("username") 
     password1 = cleaned_data.get("password1") 
     password2 = cleaned_data.get("password2") 

     # you can validate those here 

    class Meta: 
     model = User 

然後在你看來,你

from forms import RegistrationForm 

def signup(request): 
    if request.method == "GET": 
     return render(request, 'accounts/signup.html') 
    if request.method == "POST": 
     form = RegistrationForm(data = request.POST): 
     if form.is_valid(): 
      user = form.save(False) 
      user.set_password(user.password) 
      user.save() 
      user = authenticate(username=user.username, password=request.POST['password1']) 
      login(request, user) 

      return redirect('/') 

它使大量使用的是什麼Django的給你免費。