Как заменить Ajax на (форма Django {% csrf_token %})
Я пытаюсь заменить кнопку "Ответить" формой в моем приложении Django.
Вот мой код Javascript:
$(document).on('click', '.comment-reply-link', function(e) {
$(this).replaceWith("<form method='post'>{% csrf_token %}<div class='form-group'><label for='comment'>Comment:</label><textarea class='form-control' id='comment' rows='5' maxlength='300' minlength='1' name='comment' placeholder='Tell us how you loved this product :D'></textarea></div><button type='submit' name='post_comment' value='True'>Comment</button></form>");});
// The replacing line should contain no whitespace.
// Otherwise it will raise Uncaught SyntaxError: Unexpected token ILLEGAL
Я получаю элемент формы, но проблема в том, что {% csrf_token %} обрабатывается как Unicode в replaceWith(). {% csrf_token %} необходим в Django для отправки формы. Любая помощь и совет будут благодарны:)
Изменить: я предполагаю, что {% %} означает, что Django должен быть вовлечен, чтобы получить правильное значение. Поэтому я подумал, что мне нужно сделать HTML-страницу с формой и обновить ее с помощью кнопки "Ответить". Вот моя логика.
view.html
<div class="reply">
<a class='comment-reply-link' href='{% url "rango:reply_form" %}'aria-label='Reply to Araujo'>Reply</a>
</div>
reply.js
function ajax_get_update(item){
$.get(url, function(results){
//get the parts of the result you want to update. Just select the needed parts of the response
// var reply_form = $("#reply_form", results);
var reply_form = $(".head", results);
console.log(reply_form);
//console.log(results);
//update the ajax_table_result with the return value
$(item).html(reply_form);
}, "html");
}
$(document).on('click', '.reply', function(e) {
console.log("Debuggin...");
e.preventDefault();
url = ($( '.comment-reply-link' )[0].href);
console.log(url);
ajax_get_update(this);
});
reply_form.html
<!DOCTYPE html>
... code omitted ....
<form id="reply_form" method="post">
{% csrf_token %}
<div class="form-group">
<label for="comment">Reply:</label>
<textarea class="form-control" id="comment" rows="5" maxlength="300" minlength="1" name="comment" placeholder="Tell us how you loved this product :D"></textarea>
</div>
<button type="submit" name="post_comment" value="True">Reply</button>
</form>
</body>
</html>
Когда я нажимаю кнопку ответа, кнопка исчезает, но ничего не обновляется. Результаты переменной html-страницы получают правильные данные html-страницы, но похоже, что
$(item).html(reply_form);
не работает правильно. Потому что когда я делаю
$(item).html('<p>button disappears</p>');
абзац появится. Какие-нибудь мысли?
1 ответ
Чтобы использовать язык шаблонов django в javascript, вы должны инкапсулировать свой код в тег Verbatim.
пример:
{% verbatim %}
var hello = {% if some_condition %} 'World' {% else %} 'foobar' {% endif %};
{% endverbatim %}
Из документов: Останавливает механизм шаблонов от рендеринга содержимого этого тега блока. Обычно используется для того, чтобы разрешить слой шаблона JavaScript, который конфликтует с синтаксисом Django
В твоем случае:
<script>
{% verbatim %}
$(document).on('click', '.comment-reply-link', function(e) {
$(this).replaceWith("<form method='post'> {% csrf_token %} </form>")
};
{% endverbatim %}
</script>