我一直在遵循这个教程,我进行得很顺利,但我得到了一个错误。我不知道如何解决。我添加了一对一的客户与用户模型。现在有了这个用户。`models.py
from django.db import models
from django.core.validators import RegexValidator
from django.contrib.auth.models import User
class customer(models.Model):
user=models.OneToOneField(User,null=True,on_delete=models.CASCADE)
name=models.CharField(max_length=200,null=True)
phone_no=models.CharField(max_length=200, validators
[RegexValidator(r'^\d{1,10}$')],null=True)
email=models.EmailField(max_length=200,null=True)
def __str__(self):
return self.name
class tag(models.Model):
name=models.CharField(max_length=200,null=True)
def __str__(self):
return self.name
class products(models.Model):
categories=[
('indoor','indoor'),
('outdoor','outdoor')
]
name=models.CharField(max_length=200,null=True)
price=models.FloatField(null=True)
manufacturedate=models.DateTimeField(auto_now_add=True,null=True)
description:models.TextField(null=True)
categories=models.CharField(max_length=200,null=True,choices=categories)
tag=models.ManyToManyField(tag)
def __str__(self):
return self.name
class order(models.Model):
status=[
('pending','pending'),
('out of stock','out of stock',),
('Delivered',('Delivered'))
]
ordered_date=models.DateTimeField(auto_now_add=True)
status=models.CharField(max_length=200,null=True,choices=status)
customer=models.ForeignKey(customer,null=True,on_delete=models.SET_NULL)
product=models.ForeignKey(products,null=True,on_delete=models.SET_NULL)
def __str__(self):
return self.product.name
我真的很困惑。我被困在这里一段时间。一切都很好,直到我添加了一对一的关系。
views.py
从django的多处理导入上下文输入代码。快捷方式导入渲染,从django重定向。contrib.auth.模型导入组自。模型导入 * 自。表单导入CreateCustomer、CreateOrder、CreateUser。filters import过滤器搜索
from django.contrib.auth import logout,login,authenticate
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .decorators import allowed_users,admin_only
def registeruser(request):
if request.user.is_authenticated:
return redirect('home')
else :
form=CreateUser()
if request.method=='POST':
form=CreateUser(request.POST)
if form.is_valid():
user=form.save()
group=Group.objects.get(name='customer')
user.groups.add(group)
login(request,user)
return redirect('home')
context={'form':form}
return render(request,'accounts/registeruser.html',context)
def loginuser(request):
if request.user.is_authenticated:
return redirect('home')
else :
if request.method=='POST':
username=request.POST.get('username')
password=request.POST.get('password')
user=authenticate(request,username=username,password=password)
if user is not None:
login(request,user)
return redirect('home')
else:
messages.info(request,"Something went wrong!!")
context={}
return render(request,'accounts/login.html',context)
@login_required(login_url='login')
def logoutuser(request):
logout(request)
return redirect('login')
@login_required(login_url='login')
@admin_only
def home(request):
customers=customer.objects.all()
orders=order.objects.all()
total_customers=customers.count()
total_orders=orders.count()
delivered=orders.filter(status='Delivered').count()
pending=orders.filter(status='pending').count()
context= {'customers':customers,'orders':orders,'total_customers':total_customers,
'total_orders':total_orders,'delivered':delivered,
'pending':pending }
return render(request,'accounts/home.html',context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['customer'])
def userprofile(request):
return render(request,'accounts/userprofile.html',context)
@login_required(login_url='login')
def product(request):
return render(request,'accounts/products.html')
@login_required(login_url='login')
@allowed_users(allowed_roles=['customer'])
def Customer(request,pk):
Customer=customer.objects.get(id=pk)
orders=Customer.order_set.all()
if request.method=='GET':
filterset=FilterSearch(request.GET,queryset=orders)
orders=filterset.qs
order_count=orders.count()
context={'Customer':Customer,'orders':orders,'order_count':order_count
,'filterset':filterset}
return render(request,'accounts/customers.html',context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['customer'])
def createcustomer(request):
form=CreateCustomer()
if request.method=='POST':
form=CreateCustomer(request.POST)
if form.is_valid():
form.save()
return redirect('home')
context={'form':form}
return render(request,'accounts/customerform.html',context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['customer'])
def createorder(request):
form=CreateOrder()
if request.method=='POST':
form=CreateOrder(request.POST)
if form.is_valid():
form.save()
return redirect('home')
context={'form':form}
return render(request,'accounts/orderform.html',context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['customer'])
def updateOrder(request,pk):
orders=order.objects.get(id=pk)
form=CreateOrder(instance=orders)
if request.method=='POST':
form=CreateOrder(request.POST,instance=orders)
if form.is_valid():
form.save()
return redirect('home')
context={'form':form}
return render(request,'accounts/orderform.html',context)
@login_required(login_url='login')
@allowed_users(allowed_roles=['customer'])
def deleteOrder(request,pk):
orders=order.objects.get(id=pk)
if request.method=='POST':
orders.delete()
return redirect('home')
context={'order':orders}
return render(request,'accounts/deleteorder.html',context)
我会非常感激你的帮助
url.py
enter code here
from django.urls import path
from . import views
urlpatterns=[
path('registeruser/',views.registeruser,name="registeruser"),
path('login/',views.loginuser,name="login"),
path('user/',views.userprofile,name='userprofile'),
path('logout/',views.logoutuser,name="logout"),
path('',views.home,name="home"),
path('products/',views.product,name='product'),
path('customers/<str:pk>/',views.Customer,name='customer'),
path('Createcustomers/',views.createcustomer,name='createcustomer'),
path('Createorder/',views.createorder,name='createorder'),
path('updateorder/<str:pk>/',views.updateOrder,name='updateorder'),
path('deleteorder/<str:pk>/',views.deleteOrder,name='deleteorder'),
]
4条答案
按热度按时间im9ewurl1#
只需删除所有迁移文件夹并通过运行以下命令手动迁移:
尝试上面的命令,看看这是否解决了你的错误
9fkzdhlc2#
我知道什么是错误。你检查id使用
Customer=customer.objects.get(id=pk)
在客户功能在视图中.py。但是你写
path('customers/<str:pk>/',views.Customer,name='customer')
在urls.py中。
这意味着你在customer函数中检查“Id(integer value)”,但你传递pk,但作为一个字符串值。因此Python将其视为字符串值而不是整数值。
因此,您应该在www. example中更改“customers/int:pk/” www.example.com 文件。
然后运行服务器并运行它。
jvlzgdj93#
不是每个客户都有数据库中的用户。因为你是后来加上去的。转到管理面板。并从数据库手动添加一对一字段用户。那应该能用另一种方法是你必须处理异常,如果有空或id的关系。
jvlzgdj94#
db.sqlite3
文件或正在使用的数据库db.sqlite3
:重新创建数据库python manage.py makemigrations
+python manage.py migrate
调试步骤是尝试#3,如果不起作用,请执行步骤1-3*
记住:Dev dbs很容易被丢弃。
***注意:**在具有生产版本的旧项目中,跳过#2