【发布时间】:2021-09-25 18:31:54
【问题描述】:
我正在尝试编写一个模板来创建博客提要,例如具有多个同类实例的博客网站。 现在,每个实例(每个博客文章)都需要自己的点赞按钮。为了实现这个特性,我使用了 AJAX。 我可以通过单击“关注”按钮在数据库中进行更改,但无法使用成功功能在模板中进行更改。 这是模板,
{% for question, count, is_follow in zipp %}
<div class="border rounded my-2 px-3 py-1" style="box-shadow: 2px 2px 5px #2b6dad;">
<p class="fst-normal">
<small>Tags: </small>
{% for tag in question.tags.all %}
<small><a href="{% url 'tag' tag.slug %}" style="text-decoration:none; color:black"><i>{{tag.name}} |</i></a></small>
{% endfor %}
</p>
<p><a href="{{question.get_absolute_url}}" style="text-decoration: none; color: black"><h5>{{ question.question }}</h5>
<small>Arguments added: {{ count }}</small></a></p>
<div class="blank" id="{{question.question_id}}">
{% include 'snippets/follow_question.html' %}
</div>
<button type="button" class="btn btn-secondary btn-sm mt-1"><i class="fa fa-share-alt" style="padding-right: 3px;"></i>Share</button>
</div>
{% endfor%}
脚本
<script type='text/javascript'>
$(document).ready(function(event){
$(document).on('click', '#follow', function(event){
event.preventDefault();
var pk = $(this).attr('value');
$.ajax({
type: 'POST',
url: '{% url 'follow_question' %}',
data: {'id': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
datatype: 'json',
success: function(response){
var id = $(this).closest('.blank').data('id');
$(id).html(response['form']);
},
error: function(rs, e){
console.log(rs.responseText);
},
});
});
});
</script>
据我了解,问题出在成功功能上。我正在尝试在正确的实例中进行更改。我从这个问题中得到了这个想法 Question
follow_question.html
<div class='d-flex flex-row'>
<form action = "{% url 'follow_question' %}" method = "post">{% csrf_token %}
{% if is_follow %}
<button class = "btn btn-sm btn-success" id='follow' type="submit" name="question_id" value={{ question.question_id }}>Followed</button>
{% else %}
<button class = "btn btn-sm btn-success" id='follow' type="submit" name="question_id" value={{ question.question_id }}>Follow</button>
{% endif %}
</form>
Views.py
def follow_question(request):
question = get_object_or_404(Question, question_id = request.POST.get("id"))
is_follow = False
if question.follow.filter(username = request.user).exists():
question.follow.remove(request.user)
is_follow = False
else:
question.follow.add(request.user)
is_follow = True
context = {}
context["question"] = question
context["is_follow"] = is_follow
if request.is_ajax():
html = render_to_string('snippets/follow_question.html', context, request=request)
return JsonResponse({'form':html})
【问题讨论】:
-
is_follow是一个布尔字段? -
是的,is_follow 是一个布尔字段。
标签: javascript jquery django ajax