django表单填充request.POST实例(如果表单无效)

时间:2018-08-27 08:04:56

标签: python django

我有一个学生申请表,提交用户表后,如果表单中有错误(例如,电话号码输入错误),我希望django用先前的POST数据填充该表单

如果我没记错的话,我需要使用instance来实现。但是我不确定如何使它工作。

views.py

def add_new_student(request):

    if request.user.is_authenticated:
        lesson_plans = LessonPlans.objects.all()
        if 'submit_new_student' in request.POST:
            form = NewStudentForm(request.POST)
            if form.is_valid():
                #todo: add cleaned data
                form.save()  # save into DB
            else:  # this is where form is not valid, and where the POST data should fill up the form with the previous `post` data.
                form = NewStudentForm(request.POST, instance=form)
        else:
            form = NewStudentForm()
        args = {
            'form': form,
            'lesson_plans': lesson_plans
        }
        return render(request, 'static/html/new_student.html', args)

我收到的trace error'ModelFormOptions' object has no attribute 'concrete_fields'

有什么想法可以实现这一目标吗?


更新

forms.py

class NewStudentForm(forms.ModelForm):
    class Meta:
        model = models.Student
        fields = [
            'first_name', 'last_name', 'DOB', 'residential_address',
            'medical_history', 'preferred_doctor',
            'parent1_first_name', 'parent1_last_name', 'relationship1_to_student', 'parent1_contact_number',
            'parent1_contact_email',
            'parent2_first_name', 'parent2_last_name', 'relationship2_to_student', 'parent2_contact_number',
            'parent2_contact_email',
            'emergency_contact_name', 'emergency_contact_number',
            'deregistration_date', 'proficiency_level'
        ]


class NewLessonPlansForm(forms.ModelForm):
    class Meta:
        model = LessonPlans
        fields = ['level', 'lesson', 'description']

2 个答案:

答案 0 :(得分:0)

有几种方法可以做到这一点:

将发布的数据存储到上下文中,并在提交失败时将其返回到页面,请确保您在模板侧进行处理。您可以使用类似的方法来做到这一点:

form = ContactForm(initial={'subject': 'Hi there!'})

这个内置的Django解决方案还可以做的是检查数据是否已从此初始状态“更改”,如果没有,则抛出错误。

但是,如果您想返回所有数据,而不是有效的特定字段,只需使用:

form = ContactForm(request.POST)

因此,只要您将先前的答案存储在request.POST对象中,就可以在每次失败时设置初始值。

此处参考:https://docs.djangoproject.com/en/2.1/ref/forms/api/#s-dynamic-initial-values

或者...您可以使用本地存储。将它们的值存储在本地存储中,每当它们返回时,甚至几天后(只要它们没有刷新浏览器缓存),您都可以获取并使用其先前存储的答案。


针对您的设置,您可以使用类似以下内容的

def add_new_student(request):

    if request.user.is_authenticated:
        lesson_plans = LessonPlans.objects.all()
        if 'submit_new_student' in request.POST:
            form = NewStudentForm(request.POST)
            if form.is_valid():
                #todo: add cleaned data
                form.save()  # save into DB
            else:  # this is where form is not valid, and where the POST data should fill up the form with any combination of validated data from the previous `post` data.
                data = {
                   'first_name': request.POST.get('first_name'), 
                   'last_name': request.POST.get('last_name')
                }
                form = ContactForm(data, initial=data)
        else:
            form = NewStudentForm()
        args = {
            'form': form,
            'lesson_plans': lesson_plans
        }
        return render(request, 'static/html/new_student.html', args)

在设置了上述数据和初始值之后,您还可以检查表单在提交时是否发生了更改,如果没有更改,则抛出另一个自定义错误:

if form.has_changed():
   # do something here

答案 1 :(得分:0)

使用POST数据重新显示表单是默认要做的事情。您可以使用第一个else块来防止。删除它。

    if 'submit_new_student' in request.POST:
        form = NewStudentForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('...')
        # no else; invalid form is automatically passed into args below
    else:
        form = NewStudentForm()
    args = {
        'form': form,
        'lesson_plans': lesson_plans
    }
    return render(request, 'static/html/new_student.html', args)
相关问题