【问题标题】:AttributeError: module Django.contrib.auth.views has no attributeAttributeError:模块 Django.contrib.auth.views 没有属性
【发布时间】:2018-04-14 09:29:02
【问题描述】:

在我的 Django 应用用户帐户中,我为我的注册创建了一个注册表单和一个模型。但是,当我运行 python manage.py makemigrations 时,遇到错误:AttributeError: module Django.contrib.auth.views has no attribute 'registration'。其次,我在 forms.py 中正确编码 SignUpForm 吗?我不想在模型中使用 User 模型,因为它会请求用户名,我不希望我的网站要求用户名。

这是我的代码:

models.py

from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User

class UserProfile(models.Model):
    first_name = models.CharField(max_length=150)
    last_name =  models.CharField(max_length=150)
    email = models.EmailField(max_length=150)
    birth_date = models.DateField()
    password = models.CharField(max_length=150)

@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)
    instance.profile.save()

forms.py

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

class SignUpForm(UserCreationForm):

    class Meta:
        model = User

        fields = ('first_name',
                  'last_name',
                  'email',
                  'password1',
                  'password2', )

views.py

from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from useraccounts.forms import SignUpForm

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

def login(request):
    return render(request, 'useraccounts/login.html')

def registration(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()
            user.profile.birth_date = form.cleaned_data.get('birth_date')
            user.save()
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(password=raw_password)
            login(request, user)
            return redirect('home')
        else:
            form = SignUpForm()
        return render(request, 'registration.html', {'form': form})

urls.py

from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views

urlpatterns = [

    url(r'^$', views.home),
    url(r'^login/$', auth_views.login, {'template_name': 'useraccounts/login.html'}, name='login'),
    url(r'^logout/$', auth_views.logout, {'template_name': 'useraccounts/logout.html'}, name='logout'),
    url(r'^registration/$', auth_views.registration, {'template_name': 'useraccounts/registration.html'}, name='registration'),

]

【问题讨论】:

  • 请发布您的完整错误回溯
  • 原来我弄乱了 url.py 部分进行注册。感谢您的回答!
  • 始终编写 Django 版本,因为版本中正在进行大量开发。

标签: python django django-models django-forms attributeerror


【解决方案1】:

应该是:

url(r'^registration/$', views.registration, {'template_name': 'useraccounts/registration.html'}, name='registration'),

auth_views 没有注册,你的意见有

【讨论】:

  • 谢谢。但是现在当我打开 useraccounts/registration.html 时,我收到错误:“视图 useraccounts.views.registration 没有返回 HttpResponse 对象。它返回了 None。”另外,我的表单和视图是否正确?
【解决方案2】:

我不能离开 cmets 所以我决定留下一个答案。 你在 else 块附近有额外的缩进。您的注册函数应如下所示:

def registration(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()
            user.profile.birth_date = form.cleaned_data.get('birth_date')
            user.save()
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(password=raw_password)
            login(request, user)
            return redirect('home')
    else:
        form = SignUpForm()
    return render(request, 'registration.html', {'form': form})

这就是您收到此错误的原因

视图 useraccounts.views.registration 未返回 HttpResponse 对象。它返回 None 。

【讨论】:

    【解决方案3】:

    您的 urlpatterns 应该是:

    from django.contrib.auth import views as auth_views
    
    urlpatterns = [
       url( r'^login/$',auth_views.LoginView.as_view(template_name="useraccounts/login.html"), name="login"),
    ]
    

    【讨论】:

      【解决方案4】:

      打开urls.py 并替换:

      django.contrib.auth.views.logindjango.contrib.auth.views.LoginView

      django.contrib.auth.views.logoutdjango.contrib.auth.views.LogoutView

      【讨论】:

        【解决方案5】:

        在 django 2.1 版中,我使用来自身份验证应用程序的自定义 urls 模式

        from django.urls import path, re_path
        from django.contrib.auth import views as auth_views
        from django.conf import settings
        from .views import register_view, activate
        
        
        urlpatterns = [
            # url(r'^$', HomeView.as_view(), name='home'),
            re_path(r'^register/$', register_view, name='signup'),
            re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
                    activate, name='users_activate'),
            re_path('login/', auth_views.LoginView, {
                'template_name': "users/registration/login.html"},
                name='login'),
            re_path('logout/', auth_views.LogoutView,
                {'next_page': settings.LOGIN_REDIRECT_URL}, name='logout'),
        
            re_path(r'^password_reset/$', auth_views.PasswordResetView,
                {'template_name': "users/registration/password_reset_form.html"},
                name='password_reset'),
            re_path(r'^password_reset/done/$', auth_views.PasswordResetDoneView,
                {'template_name': "users/registration/password_reset_done.html"},
                name='password_reset_done'),
            re_path(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
                auth_views.PasswordResetConfirmView,
                {'template_name': "users/registration/password_reset_confirm.html"},
                name='password_reset_confirm'),
            re_path(r'^reset/done/$', auth_views.PasswordResetCompleteView,
                {'template_name': "users/registration/password_reset_complete.html"},
                name='password_reset_complete'),
        ]
        

        【讨论】:

          【解决方案6】:

          打开 urls.py 并替换:

          更改views.login => views.LoginView.as_view()

          【讨论】:

            【解决方案7】:

            您需要 LoginView 等作为一个类,而不是像 here 所见的函数(Django 1.11 中的新功能为 Should 和 2.1 版起必须)

            【讨论】:

              【解决方案8】:

              Django 2.1 contrib 视图从函数视图更改为类视图,名称也会更改,因此在忘记过程中您需要提供其他视图名称

              urls.py

              ​​>
              from django.contrib.auth import views as auth_views
              
              path('password_reset/', auth_views.PasswordResetView.as_view(), {'template_name':'registration/Reset_email.html'}, name='password_reset'),
                  path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), {'template_name':'registration/Reset_Email_Sent.html'}, name='password_reset_done'),
                  re_path('reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/', auth_views.PasswordResetConfirmView.as_view(), {'template_name' : 'registration/Forgot_password.html'}, name='password_reset_confirm'),
                  path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), {'template_name' : 'registration/Signin.html'}, name='password_reset_complete'),
              

              Django 你可以自定义用户模型,你可以删除用户名和使用电子邮件地址

              models.py

              ​​>

              用户模型,您可以编写自定义列,您可以添加和删除

              用户管理你也可以像超级用户一样自定义commond,如果你 您需要提供任何默认值

              from django.contrib.auth.models import User
              from django.contrib.auth.models import AbstractUser,BaseUserManager
              from django.utils.translation import ugettext_lazy as _
              
              class UserManager(BaseUserManager):
                  """Define a model manager for User model with no username field."""
              
                  use_in_migrations = True
              
                  def _create_user(self, email, password, **extra_fields):
                      """Create and save a User with the given email and password."""
                      if not email:
                          raise ValueError('The given email must be set')
                      email = self.normalize_email(email)
                      user = self.model(email=email, **extra_fields)
                      user.set_password(password)
                      user.save(using=self._db)
                      return user
              
                  def create_user(self, email, password=None, **extra_fields):
                      """Create and save a regular User with the given email and password."""
                      extra_fields.setdefault('is_staff', False)
                      extra_fields.setdefault('is_superuser', False)
                      return self._create_user(email, password, **extra_fields)
              
                  def create_superuser(self, email, password, **extra_fields):
                      """Create and save a SuperUser with the given email and password."""
                      extra_fields.setdefault('is_staff', True)
                      extra_fields.setdefault('is_superuser', True)
              
                      if extra_fields.get('is_staff') is not True:
                          raise ValueError('Superuser must have is_staff=True.')
                      if extra_fields.get('is_superuser') is not True:
                          raise ValueError('Superuser must have is_superuser=True.')
              
                      return self._create_user(email, password, **extra_fields)
              
              
              class User(AbstractUser):
              
                  username = None
                  email = models.EmailField(_('email'), unique=True)
                  first_name = models.CharField( _('first name'), max_length=250)
                  last_name = models.CharField(_('last name'), max_length=250)
                  email_confirmed = models.BooleanField(default=False)
              
                  USERNAME_FIELD = 'email'
                  REQUIRED_FIELDS = ['first_name', 'last_name',]
              
                  objects = UserManager()
              
                  def __str__(self):
                      return "%s" %(self.email)
              

              settings.py

              ​​>

              您需要为自定义用户模型设置的设置

              # AUTH USER MODEL
              AUTH_USER_MODEL = "Accounts.User" 
              
              LOGIN_URL = '/login/'
              #LOGIN_REDIRECT_URL  = 'login_success'
              
              LOGOUT_REDIRECT_URL = '/login/'
              

              admin.py

              ​​>

              admin 你需要注册用户模型

              ## user model view
              from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
              from django.utils.translation import ugettext_lazy as _
              
              @admin.register(User)
              class UserAdmin(DjangoUserAdmin):
                  """Define admin model for custom User model with no email field."""
              
                  fieldsets = (
                      (None, {'fields': ('email', 'password')}),
                      (_('Personal info'), {'fields': ('first_name', 'last_name', 'email_confirmed')}),
                      (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                                     'groups', 'user_permissions')}),
                      (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
                  )
              
                  add_fieldsets = (
                      (None, {
                          'classes': ('wide',),
                          'fields': ('email', 'password1', 'password2', 'first_name', 'last_name'),
                      }),
                  )
                  list_display = ('email', 'first_name', 'last_name',)
                  search_fields = ('email', 'first_name', 'last_name')
                  ordering = ('-id',)
              

              【讨论】:

                【解决方案9】:

                非常简单的步骤:

                转到项目urls.pyviews.login 更改为views.LoginView.as_view()

                如果你正在使用 Logout 属性,那么对它做同样的事情

                【讨论】:

                  【解决方案10】:

                  打开url.py文件并替换

                  views.loginviews.LoginView

                  【讨论】:

                  • 您能否添加更多上下文以使您的答案更合适?例如代码是什么?您正在用类替换函数,因此语法可能不一样。您可能还想提一下,这仅适用于 Django>=1.11
                  • 从 2 升级到 2.2.3 时,我在 django 2 中遇到此错误。我修复了我的网址,例如... url(r'^accounts/login/$', django.contrib.auth.views.LoginView,name="login"), url(r'^accounts/logout/$', django .contrib.auth.views.LogoutView,{'next_page': '/'},name="logout"),
                  【解决方案11】:

                  你必须在你的 urls.py 中导入 LoginView:

                  from django.contrib.auth.views import LoginView
                  

                  改变

                  auth_view.login
                  

                  LoginView.as_view()
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 2020-08-19
                    • 1970-01-01
                    • 2019-02-18
                    • 1970-01-01
                    • 2020-01-01
                    • 2019-07-20
                    • 2021-11-05
                    相关资源
                    最近更新 更多