Django 3“用户”对象没有属性“管理员”

Posted

技术标签:

【中文标题】Django 3“用户”对象没有属性“管理员”【英文标题】:Django 3 'User' object has no attribute 'admin' 【发布时间】:2020-10-08 19:05:03 【问题描述】:

情况

我正在从这个YouTube Series 修改这个GitHub 项目,这是demo 原始应用程序的运行方式。 我的目标是为市场中的商家(在代码 Admin 或 AdminUser 中)帐户添加设置选项,因为在原始项目中,只有买家可以选择添加图片及其联系方式。

代码

模型.py

#database table create
class Customer(models.Model):
    #empty fields accept - null=True
    user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=200, null=True)
    email = models.CharField(max_length=200, null=True)
    profile_pic = models.ImageField(default="profile1.png", null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)

    #show customer name in admin panel
    def __str__(self):
        return self.name


class Adminuser(models.Model):
    #empty fields accept - null=True
    user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=200, null=True)
    email = models.CharField(max_length=200, null=True)
    profile_pic = models.ImageField(default="profile1.png", null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)

    #show customer name in admin panel
    def __str__(self):
        return self.name

url.py

from django.urls import path
from django.contrib.auth import views as auth_views
from . import views

urlpatterns = [
    ...
    path('customer/<str:pk_test>/', views.customer, name="customer"),
    path('adminuser/<str:pk_test>/', views.adminuser, name="adminuser"),
    ...
]

views.py

#CUSTOMER_ONLY PROFILE SETTINGS
@login_required(login_url='login')
@allowed_users(allowed_roles=['customer'])
def accountSettings(request):
    customer = request.user.customer
    form = CustomerForm(instance=customer)
    if request.method == 'POST':
        form = CustomerForm(request.POST, request.FILES,instance=customer)
        if form.is_valid():
            form.save()
    context = 'form':form
    return render(request, 'accounts/account_settings.html', context)



#ADMIN_ONLY PROFILE SETTINGS
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def adminSettings(request):
    admin = request.user.admin
    form = AdminForm(instance=admin)
    if request.method == 'POST':
        form = AdminForm(request.POST, request.FILES,instance=admin)
        if form.is_valid():
            form.save()
    context = 'form':form
    return render(request, 'accounts/account_admin_settings.html', context)

forms.py

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

from .models import *

class CustomerForm(ModelForm):
    class Meta:
        model = Customer
        fields = '__all__'
        exclude = ['user']

class AdminForm(ModelForm):
    class Meta:
        model = Adminuser
        fields = '__all__'
        exclude = ['user']

navbar.html

...
<li class="nav-item">
  <a class="nav-link" href="% url 'adminsettings' %">SettingsAdmin</a>
</li>
...

account_admin_settings.html

%  extends 'accounts/main.html' %
% load static %
% block content %

<style>
    .profile-pic
        max-width: 200px;
        max-height:200px;
        margin: 0 auto;
        border-radius: 50%;
    
</style>
<!-- -->
<br>
<div class="row">
    <div class="col-md-3">
        <div class="card card-body">
            <a class="btn btn-warning" href="% url 'dashboard' %"> &#8592; Back to Profile</a>
            <hr>
            <h3 style="text-align: center">Account Settings</h3>
            <hr>
            <img class="profile-pic" src="request.user.customer.profile_pic.url" >

        </div>
    </div>
    <div class="col-md-9">
        <div class="card card-body">

            <form method="POST" action="" enctype="multipart/form-data">
                % csrf_token %
                form.as_p

            <input class="btn btn-primary" type="submit" name="Update Information">
            </form>
        </div>
    </div>
</div>

错误

AttributeError at /accounts/adminsettings/
'User' object has no attribute 'admin'
Request Method: GET
Request URL:    http://127.0.0.1:8000/accounts/adminsettings/
Django Version: 3.0
Exception Type: AttributeError
Exception Value:    
'User' object has no attribute 'admin'
Exception Location: /Users/computer/ven/lib/python3.7/site-packages/django/utils/functional.py in inner, line 225
Python Executable:  /Users/computer/ven/bin/python3
Python Version: 3.7.3
Python Path:    
['/Users/computer/project',
 '/Users/computer/anaconda3/lib/python37.zip',
 '/Users/computer/anaconda3/lib/python3.7',
 '/Users/computer/anaconda3/lib/python3.7/lib-dynload',
 '/Users/computer/ven/lib/python3.7/site-packages']
Server time:    Wed, 17 Jun 2020 22:17:12 +0000

尝试过的解决方案

