/ polls / register /中的ModuleNotFoundError

时间:2018-01-29 08:26:34

标签: python django django-models django-forms

我正在django中创建一个注册表单。我的项目名称是FirstProj,包含包含民意调查的mysite和mysite。 我的forms.py就是这个

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

class RegistrationForm(UserCreationForm):
    email= forms.EmailField(required = True)

    class Meta:
        model = User
        fields = {
            'username',
            'first_name',
            'last_name',
            'email',
            'password1',
            'password2'
        }

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

        if commit:
            user.save()

        return user

我的views.py就是这个

from mysite.polls.forms import RegistrationForm
from django.shortcuts import render,redirect

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/polls')
    else:
        form = RegistrationForm()

    args = {'form': form}
    return render(request, 'polls/reg_form.html', args)

但是我的cleaning_data()无法读取,而且我得到以下错误。

No module named 'mysite.polls'

This is my folder tree

Here's my error

我在mysite中的urls.py是

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^polls/', include('polls.urls', namespace= "polls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

并且,我的民意调查中的urls.py是

from django.conf.urls import url
from .import views
from django.conf.urls import url
from django.contrib.auth.views import login,logout

urlpatterns= [
    url(r'^$',views.index, name= "index"),
    #127.0.0.1/polls
    url(r'^(?P<question_id>[0-9]+)/$', views.detail, name= "detail"),
    #127.0.0.1/polls/1
    url(r'^(?P<question_id>[0-9]+)/results$', views.results, name="results"),
    # 127.0.0.1/polls/1/results
    url(r'^(?P<question_id>[0-9]+)/vote$', views.vote, name="vote"),
    # 127.0.0.1/polls/1/vote
    url(r'^login/$', login, {'template_name': 'polls/login.html'}),
    url(r'^logout/$', logout, {'template_name': 'polls/logout.html'}),
    url(r'^register/$', views.register, name= 'register'),
]

1 个答案:

答案 0 :(得分:3)

您可以尝试将此from mysite.polls.forms import RegistrationForm更改为此from polls.forms import RegistrationForm

问题是polls不是项目mysite的模块,所以通过输入mysite.polls django会尝试搜索项目下的内容并且找不到任何内容(模块是polls.formspolls.models之类的内容formsmodels是应用polls的模块。