Django,如何在更新表单视图中包括预先存在的数据

时间:2018-09-25 09:27:50

标签: django

更新时,我看不到预先存在的表单数据。提交数据库更新后,表单工作正常,但是要提交,用户必须输入所有表单数据(包括不会更新的数据)。重新输入时,以前的数据不可见。有没有办法在表单字段中显示正在更新的模型实例的当前数据?

表格:

UpdateSomethingForm(forms.ModelForm):
    class Meta:
    model = Something
    fields = ['field1', 'field2', 'field3']

观看次数:

def update_something(request, object_pk):
    form = UpdateSomethingForm()
    context_dict = {}
    try:
        instance = Something.objects.get(pk=object_pk)
        context_dict['instance'] = instance
    except Something.DoesNotExist:
        context_dict['instance'] = None
    if request.method == 'POST':
        form = UpdateSomethingForm(request.POST, instance=instance)
        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect('/home')
        else:
            print(form.errors)
    context_dict['form'] = form
    return render(request, 'form.html', context=context_dict)

HTML:

<form role="form" method="post">
   {% csrf_token %}
   {{ form|bootstrap }}
   <div class="form-group">
      <button type="submit" class="btn btn-primary">Submit</button>
    </div>
</form>

2 个答案:

答案 0 :(得分:3)

您在POST上传递了实例参数,但没有在GET上传递。

form = UpdateSomethingForm(instance=instance)

完整:

def update_something(request, object_pk):
    try:
        instance = Something.objects.get(pk=object_pk)
    except Something.DoesNotExist:
        instance = None
    if request.method == 'POST':
        form = UpdateSomethingForm(request.POST, instance=instance)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/home')
    else:
        form = UpdateSomethingForm(instance=instance)
    context_dict = {'form': form, 'instance': instance}
    return render(request, 'form.html', context_dict)

答案 1 :(得分:1)

主要问题是,即使可以找到该实例,您也会构造一个空的Form。但是首先,您使视图变得“混乱”。

一个可能更具可读性的视图是:

def update_something(request, object_pk):
    context_dict = {}
    try:
        instance = Something.objects.get(pk=object_pk)
    except Something.DoesNotExist:
        instance = None
    context_dict['instance'] = instance
    if request.method == 'POST':
        form = UpdateSomethingForm(request.POST, instance=instance)
        if form.is_valid():
            form.save(commit=True)
            return redirect('view_name')
    else:
        form = UpdateSomethingForm(instance=instance)
    context_dict['form'] = form
    return render(request, 'form.html', context=context_dict)

在这里,我们确保始终instance定义变量,即使except主体在“射击”中也是如此。

此外,最好使用redirect(..)并通过URL传递视图的名称,因为如果您更改该视图的URL,仍然可以使用。 / p>