简体   繁体   中英

Add Comment In Django

I have code but when I write comment not write it , and error "POST /post_list HTTP/1.1" 405 0

in views.py :

class AddPost(View):
 def get(self,request):
      form = AddPostForm()
      context = {'form':form}
      return render(request,'add_post.html',context)
 def post(self,request):
      form = AddPostForm(request.POST)
      if form.is_valid():
           form.save()
           return redirect('/')
      else:
           context = {'form':form}
           return render(request,'add_post.html',context)

in forms.py

class AddCommentForm(ModelForm):
def __init__(self,*args,**kwargs):
    super(AddCommentForm,self).__init__(*args,**kwargs)
    self.helper = FormHelper(self)
    self.helper.layout.append(Submit('submit','Add'))

class Meta:
    model = Comment
    exclude = ['post']
    labels = {
        'name' : 'Nickname',
        'comment' : '',
    }
    error_messages = {
        'name':{
            'unique' : 'This Title has been used !'
        }
    }

in post_content.html

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

 {% block title %} {{ post.title }} {% endblock %}

 {% block content %}

    <div align="center" class="divtw" style="width: 50%">


                <h1>{{ post.title }}</h1>
                <h2>{{ post.text }}</h2>
                <h5>{{ post.author }}</h5>
    <hr>
    {% for comments in post.comment_set.all %}

        <div align="left">
            <h5>{{ comments.name }}</h5>
            <p>{{ comments.comment }}</p>
        </div>
        <hr>
    {% endfor %}
    </div>

    <div align="left">
        {% include 'add_comment.html' %}
    </div>




 {% endblock %}

in add_comment.html

{% load crispy_forms_tags %}
<form method="post" action="/post_list">

    {% csrf_token %}

    {% crispy form %}

</form>

when I add comment by admin page it comes with out error for more info this is link for download tutorial and if may tell me what's the problem and how can I save it

The action of your comment form is pointing to "/post_list", which presumably is a listview that renders the list of posts. That view doesn't know what to do with the POST request, hence the 405 error.

It should be pointing to the URL of a view that processes and saves the comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM