2013-11-25 51 views
0

我很好奇,看看model = User行在我的forms.py中做了什麼,所以我決定評論它。其結果是這樣的錯誤:ModelForm沒有指定模型類Django

ModelForm has no model class specified. 

,它是強調了對views.py

args['form'] = MyRegistrationForm() 

45線我還是不太清楚model = User如何發揮在我的自定義用戶註冊成卷。 (我一直在關注教程)。我想知道如果有人能簡單地向我解釋這整個過程,爲什麼model = User需要

我的猜測是,該模型現在是一個User對象。另外args['form'] = MyRegistrationForm()需要是模型對象,否則代碼將崩潰。這就像我的假設一樣。

我views.py:

from django.shortcuts import render 
from django.http import HttpResponseRedirect  
from django.contrib import auth     
from django.core.context_processors import csrf 
from forms import MyRegistrationForm 

def register_user(request): 
    if request.method == 'POST': 
     form = MyRegistrationForm(request.POST)  # create form object 
     if form.is_valid(): 
      form.save() 
      return HttpResponseRedirect('/accounts/register_success') 
    args = {} 
    args.update(csrf(request)) 
    args['form'] = MyRegistrationForm() 
    print args 
    return render(request, 'register.html', args) 

我forms.py

from django import forms    
from django.contrib.auth.models import User 
from django.contrib.auth.forms import UserCreationForm 



class MyRegistrationForm(UserCreationForm): 
    email = forms.EmailField(required = True) 
    first_name = forms.CharField(required = False) 
    last_name = forms.CharField(required = False) 
    birthday = forms.DateField(required = False) 



    class Meta: 
     #model = User 
     fields = ('email', 'username', 'password1', 'password2', 'last_name', 'first_name', 'birthday')  # set up ordering 

    def save(self,commit = True): 
     user = super(MyRegistrationForm, self).save(commit = False) 
     user.email = self.cleaned_data['email'] 
     user.first_name = self.cleaned_data['first_name'] 
     user.last_name = self.cleaned_data['last_name'] 
     user.birthday = self.cleaned_data['birthday'] 


     if commit: 
      user.save() 

     return user 

回答

1

I'm still not quite sure how the model = User plays a roll in my custom user registration form.

您的形式繼承django.contrib.auth.forms.UserCreationForm這是一個ModelForm

I was wondering if someone could briefly explain to me this whole process and why model = User is needed

ModelForms這裏記載:https://docs.djangoproject.com/en/1.5/topics/forms/modelforms/

作爲一個側面說明,如果你繼承了你的窗體的MetaUserCreationForm.Meta你就不需要再次指定模型。

My guess is that model is now a User object.

User是一類。

Also args['form'] = MyRegistrationForm() needs to be a model object or else the code will crash. This is as far as my assumptions go.

不要假設:閱讀文檔,然後閱讀代碼(請記住,它是開源軟件)。