当我想将外键与User对象关联时,我无法检索相应的数据



型号.py

class Order(models.Model):
PAYMENT_OPTIONS = (
('VISA','VISA'),
('Master','Master'),
('Octopus','Octopus'),
('Cash','Cash'),
)
STATUS = (
('Pending','Pending'),
('Delivered','Delivered'),
)
user = models.ForeignKey(User,models.CASCADE,null=True,blank=True)
customer = models.CharField(max_length=200,null=True,blank=True)
card_id = models.IntegerField(null=True,blank=True)
mobile = models.IntegerField(null=True,blank=True)
email = models.CharField(max_length=200,null=True,blank=True)

total_price = models.DecimalField(decimal_places=2,max_digits=7)
payment_method = models.CharField(max_length=50,choices=PAYMENT_OPTIONS,null=True,blank=True)
status = models.CharField(max_length=50,choices=STATUS,default='Pending')
date = models.DateTimeField(auto_now_add=True)
address = models.CharField(max_length=350,null=True,blank=True)
def __str__(self):
return str(self.customer)+''s Order'

视图.py

def order_summary(request,order_id,user_id):
user = User.objects.get(id=user_id)
customer_order = Order.objects.get(id=order_id,user=user)
food_order = OrderDetail.objects.filter(order=customer_order)
context = {
'customer_order':customer_order,
'food_order':food_order}
return render(request,'menu/order_summary.html',context)

urls.py

path('order_summary/<int:order_id>/<int:user_id>/',views.order_summary,name='order_summary'),

navbar.html

<li><a class="dropdown-item" href="{% url 'order_summary' [order_id]%}我的訂單</a></li>

错误:

Reverse for 'order_summary' with arguments '('', 1)' not found. 1 pattern(s) tried: ['order_summary/(?P<order_id>[0-9]+)/(?P<user_id>[0-9]+)/$']

对于上面的代码,我可能想要一个超链接,它可以访问order_summary方法并过滤正确的User对象。然而,如果我试图放置与用户的订单和user.id相对应的相应参数,即使我已经在urls.py中包含了url,我也会收到错误消息。如果我想引用HTML导航栏中的参数,有人能找出问题吗?

您应该在urls.py文件中添加一个user_id参数,这样您就可以传递当前登录的用户(或您想要的任何其他用户id(。

所以,你的观点是这样的:

def order_summary(request,order_id, user_id):
user = User.objects.get(id=user_id)
customer_order = Order.objects.get(id=order_id, user=user)
food_order = OrderDetail.objects.filter(order=customer_order)
context = {
'customer_order':customer_order,
'food_order':food_order}
return render(request,'menu/order_summary.html',context)

然后在你的模板中,你可以简单地输入用户id。

<li><a class="dropdown-item" href="{% url 'order_summary' [order_id] [user_id] %}我的訂單</a></li>

我认为你可以通过反向关系直接得到这个,你可以试试这个,

request.user.order_set.all((

这将获取当前用户的订单数据。

相关内容

  • 没有找到相关文章