外键自动填表

问题描述 投票:0回答:1

我有四个模型的商店,客户,产品,订单,我显示的模型的关系。

铺子

    user = models.OneToOneField(User, null=True, related_name='shop', blank=True, on_delete=models.CASCADE)

顾客

user = models.OneToOneField(User, null=True, on_delete=models.CASCADE

产品

    shop = models.ForeignKey(Shop, models.CASCADE, null=True, blank=True)

秩序

shop = models.ForeignKey(Shop, models.CASCADE, null=True)
customer = models.ForeignKey(Customer, models.CASCADE, null=True)
product = models.ForeignKey(Product, models.CASCADE, null=True)

当顾客登录后,店铺会在屏幕上打印出一个按钮,并在店铺上显示出该店铺的产品的表单卡

我如何创建一个订单表格,使客户在订单中是实例,而商店在订单中是选择显示产品的商店,产品的每张卡都有一个字段来填写剩余的细节和提交。

django django-forms django-views django-haystack
1个回答
1
投票

如果我是你,我会把它添加到表单中,用以下两个选项之一选择1。

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    # Get the shop_id from the URL
    shop = get_object_or_404(Shop, pk=shop_id)
    # Create a form and add it the context
    form = OrderForm(
        # This is where the magic happens
        initial={"shop": shop], "customer": self.request.user})
    # Use this if you want to hide it as well
    form.fields['item'].widget = forms.HiddenInput()

备选方案2

# If the form is already created you can use this pattern
context['form'].fields['shop'].initial = shop
context['form'].fields['customer'].initial = self.request.user
© www.soinside.com 2019 - 2024. All rights reserved.