gpt4 book ai didi

django - 未显示表单实例

转载 作者:行者123 更新时间:2023-12-04 16:35:42 24 4
gpt4 key购买 nike

View .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)

对于初始值,显示默认格式。但是,如果我将该值保存到数据库,则值正在保存,但未显示所选格式(表单实例)。

最佳答案

老实说,您的代码很难遵循 - 也很难测试。首先用空函数拆分它:

def date_format(request):
settings = _retrieve_user_settings() # see below
form = _prepare_settings_form(settings) # see below

if request.method == 'POST':
form = _prepare_settings_form(settings, request.POST)
if form.is_valid():
_save_settings(form) # see below
save_msg = 'Date format has been updated.'

return render(request,'setting/date_format.html',
{
...
}
)


def _retrieve_user_settings()
"""
get the logged-in user settings or None if the user is logged off or doesn't have any settings
"""
pass

def _prepare_settings_form(settingsInstance=None, data=None)
"""
prepare the form with the settings provided
use default values if the settings are empty (to pre-fill the form)
"""
pass

def _save_settings(form) # this one is even better out of the view
# throw exception if the form wasn't validated
# retrieve the user for the new settings
# save the settings (attached to the user)
pass

在着手实现这 3 个新的小功能的代码之前,编写它们的单元测试,您一定会以一个很好的工作代码结束。如果您认为这太费力,请查看此 StackOverflow 线程的大小以及您一直在进行的手动测试的数量;)

这只是一个示例,您可以以不同的方式拆分代码 - 但您应该真正避免在 try 语句中使用长 View 和长代码...

关于django - 未显示表单实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17551285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com