0

I got problem with my edit comments when i press the edit comment from the template i get no error but is redirected to the top of the same page. Anyone got any idea how i can get it to allow me to edit the comment?

This post is edited with only the code needed and i fixed the delete comment from before so that code is removed.

Here is my code:

views.py:

from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.db.models.functions import Lower

from .models import Product, Category, Review
from .forms import ProductForm, ReviewForm




def product_detail(request, product_id):
    product = get_object_or_404(Product, pk=product_id)
    if request.method == 'POST':
        rating = request.POST.get('rating', 3)
        content = request.POST.get('content', '')
        Review.objects.create(
            product=product,
            rating=rating,
            content=content,
            created_by=request.user
        )
        # redirect to the same page
        return redirect('product_detail', product_id=product_id)

    reviews = Review.objects.filter(product=product)
    context = {
        'product': product,
        'reviews': reviews
    }
    return render(request, 'products/product_detail.html', context)





 @login_required
def edit_review(request, review_id):
    """
    Saves review form edited by user
    """
    review = get_object_or_404(Review, pk=review_id)
    product = Product.objects.get(name=review.product)
    if request.method == 'POST':
        review_form = ReviewForm(request.POST or None, instance=review)
        if review_form.is_valid():
            review_form.save()
            messages.success(request, 'Successfully updated product!')
            return redirect(reverse('product_detail', args=[product.id]))

        # Success message if added
        messages.success(request, 'Thank You! Review was edited')
    else:
        # Error message if form was invalid
        messages.error(request, 'Something went wrong. '
                                'Make sure the form is valid.')

    form = ReviewForm(instance=review)
    messages.info(request, f'You are editing {review_id}')

    template = 'products/edit_review.html'
    context = {
        'form': form,
        'product': review,
    }
    return redirect(reverse('product_detail', args=[product.id]))

models.py:

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





class Review(models.Model):
    product = models.ForeignKey(Product, related_name='reviews', on_delete=models.CASCADE)
    rating = models.IntegerField(default=3)
    content = models.TextField()
    created_by = models.ForeignKey(User, related_name='reviews', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s - %s' % (self.product.name, self.created_by)

urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.all_products, name='products'),
    path('<int:product_id>/', views.product_detail, name='product_detail'),
    path('add/', views.add_product, name='add_product'),
    path('edit/<int:product_id>/', views.edit_product, name='edit_product'),
    path('delete/<int:product_id>/', views.delete_product, name='delete_product'),
    path('delete_review/<int:review_id>/delete_review', views.delete_review, name='delete-review'),
    path('edit_review/<review_id>', views.edit_review, name="edit_review"),
]

forms.py:

from django import forms
from .widgets import CustomClearableFileInput
from .models import Product, Category, Review




class ReviewForm(forms.ModelForm):
    class Meta:
        model = Review
        fields = ('content', 'rating')
        widgets = {
            'content': forms.Textarea(attrs={'class': 'form-control'}),
            'rating': forms.Select(attrs={'class': 'form-control'}),
        }

edit_review.html template

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


{% block content %}
    <div class="overlay"></div>
    <div class="container">
        <div class="row">
            <div class="col-12 col-md-6">
                <hr>
                <h2 class="logo-font mb-4">Reviews</h2>
                <h5 class="text-muted">Edit you're Review</h5>
                <hr>
            </div>
        </div>

        <div class="row">
            <div class="col-12 col-md-6">
                <form method="POST" action="{% url 'edit_review' review.id %}" class="form mb-2" enctype="multipart/form-data">
                    {% csrf_token %}
                    {% for field in form %}
                        {% if field.name != 'image' %}
                            {{ field | as_crispy_field }}
                        {% else %}
                            {{ field }}
                        {% endif %}
                    {% endfor %}
                    <div class="text-right">
                        <a class="btn btn-outline-black rounded-0" href="{% url 'reviews' %}">Cancel</a>
                        <button class="btn btn-black rounded-0" type="submit">Update Review</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
{% endblock %}


 
tobias
  • 69
  • 7
  • I think you have already asked this [question](https://stackoverflow.com/q/72757338/17562044), isn't the same? – Sunderam Dubey Jun 26 '22 at 17:36
  • dident have any code then now i got code in there. – tobias Jun 26 '22 at 17:43
  • 1
    Please remove all the code not related to your problem, make the question more focused. If you get any error - please post this error details, callstack and so on. Describe the process of "editing comments" and elaborate what "not working" means. Do you edit via Admin page or your custom page template? Show that template. Your question currently is not a question at all: it is unclear, unfocused and requires anyone to guess what is going on or debug it oneself and find out what happens and when. Such "questions" are unanswerable, offtopic on SO and usually are closed until revised by author. – Ivan Starostin Jun 26 '22 at 18:54

1 Answers1

1

for the first problem in the delete view you must refer to the model with capital Review

@login_required
def delete_review(request, review_id):
    review = Review.objects.filter(review_id).last()

For the second problem you can see detailed information about this error and how to handle it, from Here