【发布时间】:2019-05-13 00:38:09
【问题描述】:
我有一个网站,允许用户选择他们喜欢的一些爱好。目前,该网站从模型加载这些爱好并用复选框列出它们。我想要做的是当用户保存表单时,它还应该将这些复选框值保存到数据库中 - 即如果他们勾选足球,数据库应该保存这个用户喜欢足球的事实。我是 Django 和 Python 的新手,所以不太清楚如何做到这一点。这是我正在使用的代码。这是 Hobbies 的 Models.py 文件:
TYPES = (
("Football", "Football"),
("Cricket", "Cricket"),
("Swimming", "Swimming"),
("Cycling", "Cycling")
)
class Hobby(models.Model):
myfield = models.CharField(max_length=50, choices = TYPES, default=TYPES[0], null=True)
football = models.BooleanField(default = False)
cricket = models.BooleanField(default = False)
swimming = models.BooleanField(default = False)
cycling = models.BooleanField(default = False)
这是相关的views.py文件:
def profile(request, user):
# use this for debugging:
# import pdb; pdb.set_trace()
if 'email' in request.POST:
email = request.POST['email']
gender = request.POST['gender']
dob = request.POST['dob']
## hobby = request.POST['hobby']
if user.profile:
user.profile.email = email
user.profile.gender = gender
user.profile.dob = dob
## user.profile.hobby = hobby
user.profile.save()
else:
profile = Profile(email=email, gender=gender, dob=dob)
profile.save()
user.profile = profile
user.save()
context = {
'appname': appname,
'username': user.username,
'profile' : user.profile,
'all_hobbies': [hobby[0] for hobby in TYPES],
'loggedin': True
}
return render(request, 'mainapp/profile.html', context)
最后是显示信息的 HTML/JS 代码:
<span class="fieldname">Hobbies</span>
{% for hobby in all_hobbies %}
<input type="checkbox" name={{hobby}} value={{hobby}}> {{hobby}}<br>
{% endfor %}
<input type='submit' value='Save'>
我想要的是一种检查复选框是否已被勾选的方法,如果是,则将数据库/模型中的 BooleanField 的值更改为 True 或 False。但是,我不确定在视图或 JS 代码中的何处执行此操作。有人可以帮我吗?非常感谢。
【问题讨论】:
标签: django database model-view-controller orm django-views