ImportError:没有名为' models'

时间:2017-09-27 12:13:10

标签: python django django-forms

以下代码给出了此错误

  

ImportError:没有名为' models'

的模块

我不知道为什么。我想在django中自定义我自己的注册表单。

错误符合:

from models import CustomUser in forms.py 

forms.py:

from django.contrib.auth.forms import UserCreationForm, UserChangeForm

from models import CustomUser

class CustomUserCreationForm(UserCreationForm):

def __init__(self, *args, **kargs):
    super(CustomUserCreationForm, self).__init__( *args, **kargs)
    del self.fields['username']

class Meta:
    model = CustomUser
    fields = ["email",]

class CustomUserChangeForm(UserChangeForm):

def __init__(self, *args, **kargs):
    super(CustomUserChangeForm, self).__init__(*args, **kargs)
    del self.fields['username']

 class Meta:
    model = CustomUser

register.html:

{% extends "account/base.html" %}
{% load crispy_forms_tags %}
 {% load i18n %}

{% block head_title %}{% trans "Signup" %}{% endblock %}

{% block content %}
<div class= 'col-md-4 col-md-offset-4'>
<h1>{% trans "Register" %}</h1>

<p>{% blocktrans %}Already have an account? Then please <a href="{{   login_url }}">sign in</a>.{% endblocktrans %}</p>

<form acction="account/register/" method="post">
 {% csrf_token %}
 {{ form|crispy }}


 <input type="submit" value="Register" />
 <button type="submit" class= 'btn btn-default'>{% trans "Sign Up" %} &raquo;</button>
</form>
 </div>
{% endblock %}

views.py:

from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect 
from custom_user.forms import CustomUserCreationForm

#Create your views here
def home(request):
    return render(request, "home.html")

def login(request):
    c = {}
    c.update(csrf(request))
    return render(request, "login.html", c)

def auth_view(request):
    username = request.POST.get['username', '']
    password = request.POST.get['password', '']
    user = auth.authenticate(username=username, password=password)

    if user is not None:
        auth.login(request, user)
        return HTTpResponseRedirect('account/login')
    else:
        return HTTpResponseRedirect('account/login')


def logout(request):
    auth.logout(request)
    return render(request, 'logout.html')

1 个答案:

答案 0 :(得分:9)

你需要添加点

from .models import CustomUser
#   ^^^

o使用app_name的最佳方式

from custom_user.models import CustomUser

并且对于第二个错误,您可以简单地将空排除添加到Meta:

class CustomUserChangeForm(UserChangeForm):

def __init__(self, *args, **kargs):
    super(CustomUserChangeForm, self).__init__(*args, **kargs)
    del self.fields['username']

 class Meta:
    model = CustomUser
    exclude = () # THIS ROW