2014-03-18 58 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

相关问题