我正在Django电子商务项目中构建一个产品评论应用程序,我无法让我的评论表单显示在主商店应用程序的模板上

qxsslcnc  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(104)

以下是我的设置:
使用Django 3.2.21。Bootstrap4
评论/models.py

from django.db import models
from django.contrib.auth.models import User
from shop.models import Product

class Reviews(models.Model):
    product = models.ForeignKey(
        Product, on_delete=models.CASCADE, related_name='review')
    body = models.TextField()
    rating = models.IntegerField(default=5)
    created_on = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now=True)
    author = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='review')

    class Meta:
        ordering = ['created_on']

    def __str__(self):
        return f"Review {self.rating} {self.body} by {self.author}"

评论/views.py

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from shop.models import Product
from .models import Reviews
from .forms import ReviewForm

def review(request, product_id):
    product = get_object_or_404(Product, pk=product_id)

    if request.method == 'POST': 
        review_form = ReviewForm(request.POST)
        print(review_form)
        if review_form.is_valid():
            print(review_form)
            review_form.save()
            messages.success(request, 'Successfully reviewed product')
            return redirect(reverse('product_detail', args=[product.id]))
        else:
            messages.error(request, 'Failed to add product. \
                Please check the form data is correct')
    else:
        review_form = ReviewForm()
        print(review_form)

    template = 'shop/product_detail.html'
    context = {
        'review_form': review_form,
    }

    return render(request, template, context)

评论/urls.py

from django.urls import path
from . import views

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

评论/forms.py

from .models import Reviews
from django import forms

class ReviewForm(forms.ModelForm):
    class Meta:
        model = Reviews
        fields = (
            'body',
            'rating',
            )

shop/product_detail.html(我有两个表单,第一个正在工作,但review_form没有呈现字段)

{% extends "base.html" %}
{% load static %}
{% load crispy_forms_tags % }

{% block content %}

<div class="container-fluid">
    <div class="row">
        <div class="col-12 col-md-6 col-lg-4 offset-lg-2">
            <div class="image-container my-5">
                {% if product.image %}
                <a href="{{ product.image.url }}" target="_blank">
                    <img class="card-img-top img-fluid" src="{{ product.image.url }}" alt="{{ product.name }}">
                </a>
                {% else %}
                <a href="">
                    <img class="card-img-top img-fluid" src="{{ MEDIA_URL }}noimage.png" alt="{{ product.name }}">
                </a>
                {% endif %}
            </div>
        </div>
        <div class="col-12 col-md-6 col-lg-4">
            <div class="product-details-container mb-5 mt-md-5 text-left">
                <p class="mb-2">Album Title: <strong>{{ product.name }}</strong></p>
                {% if product.artist %}
                <p class="mb-2">Artist: <strong>{{ product.artist }}</strong></p>
                {% else %}
                <p class="mb-0"></p>
                {% endif %}
                {% if product.release_date %}
                <p class="mb-2">Year Released: <strong>{{ product.release_date }}</strong></p>
                {% else %}
                <p class="mb-0"></p>
                {% endif %}
                <p class="mb-2">{{ product.description }}</p>
                <p class="lead mb-0 font-weight-bold">€{{ product.price }}</p>
                {% if product.category %}
                <p class="small mt-1 mb-0 tags">
                    <a class="mx-3" href="{% url 'shop' %}?category={{ product.category.name }}">
                        <i class="fa-solid fa-hashtag"></i>{{ product.category.friendly_name }}
                    </a>
                    <a class="mx-3" href="{% url 'shop' %}?genre={{ product.genre.name }}">
                        <i class="fa-solid fa-hashtag"></i>{{ product.genre.friendly_name }}
                    </a>
                </p>
                {% endif %}

                <form class="form" action="{% url 'add_to_cart' product.id %}?source=product_detail" method="POST">
                    {% csrf_token %}
                    <div class="form-row">

                        <div class="col-12">
                            <p class="mt-3"><strong>Quantity:</strong></p>
                            <div class="form-group w-50">
                                <div class="input-group">

                                    <div class="input-group-prepend">
                                        <button class="decrement-qty btn btn-dark rounded-0"
                                            data-item_id="{{ product.id }}" id="decrement-qty_{{ product.id }}">
                                            <span>
                                                <i class="fa-solid fa-minus"></i>
                                            </span>
                                        </button>
                                    </div>

                                    <input class="form-control qty_input text-center" type="number" name="quantity"
                                        value="1" min="1" max="99" data-item_id="{{ product.id }}"
                                        id="id_qty_{{ product.id }}">

                                    <div class="input-group-append">
                                        <button class="increment-qty btn btn-dark rounded-0"
                                            data-item_id="{{ product.id }}" id="decrement-qty_{{ product.id }}">
                                            <span>
                                                <i class="fa-solid fa-plus"></i>
                                            </span>
                                        </button>
                                    </div>

                                </div>
                            </div>
                        </div>

                        <div class="col-12">
                            <a href="{% url 'shop' %}" class="btn btn-outline-black rounded-0 mt-5">
                                <span class="icon">
                                    <i class="fas fa-chevron-left"></i>
                                </span>
                                <span class="text-uppercase">Keep Shopping</span>
                            </a>
                            <input type="submit" class="btn btn-black rounded-0 text-uppercase mt-5"
                                value="Add to Cart">
                        </div>
                        <input type="hidden" name="redirect_url" value="{{ request.path }}">
                    </div>
                </form>

            </div>
        </div>
    </div>
    <hr>
    <div class="row mb-5">
        <div class="col-6">
            <h3>Reviews</h3>
        </div>
        <div class="col-6">
            <h3>Leave a Review</h3>
            <form method="post" action="{% url 'review' product.id %}">
                {% csrf_token %}
                {{ review_form|crispy }}
                <input type="submit" value="Submit review">
            </form>
               
        </div>
    </div>
    <hr>
