视图.py
@login_required
@user_passes_test(lambda u: u.is_superuser)
def date_format(request):
save_msg = ''
user = request.user
try:
settings = Settings.objects.get(user=user.id)
settingsForm = SettingsForm(instance=settings)
except:
settings = None
settingsForm = SettingsForm(initial={'date_format':0, 'time_format':0})
if request.method == 'POST':
settingsForm = SettingsForm(request.POST, instance=settings)
if settingsForm.is_valid():
settings = settingsForm.save(commit=False)
settings.user = user
settings.save()
save_msg = 'Date format has been updated.'
return render(request,'setting/date_format.html',
{
'about_menu': True,
'date_tab':True,
'SettingsForm':settingsForm,
'save_msg': save_msg,
})
模型.py
class Settings(models.Model):
user = models.ForeignKey(User, null=True)
date_format = models.BooleanField('Date format', default=False)
time_format = models.BooleanField('Time format', default=False)
is_contactlist_active = models.BooleanField('Contacts', default=True)
对于初始值,显示默认格式。但是,如果我将该值保存到数据库,则值正在保存,但未显示所选格式(表单实例)。