【问题标题】:How to get the current object / product from the class based detail view in django?如何从 django 中基于类的详细视图中获取当前对象/产品?
【发布时间】:2020-09-04 01:34:12
【问题描述】:
'''Models Code'''
# Product Model
class Products(models.Model):
    name = models.CharField(max_length=50)
    img = models.ImageField(upload_to='productImage')
    CATEGORY = (
        ('Snacks','Snacks'),
        ('Juice','Juice'),
    )
    category = models.CharField(max_length=50, choices=CATEGORY)
    description = models.TextField()
    price = models.FloatField()
# Rating Model
class Rating(models.Model):
    product = models.ForeignKey(Products, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    stars = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)], blank=True, null=True)
    comment = models.TextField(blank=True,null=True)

''' Views Code '''

class ProductListView(ListView):
    model = Products
    template_name = 'products.html'
    context_object_name ='Products'


class ProductDetailView(LoginRequiredMixin,DetailView):
    login_url = '/accounts/login'
    model = Products

# Using this function I want to take the rating and comment, but how can I access the cuurent object for which the comment and rating is being send by the user.
def review(request,slug):
    star=request.POST.get('rating')
    comment=request.POST.get('comment')
    user = request.user
    productId = request.POST.get('productsid') # How to get the Product
    product = Products.objects.get(id=productId)
    review = Rating(product=product,user=user,stars=star,comment=comment)
    review.save()
    return redirect('/')

# Urls code
urlpatterns = [
  path('',views.home,name='Home'),
  path('products',ProductListView.as_view(),name='Products'),
  path('product/<int:pk>',ProductDetailView.as_view(),name='Product-Details'),
  path('contact',views.contact,name='Contact'),
  path('review',views.review,name='review')

#Templates Code
<form method="POST" action="review">
{% csrf_token %}
<input type="hidden" id="rating-value" name="rating">
<textarea  style="margin-top:5px;" class="form-control" rows="3" id="comment" placeholder="Enter your review" name="comment"></textarea>
<button type="submit" style="margin-top:10px;margin-left:5px;" class="btn btn-lg btn-success">Submit</button>
</form>

如何在review功能中从deatailed view page中获取当前对象? 我在这里添加了代码。在产品详细视图页面中,它正在呈现我想要对产品进行评级和评论的页面。有没有其他方法可以获取 product、user、star 和 rating 字段值并将其存储在数据库中?

【问题讨论】:

    标签: django django-models django-views django-templates django-class-based-views


    【解决方案1】:

    我可以指出一些在您的 review 函数中检索 product_id 的方法。

    第一种方法:

    您可以将product_id 作为 URL 参数传递。在这种情况下,我希望从产品详细信息页面调用review 视图。

    所以,你的网址应该是这样的:

    path('review/<int:product_id>', views.review, name="review),
    

    你的看法:

    def review(request, *args, **kwargs):
        star=request.POST.get('rating')
        comment=request.POST.get('comment')
        user = request.user
        productId = kwargs.get('product_id') # change is here
        product = Products.objects.get(id=productId)
        review = Rating(product=product,user=user,stars=star,comment=comment)
        review.save()
        return redirect('/')
    

    您的模板:

    <form method="POST" action="{% url 'review' object.pk %}">
    {% csrf_token %}
    <input type="hidden" id="rating-value" name="rating">
    <textarea  style="margin-top:5px;" class="form-control" rows="3" id="comment" placeholder="Enter your review" name="comment"></textarea>
    <button type="submit" style="margin-top:10px;margin-left:5px;" class="btn btn-lg btn-success">Submit</button>
    </form>
    

    在模板中,object 是您为产品对象指定的对象名称。您可以通过添加来更改对象名称:

    context_object_name = product
    

    在你的ProductDetailView

    第二种方法:

    将 product_id 作为表单数据传递。您可以在模板中创建一个隐藏输入,该输入将包含 product_id 作为值。例如:

    在您的模板中:

    <form method="POST" action="review">
    {% csrf_token %}
    <input type="hidden" id="rating-value" name="rating">
    <input type="hidden" name="product_id" value="{{ object.pk }}"> # add a hidden input field
    <textarea  style="margin-top:5px;" class="form-control" rows="3" id="comment" placeholder="Enter your review" name="comment"></textarea>
    <button type="submit" style="margin-top:10px;margin-left:5px;" class="btn btn-lg btn-success">Submit</button>
    </form>
    

    object 是我之前提到的。

    然后你可以在视图中检索product_id:

    def review(request,slug):
        star=request.POST.get('rating')
        comment=request.POST.get('comment')
        user = request.user
        productId = int(request.POST.get('product_id')) # here
        product = Products.objects.get(id=productId)
        review = Rating(product=product,user=user,stars=star,comment=comment)
        review.save()
        return redirect('/')
    

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-03
      • 2017-06-06
      • 2012-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多