name' category_id'没有定义

时间:2017-09-12 12:26:30

标签: django django-models

我正在尝试获取该类别的ID,但此错误不断弹出。 这是我的 models.py

class Category(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='category_created')
    name = models.CharField(max_length=500, db_index=True)
    slug = models.CharField(max_length=500, blank=True)
    images = models.ImageField(upload_to='users/%Y/%m/%d', blank=True)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
            super(Category, self).save(*args, **kwargs)

class Product(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='product')
    category = models.ForeignKey(Category, related_name='products')
    name = models.CharField(max_length=500, db_index=True)
    slug = models.CharField(max_length=500, blank=True)
    images = models.ImageField(upload_to='users/%Y/%m/%d', blank=True)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    stock = models.PositiveIntegerField(blank=True)
    available = models.CharField(max_length=25)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('name',)
    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
            super(Product, self).save(*args, **kwargs)

这是我的观点,其中发生错误并且不知道如何修复视图,我确信问题来自我的 views.py

@login_required
def product(request):
    if request.method == 'POST':
        category = Category.objects.get(pk = category_id)
        product_form = ProductForm(data=request.POST, files=request.FILES)
        if product_form.is_valid():
            new_item = product_form.save(commit=False)
            new_item.category = category
            new_item.save()
            messages.success(request, 'Product created')
        else:
            messages.error(request, 'Product Failed to be created')
    else:
        product_form = ProductForm()
    return render(request, 'shop/product/product_create.html', {'product_form':product_form})

3 个答案:

答案 0 :(得分:0)

嗨Ekhorutomwen Harsley,

如果您尝试创建新对象,则不需要此ID,因为Django会自动添加它。

你只需要用类似的东西创建一个新的Category对象

    @login_required
def product(request):
    if request.method == 'POST':
        category = Category()
        product_form = ProductForm(data=request.POST, files=request.FILES)
        if product_form.is_valid():
            new_item = product_form.save(commit=False)
            new_item.category = category
            new_item.save()
            messages.success(request, 'Product created')
        else:
            messages.error(request, 'Product Failed to be created')
    else:
        product_form = ProductForm()
    return render(request, 'shop/product/product_create.html', {'product_form':product_form})

如果要访问数据库中已存在的类别。您可以通过以下方式访问它:

category_id = 3 // the id you want to access
category = Category.objects.get(id=category_id)

我希望它能帮到你

答案 1 :(得分:0)

你应该使用静态ID或 你应该使用post方法的id

 @login_required
def product(request):
    if request.method == 'POST':
        #category_id = 1
        #you should have to use a static id
        #category_id = request.POST['category_id']
        #you should have to use a id from post method 
        category = Category.objects.get(pk = category_id)
        product_form = ProductForm(data=request.POST, files=request.FILES)
        if product_form.is_valid():
            new_item = product_form.save(commit=False)
            new_item.category = category
            new_item.save()
            messages.success(request, 'Product created')
        else:
            messages.error(request, 'Product Failed to be created')
    else:
        product_form = ProductForm()
    return render(request, 'shop/product/product_create.html', {'product_form':product_form})

答案 2 :(得分:0)

category = Category.objects.get(pk = category_id)

为了能够获得Category标识的category_id对象,必须定义category_id。您的视图函数(product())未定义此变量。

我了解到您正在尝试使用表单数据创建Product。如果表单包含ProductCategory之间关系的字段,则无需手动设置product.category

如果ProductForm没有关系的归档,那么您必须从category_id对象的表单中获取request(假设您在HTML中有该字段)形式)像:

category_id = request.POST.get('category_id')

或将类别ID作为网址参数(doc

传递