Я не могу реализовать AJAX в моем приложении для форума django, чтобы разместить вопрос
У меня есть приложение для форума, в котором пользователи могут публиковать свои вопросы. Я хочу предотвратить перезагрузку страницы каждый раз, когда пользователь публикует комментарий к вопросу. Я пробовал реализовать ajax, но это не сработало.
Я сделал это: это forms.py:
class CommentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CommentForm, self).__init__(*args, **kwargs)
# add a "form-control" class to each form input
# for enabling bootstrap
for name in self.fields.keys():
self.fields[name].widget.attrs.update({
'class': 'form-control',
})
class Meta:
model = Comment
fields = ('question', 'reply_to', 'text')
это views.py:
def post_comment(request):
# request should be ajax and method should be POST.
if request.is_ajax and request.method == "POST":
# get the form data
form = CommentForm(request.POST)
# save the data and after fetch the object in instance
if form.is_valid():
instance = form.save()
# serialize in new friend object in json
ser_instance = serializers.serialize('json', [instance, ])
# send to client side.
return JsonResponse({"instance": ser_instance}, status=200)
else:
# some form errors occured.
return JsonResponse({"error": form.errors}, status=400)
# some error occured
return JsonResponse({"error": ""}, status=400)
это urls.py:
urlpatterns = [
path('comment/', post_comment, name='post-comment'),
]
это base.html:
{% block content %}
{% endblock content %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
{% block javascript %}
{% endblock javascript %}
это index.html:
<div class="container-fluid">
<form id="comment-form">
<div class="row">
{% csrf_token %}
{% for field in form %}
<div class="form-group col-4">
<label class="col-12">{{ field.label }}</label>
{{ field }}
</div>
{% endfor %}
<input type="submit" class="btn btn-primary" value="Create comment" />
</div>
</form>
</div>
<hr />
{% endblock %}
{% block javascript %}
<script>
$("#comment-form").submit(function (e) {
e.preventDefault();
var serializedData = $(this).serialize();
$.ajax({
type: 'POST',
url: "{% url 'post-comment' %}",
data: serializedData,
success: function (response) {
// on successfull creating object
// 1. clear the form.
$("#comment-form").trigger('reset');
},
error: function (response) {
// alert the error if any error occured
alert(response["responseJSON"]["error"]);
}
})
})
</script>
{% endblock javascript %}
Должно быть, что-то не так с моим устройством, потому что я пробовал это со многими учебниками и все равно не смог сделать это. Однажды я клонировал репу, и это не сработало.
Поправки
1. In base.html, setup code as this:
{% block content %}
{% endblock %}
{% block javascript %}
{% endblock%}
<script>
document.addEventListener('DOMContentLoaded', (event) => {
//DOM loaded
{% block domready %}
{% endblock %}
})
</script>
2. In index.html, setup code as this:
And judging from the code snippet, **index.html** extends **base.html**, therefore it needs to be loaded in **index.html** as well
{% extends "base.html" %}
{% block content %}
//code stub here
{% endblock %}
{% block javascript %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
{% endblock%}
{% block domready %}
//ajax code stub here
{% endblock %}
[POINTS TO NOTE]
The block named {% block javascript %} will allow you to insert JavaScript files in any template that extends the base.html template.
You add JavaScript code to the {% block domready %} block that was defined in
the event listener for the **DOMContentLoaded event** in the **base.xhtml** template.
This guarantees that your JavaScript code will be executed **once the page has been loaded.**
[Source: Django by Example - Antonio Mele]