2014-03-18 57 views
6

我正在嘗試爲我的網站啓動註冊過程。我正在使用Python 3.3.5和Django 1.6。沒有名爲'forms'的模塊Django

我收到一條錯誤消息,內容爲No module named 'forms'。我對Python/Django相當陌生。

這裏是我的文件:

Views.py:

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


def register_user(request): 
    if request.method == 'POST': 
     form = MyRegistrationForm(request.POST) 
     if form.is_valid(): 
      form.save() 
      return HttpResponseRedirect('/accounts/register_success') 

    else: 
     form = MyRegistrationForm() 
    args = {} 
    args.update(csrf(request)) 

    args['form'] = form 

    return render_to_response('register1.html', args) 



def register_success(request): 
    return render_to_response('register_success.html') 

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) 

    class Meta: 
     model = User 
     fields = ('username', 'email', 'password1', 'password2') 

    def save(self, commit=True): 
     user = super(MyRegistrationForm, self).save(commit=False) 
     user.email = self.cleaned_data['email'] 
     # user.set_password(self.cleaned_data['password1']) 

     if commit: 
      user.save() 

     return user 

的forms.py位於同一文件夾中views.py。我嘗試從django.forms導入MyRegistrationForm但出現錯誤cannot import name MyRegistrationForm

+0

該文件夾是否包含__ init __.py文件? –

回答

8

如果您沒有更改默認位置views.py,那麼它可能位於您的應用程序文件夾中。嘗試類似from myapp.forms import MyRegistrationForm其中myapp是你的應用程序

+1

這個技巧!非常感謝! – edwards17

+0

Np :)別忘了給我投票 – antimatter

+1

我會當我到15代表:)(新來的) – edwards17

8

的名稱如果那是一個應用模塊,改變你的第六行:

from forms import MyRegistrationForm 

到:

from .forms import MyRegistrationForm 

(只是形式之前加點)

+1

這也適用! – edwards17

+1

這應該是公認的答案。您不想將您的應用程序名稱硬編碼到您的應用程序中。如果你想重命名你的應用程序,並且在任何地方都有你的應用程序名稱,該怎麼辦? – allcaps

+1

我不同意。如果您有多個具有相同表單名稱的應用程序,該怎麼辦? – antimatter

相關問題