如何在Django视图中渲染对象? [英] How To Render An Object In Django Views?
问题描述
我有一个接受URL的表格。然后使用BS4解析此URL,并使用以下类创建产品:
I have a form that accepts URLs. This URL is then being parsed with BS4 and product created with the following class:
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检查产品:
I want to save only unique products to the database. Therefore I added the following code into the add function in the views.py file to check the product by its 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))
当前,用户收到产品已存在错误消息。但是我实际上想渲染已经存在的产品。这是详细产品的功能:
Currently, user receives the 'Product already exists' error message. But I want to actually render the already existing product instead. Here is the function for detailed product:
def detail(request, product_id):
product = get_object_or_404(Product, pk=product_id)
return render(request, 'product/detail.html', {'product': product})
详细产品的URL如下所示: http://example.com/product / 22
可能有一种更好的方法来检索,比较然后呈现对象。请告诉我。
The URL to detailed product looks like this: http://example.com/product/22 There is probably a better way to retrieve, compare and then render an object. Please let me know. Thanks in advance!
推荐答案
您可以直接重定向到产品的已定义get_absolute_url属性吗?
Can you just redirect to the Product's defined get_absolute_url property?
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())
这篇关于如何在Django视图中渲染对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!