如何将选择类别从模板链接到Django模型对象?

时间:2018-10-07 08:59:24

标签: python django

我在我的产品模型(类别字段)中有很多关系。我可以在一个选择框中显示类别数据,该选择框为多项选择。我要做的是让用户从模板中选择一个或多个类别,然后将数据保存在我的产品模型中。这是我的代码:

      if request.method =='POST':
            print ('entered')
            name = request.POST['name']
            brand = request.POST['brand']
            sku = request.POST['sku']
            price = request.POST['price']
            quantity = request.POST['quantity']
            description = request.POST['description']
            imageurls = request.POST['urls']

            print('imageurls',imageurls)

            categorylist = request.POST['categories']
            print('categorylist',categorylist)
            categories =  re.findall(r"[\w']+", categorylist)
            print categories

            imageurls = imageurls.split('~')
            print('iageurls',imageurls)

            for x in categories:
                categoryobj = Category.objects.filter(name=x).values()
                _id = categoryobj.id
                print('_id',_id)
                print ('categoryobj',categoryobj)
               # Product.objects.create(name=name,sku=sku,brand=brand,price=price,quantity=quantity,description=description,imageurls=imageurls,categories=categoryobj)



            return HttpResponse('success')

models.py

class Category(models.Model):
    name = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50, unique=True,
                            help_text='Unique value for product page URL, created from name.')
    description = models.TextField()
    is_active = models.BooleanField(default=True)
    meta_keywords = models.CharField("Meta Keywords", max_length=255,
                                     help_text='Comma-delimited set of SEO keywords for meta tag')
    meta_description = models.CharField("Meta Description", max_length=255,
                                        help_text='Content for description meta tag')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('catalog:categories', kwargs={'category_slug': self.slug})

    class Meta:
        ordering = ['-created_at']
        verbose_name_plural = 'Categories'


class Product(models.Model):
    name = models.CharField(max_length=255, unique=True)
    slug = models.SlugField(max_length=255, unique=True,
                            help_text='Unique value for product page URL, created from name.')
    brand = models.CharField(max_length=50)
    sku = models.CharField(max_length=50)
    price = models.DecimalField(max_digits=9, decimal_places=2)
    old_price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, default=0.00)
    thumbnail = models.FileField(upload_to='static/images/products/thumbnails')
    imageurls = models.CharField(max_length=1000)
    is_active = models.BooleanField(default=True)
    is_bestseller = models.BooleanField(default=False)
    is_featured = models.BooleanField(default=False)
    quantity = models.IntegerField()
    description = models.TextField()
    meta_keywords = models.CharField(max_length=255, help_text='Comma-delimited set of SEO keywords for meta tag')
    meta_description = models.CharField(max_length=255, help_text='Content for description meta tag')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    categories = models.ManyToManyField(Category)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('catalog:products', kwargs={'product_slug': self.slug})

    def sale_price(self):
        if self.old_price > self.price:
            return self.price
        else:
            return None

    class Meta:
        ordering = ['-created_at']

1 个答案:

答案 0 :(得分:0)

您应该使用Django ModelForms。因此,您只需要检查form.is_valid(),然后执行form.save()。 Save方法会自动为您创建一个新对象。

让我知道这是否有效!