我正在使用Django的用户模型。
如何让Django ModelForm预先填充模板中的值?我知道我必须使用该表单的实例,但我在下面的地方出错:
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 })
此代码返回没有错误的页面,但是不会使用数据库中的值预填充表单字段。
我只能假设instance
未正确加载?
答案 0 :(得分:2)
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
传递给表单。我假设你想要用户在模板中填写的新值。
答案 1 :(得分:2)
根据我的经验,假设基于函数的视图中的默认行为为GET
请求将避免一些错误,您将摆脱那些if-else
语句。如果您要编辑对象,则需要在GET
请求期间填充表单:
def settings(request):
site_profile = Site.objects.get(user=request.user)
form = SiteForm(instance=site_profile) # GET method
if request.method == "POST":
# Don't forget the request.POST !
form = SiteForm(request.POST, instance=site_profile)
if form.is_valid():
form.save()
return redirect('dashboard_home')
return render(request, "dashboard/settings.html", {'form': form })
答案 2 :(得分:0)
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(instance = site_profile)
return render(request, "dashboard/settings.html", {'form': form })