Home > Software engineering >  I am creating a django review system. I think my Html is wrong
I am creating a django review system. I think my Html is wrong

Time:11-13

I created the form and added it to view, how I must add it to html form?

index.html

        <form action="." method="post">
    {{ form.as_p }}
    {% csrf_token %}
    <p><input type="submit" value="Add comment"></p>
</form>
      <h1 style="margin:0 57%">Reviews</h1>
    <input type="hidden" name="parent" id="contactparent" value="">
    <div  style="display:flex; padding: 5%;   justify-content: space-around;  flex-wrap: wrap;align-items:center; box-shadow:4px 4px 16px gold;width: 80%;margin:8% 18% 0">
    <div >
     <label for="contactcomment"   placeholder=" Message" >
      Your reviews *
     </label>

views.py

class AddReview(View):
"""Отзывы"""
def post(self, request,pk):
    form = ReviewForm(request.POST,)
    if form.is_valid():
        form = form.save(commit=False)
        #form.Dish = Dish
        form.save()
    review = Reviews.objects.all()
    return render(request,'index.html',{'Reviews':review})

forms.py

class ReviewForm(ModelForm):
class Meta:
    model =  Reviews
    fields = ('name', 'email', 'text')

urls.py path("review/<int:pk>/", AddReview.as_view(), name='add_review'), Request not found. Request URL: http://127.0.0.1:8000/{url 'add_review' dish.id}

enter code here

enter code here

CodePudding user response:

Answer to the original question as to how to add the form to your HTML is to put the form into the context that is sent to the template:

{'form': form, 'Dish': dish, 'Snack': snack, 'Desserts': desserts, 'Lastcourses': lastcourses, 'Reviews': reviews}

Now for the rest. Here's what I had before you made all the changes to your code. The problem, I think is you're mixing function based views with class based views together in the same view. Second, you are handling either get or post when you need to handle both in the same view.

class DishView(View):
    form_class = ReviewForm
    template_name = 'index.html'

    def get(self, request, *args, **kwargs):
        form = self.form_class()
        return render(request, self.template_name, {'form': form})

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            form = form.save(commit=False)
            form.name = request.name
            form.text = request.text
            form.save()
            return redirect(self.path)

        return render(request, self.template_name, {'form': form})

I also think you have an error in your form tag. If you want the form to be submitted back to the same view, then you don't use ".". You can leave the action out:

<form method="post">
<!-- OR -->
<form action="" method="post">
  • Related