如何在 Django ModelForms 中加载实例 [英] How to load an instance in Django ModelForms
问题描述
我正在使用 Django 的用户模型.
I am using Django's user model.
如何让 Django ModelForm 预填充模板中的值?我知道我必须使用该表单的实例,但我在下面哪里出错了:
How do I get a Django ModelForm to prepopulate values in a template? I know I have to use the instance for that form, but where am I going wrong below:
models.py:
class Site(models.Model):
user = models.ForeignKey(User, )
site_name = models.CharField(max_length=128, blank=False, null=False)
forms.py:
class SiteForm(forms.ModelForm):
class Meta:
model = Site
fields = '__all__'
views.py:
def settings(request):
site_profile = Site.objects.get(user=request.user)
if request.method == "POST":
form = SiteForm( instance=site_profile )
if form.is_valid():
form.save()
return redirect('dashboard_home')
else:
form = SiteForm()
return render(request, "dashboard/settings.html", {'form': form })
此代码返回没有错误的页面,但不会使用数据库中的值预填充表单字段.
This code returns the page with no errors, however does not prepopulate the form fields with values from the database.
我只能假设 instance
没有正确加载?
I can only assume the instance
is not loading correctly?
推荐答案
def settings(request):
if request.method == "POST":
form = SiteForm(request.POST, instance=request.user.site_profile)
if form.is_valid():
form.save()
return redirect('dashboard_home')
site_profile = Site.objects.get(user=request.user)
form = SiteForm(instance=site_profile)
return render(request, "dashboard/settings.html", {'form': form })
您的缩进已关闭,您从未将 site_profile
传递给表单以填充它.如果出现 POST
请求,您不想将旧版本的 site_profile
传递给表单.我假设您想要用户在模板中填写的新值.
Your indentation was off and you never passed the site_profile
to the form to have it populated. In the event of a POST
request you don't want to pass the old version of site_profile
to the form. I assume you want the new values the user has filled out in the template.
这篇关于如何在 Django ModelForms 中加载实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!