N
N
Nick V2016-03-13 23:25:04
JavaScript
Nick V, 2016-03-13 23:25:04

How to catch data both from the form and from ajax?

There is a comment form

form.py

class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = [
            'content'
        ]
        widgets = {'content': w.Textarea(attrs={
            'cols': 80,
            'row': 5,
            'placeholder': 'Comment...',
        })}

there is a view
views.py

class Comment(CreateView):
    form_class = CommentForm
    def form_valid(self, form):
        self.object = form.save(commit=False)
        user = get_object_or_404(UserModel, id=self.request.user.id)
        self.object.user = user
        self.object.article = self.get(request=self)
        self.object.save()
        return HttpResponseRedirect(self.get_success_url())

still have a template
template.py

<div class="well">
        <form action="{% url "comment:comment_create" article.slug %}" method="post">
            {% csrf_token %}
            {{ form.as_p }}
            <input id="comment" type="submit" class="btn btn-primary" value="Submit">
        </form>
    </div>

and there is js
main.js

(function() {
  $(document).ready(function() {

    var csrfSafeMethod, csrftoken, getCookie, parentID, url;

    getCookie = function(name) {
      var cookie, cookieValue, cookies, i;
      cookieValue = null;
      if (document.cookie && document.cookie !== '') {
        cookies = document.cookie.split(';');
        i = 0;
        while (i < cookies.length) {
          cookie = jQuery.trim(cookies[i]);
          if (cookie.substring(0, name.length + 1) === name + '=') {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
          }
          i++;
        }
      }
      return cookieValue;
    };

    csrftoken = getCookie('csrftoken');

    csrfSafeMethod = function(method) {
      return /^(GET|HEAD|OPTIONS|TRACE)$/.test(method);
    };

    parentID = null;
    url = window.location.pathname.replace(/\/\s*$/, '').split('/')[2];

    $('a:contains(Reply)').click(function() {
      return parentID = $(this).attr('data-parent');
    });

    return $('#comment').click(function() {
      if ((parentID != null) && parentID > 0) {
        console.log(parentID);
        return $.ajax({
          type: 'POST',
          url: "/comment/" + url + "/comment_create/",
          beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
              return xhr.setRequestHeader('X-CSRFToken', csrftoken);
            }
          },
          dataType: 'html',
          data: {
            'parentID': parentID
          },
        });
      }
    });
  });

}).call(this);


Tell me how to pass parentID in form_valid ? does
if self.request.is_ajax():not respond to
If you get it in this way,
self.request.POST["parentID"]
there will be an error
error - django.utils.datastructures.MultiValueDictKeyError: "'parentID'"
whatever it was, you need to do this, self.request.POST.get("parentID")but the output is None because request.POST is passed
<QueryDict: {'csrfmiddlewaretoken': ['zkuIhR6yen3k38bGmFKrLfC7jTaACl0N'], 'content': ['']}>
but it doesn't hit parentID . CHADNT?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Valery Ryaboshapko, 2016-03-14
@half-life

The problem is that the POST request is not made from JavaScript, but by the browser itself through the form. Obviously, in this case, self.request.POSTthe parentID key is not in the dictionary.
You need to either remove the default action from the button #comment(then the form will not be processed, and the request will be guaranteed to be sent using AJAX), or add a hidden field to the form, which will be filled using JavaScript or, if possible, on the server in the template.

B
Bulat Kurbangaliev, 2016-03-14
@ilov3

self.request.POST["parentID"]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question