情况
密码
model.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' %}"> ← 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
尝试过的解决方案
AttributeError at/accounts/adminsettings/'User'对象没有属性'adminuser'
MY FUNCTION ANME
try:
# MY ORIGINAL CODE
except ObjectDoesNotExist:
# and what goes here?????
#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)
文件/用户/计算机/项目/帐户/views.py,第106行form=AdminForm(实例=admin)^
NameError at /accounts/adminsettings/
name 'requset' is not defined
从OneToOneField
的文档中:
如果您没有为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
时,通常会出现这种情况)。由于这次没有AtiniteError
,这意味着Django确实识别了admin
属性;因此,该问题已修复。
您必须在访问相关属性的任何地方处理RelatedObjectDoesNotExist
异常。
from django.core.exceptions import ObjectDoesNotExist
try:
admin = requset.user.admin
except ObjectDoesNotExist:
admin = # set some other value ...
这是我得到的错误,我无法得到管理员登录屏幕。 属性错误在 /admin/ 'WSGIRequest' 对象没有属性 'user' 请求方法: GET 请求 URL: http://127.0.0.1:8000/admin/ Django 版本: 2.1.2 异常类型: 属性错误异常值: 'WSGIRequest' 对象没有属性 “用户” 异常位置: C:\用户\海王星\AppData\本地\程序\
更新的文件: 回溯:`文件“c:\python27\lib\site-packages\django-1.9-py2.7.eg\django\core\handlers\base.py”在get_response 149中。响应=self.process_exception_by_middleware(e,request) get_response 147中的文件“C:\python27\lib\
问题内容: 但是,这给了我一个AttributeError,我将在下面粘贴StackTrace。这完全是我从示例来源中粘贴的错误。我确实使用PeeWee代替了SQLAlchemy,但是由于这段代码对数据库没有任何作用,但是我不知道为什么会这样。 有人知道我在这里做错什么吗? 问题答案: g.user全局 如果你要注意的话,你会记得在登录视图功能中我们检查以确定用户是否已经登录。要实现此目的,我们将
这是我的密码: 这条线给了我错误 "属性错误:'浮点'对象没有属性'exp'"。X,t是Numpy ndarray。
问题内容: 如果用户未登录,我想设置一个cookie。 My中间件: 最后添加到中。 问题: 错误:“ WSGIRequest”对象没有属性“ user” 为什么,当我已经激活身份验证和会话中间件时? 另外,有些页面在出现此错误的地方工作流畅。 我究竟做错了什么 ? 问题答案: 根据FineManual: 因此,我想你最好在auth和会话中间件之前添加你的中间件(假设它仅处理响应)。 话虽这么说,
问题内容: 我正在开发Django应用程序,并且出现以下错误 我的模型是这样构造的 我应该做什么? 问题答案: 首先,您必须非常小心地重写以具有非可选参数。记住,每次从一个查询集中获取一个对象时,它将被调用! 这是您想要的正确代码: 如果您只使用该对象的子类,我强烈建议在Animal上设置abstract选项。这样可以确保不为动物创建表,而仅为绵羊(等)创建表。如果未设置abstract,则将创建