首页 > 解决方案 > Django 表单与 HTML 表单

问题描述

当我使用 Django

{{ forms }}

我使用内置功能呈现的表单,如果用户提交并且字段无效,则清除无效字段但未清除表单中的其余信息,这使用户只能更改引发错误的字段。

当我在提交时使用 HTML 表单时,如果出现错误,所有字段都会被清除,用户必须从头开始重新编写所有信息。

如何在 html 表单中完成与 Django 中相同的功能

{{ forms }}

标签: djangodjango-modelsdjango-viewsdjango-formsdjango-templates

解决方案


您必须在视图中定义表单处理。例子:

class UserLoginView(View):
    def get(self, request):
        # here we process GET request

    def post(self, request):
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            # do something
        else:
            # save form with data as context, and render it 
            context = {'form': form}
            return render(request, 'customers/login.html', context)

推荐阅读