没有名为“forms”的Djang模块

2024-05-17 04:34:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试启动我的网站的注册过程。我使用的是Python3.3.5和Django1.6。

我收到一个说No module named 'forms'的错误。我对Python/Django还比较陌生。

这是我的文件:

视图.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')

表单.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


Tags: djangofrompyimportformauthregisterreturn
2条回答

如果是应用程序模块,请更改第6行:

from forms import MyRegistrationForm

致:

from .forms import MyRegistrationForm

(只需在表单前添加一个点)

如果没有更改views.py的默认位置,则很可能在应用程序文件夹中。尝试类似于from myapp.forms import MyRegistrationForm的方法,其中myapp是应用程序的名称

相关问题 更多 >