</div>
{% endblock %}

{% block postloadjs %}
{{ block.super }}
{% include 'shop/includes/quantity_input_script.html' %}
{% endblock %}

编辑:我已经从产品模板(add_to_cart)和reviews/ www.example.com中添加了另一个表单forms.py,在reviews/ www.example.com中也有一个错字views.py,引用ProductForm而不是ReviewForm,从我尝试不同的东西时起,我已经将其更改回ReviewForm,问题仍然存在。我有两个形式在同一页上,一个是添加产品的数量,并将其添加到购物车,另一个我试图呈现的是一个审查形式的客户留下对该特定产品的审查。如果任何人需要更多的信息让我知道,谢谢你有一个看
模型和表单文件对我来说看起来不错,他们也在revies应用程序中设置。主项目级urls.py路径看起来正常。我在项目中的其他应用程序都设置好了。在product_detail模板上,有另一个用于将商品添加到购物车的表单。
我试过改变网址和重写不同的看法,但没有工作。显示标题和提交按钮,但没有字段。但是当点击sumbit按钮时,它调用页面上的其他表单,并出现(Reverse for 'add_to_cart' with arguments '(',)' not found)错误,add_to_cart_是商店应用程序中的其他表单视图。
任何关于我做错了什么的想法,我只是在学习。
Thanks in advance

r1wp621o

r1wp621o1#

确保在模板中指定要呈现的表单,如下所示:

<form method="post" action="{% url 'review' product.id %}">
    {% csrf_token %}
    {{ review_form.as_p }}
    <button type="submit">Submit Review</button>
</form>

检查表单对象->要进一步排除故障,可以在视图中将review_form对象打印到控制台,以查看它是否有效并包含预期的字段。举例来说:

print(review_form)

模板中的调试->如果您没有看到表单字段正确呈现,您可以在模板中添加调试语句来检查review_form对象是否正确传递到模板:

{% if review_form %}
    {{ review_form }}
{% else %}
    <p>Review form is not provided to the template.</p>
{% endif %}

请在您的views.py中尝试使用以下代码:

from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.urls import reverse
from models import Product
from forms import ReviewForm

def review(request, product_id):
    product = get_object_or_404(Product, pk=product_id)

    if request.method == 'POST':
        review_form = ReviewForm(request.POST)
        print ('Review Inside Post:', review_form)
        if review_form.is_valid():
            review = review_form.save(commit=False)
            review.product = product
            review.author = request.user  # Assuming you are using authentication
            review.save()

            messages.success(request, 'Successfully reviewed product')
            return redirect(reverse('product_detail',
                            args=[product.id]))
        else:
            messages.error(request,
                           'Failed to add review. Please check the form data is correct'
                           )

    if request.method == 'GET':
        review_form = ReviewForm()
        print ('Review Inside Get:', review_form)

    template = 'shop/product_detail.html'
    context = {'review_form': review_form}

    return render(request, template, context)

让我知道上面代码的输出。如果可能的话,在这里贴一张终端的快照。检查终端/浏览器控制台中的错误。让我知道以上建议的反馈。

相关问题