Django Form field initial value on failed validation

前端 未结 3 2093
花落未央
花落未央 2021-02-09 11:51

how do I set the value of a field element after a form has been submitted but has failed validation? e.g.

if form.is_valid():
    form.save()
else:
    form.dat         


        
3条回答
  •  一向
    一向 (楼主)
    2021-02-09 12:37

    I ended up doing

    if request.method == 'POST':
        new_data = request.POST.copy()
        form = MyForm(data=new_data)
        if form.is_valid(): 
            form.save() 
        else: 
            new_data['myField'] = 'some different data'
    

    Hope this helps someone

提交回复
热议问题