如何在Django ModelForms中加载实例 [英] How to load an instance in Django ModelForms

查看:51
本文介绍了如何在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:

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.

我只能假定实例无法正确加载吗?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