如何请求对象并将其发布到外键字段

发布于 2025-01-11 05:40:36 字数 1577 浏览 0 评论 0原文

当我完全按照下面提供的方式执行此操作时,会创建一个送货地址对象,而无需在送货地址外键字段中分配客户,我可以从管理面板手动添加它,但我无法通过代码使其工作,我不知道什么我做错了,请帮忙!

**models.py**

class Customer(models.Model):
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, blank=True, null=True)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField(max_length=150)

class ShippingAddress(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
    address_one = models.CharField(max_length=200)
    address_two = models.CharField(max_length=200)
    ...

**views.py**
    
def checkout(request):

    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
        items = order.orderitem_set.all()
    else:
        items = []
        order = {'get_cart_total': 0, 'get_cart_items': 0}


    if request.method == 'POST':
        form = ShippingForm(request.POST)

        if form.is_valid():

            #how do I get the customer to get added in the foreignkey field for the shipping address model

            form.save()
            return redirect('store:checkout_shipping')
        else:
            form = ShippingForm()

    else:
        form = ShippingForm()

    context = {"items": items, "order": order, "form": form}
    return render(request, 'store/checkout.html', context)

When I do this exactly as provided below, a shipping address object is created without the customer assigned in the shipping address foreignkey field, I can add it from the admin panel manually but I'm not able to make it work through code, idk what I'm doing wrong, please help!

**models.py**

class Customer(models.Model):
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, blank=True, null=True)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField(max_length=150)

class ShippingAddress(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
    address_one = models.CharField(max_length=200)
    address_two = models.CharField(max_length=200)
    ...

**views.py**
    
def checkout(request):

    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
        items = order.orderitem_set.all()
    else:
        items = []
        order = {'get_cart_total': 0, 'get_cart_items': 0}


    if request.method == 'POST':
        form = ShippingForm(request.POST)

        if form.is_valid():

            #how do I get the customer to get added in the foreignkey field for the shipping address model

            form.save()
            return redirect('store:checkout_shipping')
        else:
            form = ShippingForm()

    else:
        form = ShippingForm()

    context = {"items": items, "order": order, "form": form}
    return render(request, 'store/checkout.html', context)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

り繁华旳梦境 2025-01-18 05:40:36

响应您的评论#how do I get the customer to get add...等,如果您的ShippingForm()指向您的ShippingAddress< /code> 模型,或者至少具有 customer 外键字段的内容,您可能需要执行以下操作:

def checkout(request):

    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
        items = order.orderitem_set.all()
    else:
        items = []
        order = {'get_cart_total': 0, 'get_cart_items': 0}


    if request.method == 'POST':
        form = ShippingForm(request.POST)

        if form.is_valid():
            new_shipment = form.save(commit=False)
            new_shipment.customer = customer
            new_shipment.save()
            return redirect('store:checkout_shipping')
        else:
            form = ShippingForm()

    else:
        form = ShippingForm()

    context = {"items": items, "order": order, "form": form}
    return render(request, 'store/checkout.html', context)   

在 form.save() 上使用 commit=False将允许您随后修改其他字段,在本例中,通过添加客户关系,然后保存。 Django 文档中的更多信息 。重要引述:

此 save() 方法接受可选的 commit 关键字参数,该参数
接受 True 或 False。如果您使用 commit=False 调用 save(),
然后它会返回一个尚未保存到的对象
数据库。在这种情况下,您可以对结果调用 save()
模型实例。如果您想进行自定义处理,这很有用
保存对象之前,或者如果您想使用其中之一
专门的模型保存选项。 commit 默认为 True。

本例中的“自定义处理”是创建与模型实例(客户)的外键关系。

In response to your comment #how do I get the customer to get added... etc, in the case that your ShippingForm() points to your ShippingAddress model, or at least something with a customer foreign key field, you may need to do something like this:

def checkout(request):

    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
        items = order.orderitem_set.all()
    else:
        items = []
        order = {'get_cart_total': 0, 'get_cart_items': 0}


    if request.method == 'POST':
        form = ShippingForm(request.POST)

        if form.is_valid():
            new_shipment = form.save(commit=False)
            new_shipment.customer = customer
            new_shipment.save()
            return redirect('store:checkout_shipping')
        else:
            form = ShippingForm()

    else:
        form = ShippingForm()

    context = {"items": items, "order": order, "form": form}
    return render(request, 'store/checkout.html', context)   

Using commit=False on the form.save() will allow you to subsequently modify other fields, in this case, by adding the customer relation, then saving it. More information here in the Django documentation. Salient quote:

This save() method accepts an optional commit keyword argument, which
accepts either True or False. If you call save() with commit=False,
then it will return an object that hasn’t yet been saved to the
database. In this case, it’s up to you to call save() on the resulting
model instance. This is useful if you want to do custom processing on
the object before saving it, or if you want to use one of the
specialized model saving options. commit is True by default.

"Custom processing" in this case is the creation of the foreign key relationship to the model instance (customer).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文