Answer the question
In order to leave comments, you need to log in
How to catch data both from the form and from ajax?
There is a comment form
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = [
'content'
]
widgets = {'content': w.Textarea(attrs={
'cols': 80,
'row': 5,
'placeholder': 'Comment...',
})}
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())
<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>
(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);
if self.request.is_ajax():
not respond to self.request.POST["parentID"]
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
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.POST
the 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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question