Django - 获取相关密钥并插入数据库

Django - Get Related Key and Insert into Database

好的,所以我想做的是允许用户将 "product" 添加到他们的商店,但不必选择要添加的商店,因为每个用户将只有一个商店。

我得到: “/shop/product/add/ 处的完整性错误 NOT NULL 约束失败:shop_product.business_id"

这是局部变量中显示的内容: Local Vars

局部变量:

Variable    Value
__class__   <class 'shop.views.ProductCreate'>
form    <AddProductForm bound=True, valid=True, fields=(product_name;product_desc;product_image)>
s    <Shop: 4>
self     <shop.views.ProductCreate object at 0x048B0370>
user     10

现在我认为问题可能出在 "s" 变量上,因为代码实际上得到了正确的商店..但它也增加了那个奇怪的“

我现在的代码。

models.py

 # Shop Model. A Shop Object will be created when the user registers
class Shop(models.Model):
    name = models.CharField(max_length=150)
    owner = models.OneToOneField(User, related_name="owner")
    shop_logo = models.FileField()

    def __str__(self):
        return str(self.name) + ": " + str(self.owner)

    def create_shop(sender, **kwargs):
        user = kwargs["instance"]
        if kwargs["created"]:
            up = Shop(owner=user)
            up.save()
    post_save.connect(create_shop, sender=User)

    def shoplogo_or_default(self, default_path='/static/images/dft/no-img.png'):
        if self.shop_logo:
            return self.shop_logo
        return default_path


    # The class that will link a product to the shop
class Product(models.Model):
            product_name = models.CharField(max_length=250)
            # connect the product to the shop
            business = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name="products")
            product_desc = models.TextField()
            product_image = models.FileField()

            def __str__(self):
                return self.product_name

views.py

class ProductCreate(CreateView):
    model = Product
    form_class = AddProductForm
    template_name = 'shop/add-product.html'

        def form_valid(self, form):
        form.save(commit=False)
        # get current logged in user
        user = self.request.user.id
        # match the current logged in user to an owner in the Shop model
        s = Shop.objects.get(owner=user)
        #  get the id of that owner's shop identification number
        form.business = str(s.id)
        form.save()
        # This method is called when valid form data has been POSTed.
        # It should return an HttpResponse.
        return super(ProductCreate, self).form_valid(form)

以上理论上应该获取当前登录的用户,将该用户作为所有者与商店模型中的商店匹配,然后获取该商店 ID。

forms.py

class AddProductForm(forms.ModelForm):
class Meta:
    model = Product
    fields = ['product_name', 'product_desc', 'product_image']
    exclude = ['business']

我是 Django 的新手和一名学生,所以如果您看到任何奇怪的地方,我想道歉。

谢谢:)

您很接近,但不要尝试将商店价值编辑到表格中。相反,从保存表单中捕获内存中的 Product 实例并分配其 business 属性:

def form_valid(self, form):
    new_product = form.save(commit=False)
    # get current logged in user
    user = self.request.user.id
    # match the current logged in user to an owner in the Shop model
    s = Shop.objects.get(owner=user)
    # assign the shop instance to the product
    new_product.business = s
    # record the product to the database
    new_product.save()
    # This method is called when valid form data has been POSTed.
    # It should return an HttpResponse.
    return super(ProductCreate, self).form_valid(form)