我的错误不在登录时,我不确定它在哪里 - Attribute error: 'User' object has no attribute 'is_admin' 我之前做过迁移和迁移 - Django - No such table: main.auth_user__old 买家可以使用他们自己的模型访问设置,所以这个自己。不能解决我的情况django 'User' object has no attribute 'user' 我不会重写 .save 方法 - 'NoneType' object has no attribute 'user' Django 它应该有相同的实例等级,就像在客户模型中它只是一个不同的用户优先等级等级组 - Django 'User' object has no attribute 'Goals' 这是 python 2.7 和 Django 1.5 过时的问题和答案以 - Django Admin Issue - 'NoneType' object has no attribute 'user' 开头 这与我的情况无关 - Django Admin Action: 'QuerySet' object has no attribute 'user' 我所有的中间穿着都很好 - Django admin error 'WSGIRequest' object has no attribute 'user 过时的问答和我的中间穿作品 - 'WSGIRequest' object has no attribute 'user' Django admin @allowed_users(allowed_roles=['customer']) 更改为 @allowed_users(allowed_roles=['customer','admin']) 以将所有内容都放入 def accountSettings(request): 中的 1 个函数中会出错 已添加user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE, related_name='admin') 错误:RelatedObjectDoesNotExist at /accounts/adminsettings/ User has no admin. 在我将request.user.adminuser 添加到视图函数之后 错误AttributeError at /accounts/adminsettings/ 'User' object has no attribute 'adminuser' 我需要在视图或模型的什么地方使用这个How do you catch this exception??如何? :
MY FUNCTION ANME  
    try:
        # MY ORIGINAL CODE
    except ObjectDoesNotExist:
        # and what goes here?????
@xyres 更新了 view.py def adminSettings(request):
#ADMIN_ONLY PROFILE SETTINGS ''' '''
@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def adminSettings(request):
    try:
        admin = requset.user.admin
        form = AdminForm(instance=admin)
        if request.method == 'POST':
            form = AdminForm(request.POST, request.FILES,instance=admin)
            if form.is_valid():
                form.save()
        context = 'form':form
        return render(request, 'accounts/account_admin_settings.html', context)
    except ObjectDoesNotExist:
        print("Either the entry or blog doesn't exist.")
        return render(request, 'accounts/account_admin_settings.html', context)
错误:File "/Users/computer/project/accounts/views.py", line 106 form = AdminForm(instance=admin) ^ 将views.py 和models.py 挂回原来的状态,现在我收到一个新错误(在makemigration migrate 更改之后)
NameError at /accounts/adminsettings/
name 'requset' is not defined

【问题讨论】:

【参考方案1】:

来自OneToOneField's documentation:

如果您没有为OneToOneField 指定related_name 参数,Django 将使用当前模型的小写名称作为默认值。

因此,您必须以以下方式访问相关的 Adminuser 实例:

request.user.adminuser

如果您只想使用 admin 访问它,如文档中所述,则必须使用 related_name 参数:

class Adminuser(models.Model):
    user = models.OneToOneField(User, related_name='admin' ...)
    ...

# request.user.admin will work now

更新

RelatedObjectDoesNotExist 异常在数据库中不存在相关对象时引发(当相关字段可以是null 时经常出现这种情况)。由于这次没有AttributeError,这意味着Django 确实 识别了admin 属性;所以,这个问题是固定的。

您必须在访问相关属性的任何地方处理 RelatedObjectDoesNotExist 异常。

from django.core.exceptions import ObjectDoesNotExist

try:
    admin = requset.user.admin
except ObjectDoesNotExist:
    admin = # set some other value ...

【讨论】:

我已完成更正并将您的代码部分添加到模型函数中,但我仍然收到错误,请参阅“TRIED SOLUTIONS”。 我在我的代码库中添加了request.user.adminuseruser = models.OneToOneField(User, related_name='admin' ...),并在两步之后应用了 migrarionas。 @sogu 所以AttributeError 已经解决了。 RelatedObjectDoesNotExist 相关对象不存在时引发异常。在这种情况下,数据库中没有相关的 admin 实例。使用ObjectDoesNotExist 处理此异常,如下所示:docs.djangoproject.com/en/3.0/ref/models/querysets/… @sogu 或者这里有一个更好的例子来处理这个异常:***.com/a/42821464/1925257 将 ***.com/a/42821464/1925257 后使用问题添加到“已尝试的解决方案”中

以上是关于Django 3“用户”对象没有属性“管理员”的主要内容,如果未能解决你的问题,请参考以下文章

组对象没有属性 user_set

Django 条件管理员 list_editable

在 Django 管理员中,有没有办法显示模型的一对多对象的实际链接列表?

Django之outh模块

WIN10管理员权限怎么改不了

如何只允许管理员(或某些用户)在 Django 中编辑页面?