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

时间:2022-03-26 19:17:04

I have tried various options for this but no luck so far. I am trying to get instance data to be pre-populated into my ModelField. Here is what I have:

我已经尝试过各种各样的选择但到目前为止没有运气。我试图将实例数据预先填充到我的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()

All I get is an empty field. I can add the initial value to forms.py, but then it is static rather than populated based on the form instance. What I have done here with creating a dict and then passing it to initial in the form instance does not seem to do anything. I'm sure I am missing something basic. Any help would be great! Thanks ahead of time.

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

1 个解决方案

#1


0  

Two last lines recreate your form variable. Just remove else: form = edit_project_info():

最后两行重新创建表单变量。只需删除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()
    # ...

#1


0  

Two last lines recreate your form variable. Just remove else: form = edit_project_info():

最后两行重新创建表单变量。只需删除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()
    # ...