简体   繁体   中英

Django creating Comment System with Ajax

I want to create a comment system for my page. The system should work without refreshing page.I am very new at Ajax and I probably missing somethings but I don't know what. When I click "comment" button, the page shows something like;

在此处输入图片说明

my codes:

view.py

def post_detail(request, pk, ):
    post = get_object_or_404(Post, pk=pk)
    form = CommentForm(request.POST or None)
    if form.is_valid():
        name = request.POST['name']
        content = request.POST['content']
        comment = Comment()
        comment.name = name
        comment.content= content
        return JsonResponse(model_to_dict(comment), safe=False)
    context = {
        'post': post,
        'form': form,
    }
    return render(request, 'blog/post_detail.html', context)

models.py

class Comment(models.Model):
    name = models.CharField(max_length=200, verbose_name='name')
    content = models.TextField(verbose_name='comment')
    created_date = models.DateTimeField(auto_now_add=True)

comment.html

    {% load crispy_forms_tags %}

<hr>
<form method="POST" style="width: 50%; margin-left: 20px" id="comment_form">
    {% csrf_token %}
    {{ form|crispy }}
    <input type="submit" class="btn btn-info" value="Yorum Ekle" style="margin-left: 20px">
</form>

post_detail.html

...     
    <div id="comment">
    <h2>Yorum Ekle:</h2>
    {% include 'blog/comment.html' %}
    <hr>
    {% for comment in post.comments.all %}
        <h4>{{ comment.name }} |
            <small>{{ comment.created_date|timesince }} önce</small>
        </h4>
        <p>{{ comment.content|linebreaks }}</p>
    {% endfor %}
</div>
<hr>
<hr>
<script type="text/javascript" src="{% static 'js/jquery-1.11.1.min.js' %}"></script>
<script type="text/javascript">

    $(document).ready(function () {
        $("#comment|form").submit(function (e) {
            e.preventDefault();
            var url = "/post/12";
            $.ajax({
                type: 'POST',
                url: url,
                data: $("#comment_form").serializeArray(),
                success: function (data) {
                    console.log('SUCCESS');

                }
            });
        });
    });
</script>

forms.py `

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = [
            'name',
            'content',

        ]

What are my mistakes and how can I fix it? Please help me. Thanks for your attentions.

You have an issue with your selector syntax:

$(document).ready(function () {
    $("#comment|form").submit(function (e) {
        ...

$("#comment|form") should instead be $("#comment_form") in your post_detail.html file.

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