Django Ajax response from model



  • Hello. I would like to know the answer to my question is a view that is responsible for receiving ajax data from the comments form. How to add comments on the page without reloading it. It's not very strong in ajax and jquery, so I'm very grateful to help with the examples of the code. Thank you for your help.

    views.py
    def comment_create(request):
        if request.method == 'POST' and request.is_ajax():
            c = Comments(name=request.POST.get('name', '')[:50],
                     email=request.POST.get('email', '')[:150],
                     web_site=request.POST.get('web_site', '')[:150],
                     comment=request.POST.get('comment', ''),
                     blog_id=request.POST.get('blog', '')
                     )
            c.save()
    
        return HttpResponse('ok')
    

    else:
    return HttpResponse('bad')

    sendform.js

    jQuery(document).ready(function($) {
    $('#submit').click(function () {
    //
    var name = $('input[name=name]');
    var email = $('input[name=email]');
    var web_site = $('input[name=web_site]');
    var comment = $('textarea[name=comment]');
    var blog = $('p#pk').data('item');
    var reply = $('p#reply').data('item');
    //
    var error = '';
    //Проверка введена ли информация в поля формы
    if ((name.val() == '') || (email.val() == '')) {
    error = 'Вы не ввели имя и e-mail';
    if (name.val() == '' && email.val() != '') {
    error = 'Вы не ввели имя'
    }
    if (name.val() != '' && email.val() == '') {
    error = 'Вы не ввели e-mail'
    }
    alert(error)
    };
    if ((comment.val() == '')){
    error = 'Вы не ввели комментарий'
    alert(error)
    };
    //if ((blog.val() != '')){
    //error = 'Pk не отправлено'
    // alert(blog.val())
    //}
    // Если поля заполнены, отправляем их значения
    if (!error) {
    $.ajax({
    url: '/add_comment/',
    type: 'POST',
    datatype: 'html',
    data: {'name': name.val(), 'email': email.val(), 'web_site': web_site.val(), 'comment': comment.val(), 'blog': blog},
    error: function () {
    alert('Ошибка получения запроса')
    },
    success: function (data) {
    ЧТО ПИСАТЬ ЗДЕСЬ ЧТОБЫ ПОСЛЕ ОТПРАВКИ ФОРМЫ
    ДАННЫЕ КОТОРЫЕ БЫЛИ ВВЕДЕНЫ В ФОРМУ КОМЕНТАРИЕВ
    БЕЗ ПЕРЕЗАГРУЗКИ СТРАНИЦЫ ОТОБРАЗИЛИСЬ В ДОБАВЛЕННЫХ
    КОММЕНТАРИЯХ

            }
    
    
    
        });
    }
    



  • I'll have to deal with ajax and jquery if you want to use them.

    In an example you'd better use jquery method. http://api.jquery.com/append/ to the container where you have comments. You'll have the data from the server on the variables, you'll have to put them in some kind of template.

    Well, if it's totally banal, then somehow.

    $('#comments-container').append('<p>' + data.name + '<br>' + data.comment + '</p>')
    

    How would I have organized the Backend?

    In fact, to work with all asynchronous instruments, it's better to follow the rules. https://ru.wikipedia.org/wiki/REST

    In short, when you set up the facility, you must return to the server either 201 created or 400 with json errors. In the construction of the facility, the newly established facility is returned in the same json, not ok and other lines, how they like to do very many who don't lead on this subject.

    If the object needs to be updated, PUT or PATCH methods are used. The HTTP DELETE method is used to remove the facility.

    Api should be divided into two types - a list of objects and a page of detailed examination. Accordingly, the list could be anything, for example, comments. For example, reference /api/comments/. A detailed examination of the comment with id 1 may be arranged by reference / api/comments/1/. Accordingly, the use of:

    • To make a comment, we send POST to /api/comments/. In response, for example

      { 'id': 1, 'text': 'hello world' 'owner': 10 ♪

    • To edit the comment, we send a request to PUT for /api/comments/1/. In response Once again, full objectas in the example above. So you can, for example, update your comment on the page.

    That's enough for starters.

    Now the next question is, how do we do this, and how do we not get excited?

    The solution is, you've been written for a long time. I can advise. http://www.django-rest-framework.org/ ♪ He's got a good browser api, so you're gonna be able to take care of everything you've set up without writing js.

    As to how to get comment objects for a certain post, the rest framework has filters. Accordingly, after their announcement (read) http://www.django-rest-framework.org/api-guide/filtering/ ) you can make some kind of request. /api/comments/?post=25 where 25-id post and receive all comments for him. There's also a panic in it that touches the shelf, so you can also make an endless scrub, for example. But that's what you want.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2