我如何使用html按钮改变models.py的模型值,所以这是我的models.py和我的main.html。
模型.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"
值为true或false,每当我点击按钮时 "btn-note"
.
最简单的方法是这样的。
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。