如何在Django ModelForms中加载实例

时间:2015-07-14 12:13:22

标签: python django django-models django-forms django-views

我正在使用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未正确加载?

3 个答案:

答案 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 })
  1. 第12行中的else块有一个缩进
  2. 您还必须在else块
  3. 中设置实例参数