Skip to main content
 首页 » 编程设计

python之Django 1.8 ModelForm request.POST 取代实例

2024年10月25日23bluestorm

所以我正在使用 Django 1.8 Alpha 代码库,想看看是否还有其他人遇到过这个有趣的问题。我有一个模型表单:

class ChildForm(forms.ModelForm): 
    class Meta: 
        model = Child 
        fields = ('first_name', 'last_name', 'gender', 'birthday', 'avatar') 

我也有我的看法:

@login_required 
def edit_child(request, id): 
    """Edit a child""" 
    child = get_object_or_404(Child, pk=id) 
 
    if not child.parent == request.user: 
        raise Http404() 
 
    form = ChildForm(request.POST, request.FILES, instance=child) 
 
    if request.method == 'POST' and form.is_valid(): 
        form.save() 
        return redirect('dashboard') 
 
    context = { 
        'child': child, 
        'form': form 
    } 
 
    return render(request, 'edit_child.html', context) 

当我在模板中呈现表单时,一切正常,少了一点。初始值为空。在 Django 的过去版本中,同时使用 request.POST 和 instance=child 允许实例闪耀并填充表单。但出于某种奇怪的原因,它似乎接受 request.POST 作为初始状态而不是实例。调试中:

  • 表格已绑定(bind)
  • 表单中的初始数据设置正确
  • 实例设置正确

唯一的问题是渲染。为了展示,这是我使用 crispy_forms 进行表单渲染的模板:

<form role="form" method="post" action="{{ child.get_edit_url }}" enctype="multipart/form-data"> 
    {% csrf_token %} 
    {{ form|crispy }} 
    <button type="submit" class="btn btn-default">Save</button> 
</form> 

有人以前看过这个或看到我明显做错了什么吗?

请您参考如下方法:

事实证明,如果为 BOTH 文件和发布数据返回了字典,我需要明确设置 None:

form = ChildForm(request.POST or None, request.FILES or None, instance=child) 

继续。