我有一个 work_experience 模型,其中包含“is_working”字段,当用户仍在公司工作时该字段为真。 在前端,我使用的是拨动开关,我想在单击时更改 bool 字段值“is_working”。 在django中使用toggle的逻辑应该是什么?
拨动开关
HTML
<div style="display:inline-block">
<label>Currently working here?</label>
<label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label>
</div>
型号
class Work_Experience(models.Model):
job_title = models.CharField(max_length=100, null=True, blank=True)
company = models.CharField(max_length=100, null=True, blank=True)
description = models.CharField(max_length=300, null=True, blank=True)
exp_start_date = models.DateField(null=True, blank=True)
exp_end_date = models.DateField(null=True, blank=True)
is_working = models.BooleanField(default=False)
最佳答案
为 CharField
提供 null=True
参数是个坏主意。
如果你想在点击时改变 bool 字段值is_working
,你需要使用Jquery。
我创建了一个名为 toggle
的应用,因此您需要将其替换为您的应用名称。
这里是完整的代码
urls.py::
from django.urls import path
from toggle.views import home, toggle
urlpatterns = [
path('', home),
path('toggle/', toggle),
]
views.py:
from django.shortcuts import render
def home(request):
w, created = Work_Experience.objects.get_or_create(id=1)
return render(request,'home.html', {'workexperiance': w})
from django.http import HttpResponse
from toggle.models import Work_Experience
def toggle(request):
w = Work_Experience.objects.get(id=request.POST['id'])
w.is_working = request.POST['isworking'] == 'true'
w.save()
return HttpResponse('success')
home.html:
<div style="display:inline-block">
<label>Currently working here?</label>
<label class="switch">
<input type="checkbox" id="checkbox" value="{{workexperiance.is_working}}">
<span class="slider round"></span>
</label>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script> <!-- Import Jquery Here-->
<script type="text/javascript">
$(document).ready(function() {
$('#checkbox').change(function() {
$.post("/toggle/", {
id: '{{workexperiance.id}}',
isworking: this.checked,
csrfmiddlewaretoken: '{{ csrf_token }}'
});
});
});
</script>
运行:./manage.py runserver
并访问:http://localhost:8000
当您单击Currently working here? 复选框时,将立即 更改 bool 字段值“is_working”。
关于javascript - 如何在 Django bool 字段中使用切换开关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55671266/