Python 如何在Django视图中渲染对象?
我有一个接受URL的表单。然后使用BS4解析此URL,并使用以下类创建产品:Python 如何在Django视图中渲染对象?,python,django,postgresql,django-models,beautifulsoup,Python,Django,Postgresql,Django Models,Beautifulsoup,我有一个接受URL的表单。然后使用BS4解析此URL,并使用以下类创建产品: class Product(models.Model): product_id = models.CharField(max_length=50) pub_date = models.DateTimeField(default=datetime.now) title = models.CharField(max_length=255) url = models.TextField()
class Product(models.Model):
product_id = models.CharField(max_length=50)
pub_date = models.DateTimeField(default=datetime.now)
title = models.CharField(max_length=255)
url = models.TextField()
price = models.FloatField()
我只想将唯一的产品保存到数据库中。因此,我在views.py文件中的add函数中添加了以下代码,以通过其ID检查产品:
def add(request):
...
product.product_id = soup.find('h1', class_='product-id').text
if Product.objects.filter(product_id=product.product_id):
return render(request, 'product/add.html', {'error': 'Product already exists'})
else:
product.title = soup.find('h1', class_='product-name').text
...
product.save()
return redirect('/product/' + str(product.id))
当前,用户收到“产品已存在”错误消息。但是我想实际渲染已经存在的产品。以下是详细产品的功能:
def detail(request, product_id):
product = get_object_or_404(Product, pk=product_id)
return render(request, 'product/detail.html', {'product': product})
详细产品的URL如下所示:
可能有更好的方法来检索、比较和渲染对象。请让我知道。提前谢谢 能否重定向到产品定义的get\u absolute\u url属性
def add(request):
...
product.product_id = soup.find('h1', class_='product-id').text
existing_product = Product.objects.filter(product_id=product.product_id)
if existing_product:
return redirect(existing_product.get_absolute_url())
非常感谢。但是,我们似乎必须找到另一种方法来查找现有产品,因为现在我遇到以下错误:“QuerySet”对象没有“get_absolute_url”属性。您需要在模型中定义get_absolute_url: