如何使用html按钮从models.py更改模型值,所以这是我的models.py和main.html
models.py
class Note(models.Model):
topic = models.ForeignKey(Topic, null=True, on_delete=models.SET_NULL)
notes = models.TextField(max_length=3000, null=True)
title = models.CharField(max_length=200, null=True)
clear = models.BooleanField(default=False)
date_created = models.DateTimeField(auto_now_add=True, null=True)
main.html
<div class="col">
{% if note.clear %}
<button class="btn btn-primary btn-sm btn-note">Unclear</button>
{% else %}
<button class="btn btn-primary btn-sm btn-note">Clear</button>
{% endif %}
</div>
每次单击按钮"clear"
时,我都希望将"btn-note"
的值更改为true或false。
答案 0 :(得分:0)
最简单的方法是:
def toggle_note_clear(request):
note = get_object_or_404(Note, pk=request.GET.get('note_id'))
note.clear = not note.clear
note.save()
return redirect('notes:detail') # you should change that with the name of your view
<div class="col">
<!-- make sure you are using the correct name url here -->
<a href="{% url 'notes:toggle_clear' %}?note_id={{note.pk}}"
class="btn btn-primary btn-sm btn-note">
{% if note.clear %}
Unclear
{%else%}
Clear
{%end%}
</a>
</div>
别忘了用上面创建的新视图更新URL。