使用对象数据预填充模型表单 - Django

时间:2017-08-14 17:41:31

标签: django django-forms

我为此尝试了各种选择,但到目前为止还没有运气。我试图将实例数据预先填充到我的ModelField中。这就是我所拥有的:

forms.py

class edit_project_info(ModelForm):
    project_name = forms.CharField(max_length=150)


class Meta:
    model = Project
    exclude = ['project_type', 'created_date', 'start_date', 'end_date', 'pm_scope', 'dev_scope', 'design_scope', 'testing_scope' ]

View.py

def edit_project (request, offset):
    this_project = Project.objects.get(pk=offset)
    data = {'project_name' : 'abc'}
    if request.method == 'POST':
        form = edit_project_info(request.POST, instance=this_project, initial=data)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/project_profile/%s/' % offset)
    else:
        form = edit_project_info()

我得到的只是一片空地。我可以将初始值添加到forms.py,但是它是静态的而不是基于表单实例填充。我在这里创建一个dict然后将它传递给表单实例中的初始化似乎没有做任何事情。我确定我遗漏了一些基本的东西。任何帮助都会很棒!提前谢谢。

1 个答案:

答案 0 :(得分:0)

最后两行重新创建form变量。只需删除else: form = edit_project_info()

即可
def edit_project (request, offset):
    this_project = Project.objects.get(pk=offset)
    data = {'project_name' : 'abc'}
    form = edit_project_info(request.POST, instance=this_project, initial=data)
    if request.method == 'POST':
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/project_profile/%s/' % offset)
    # else:
    #     form = edit_project_info()
    # ...