https://www.cnblogs.com/OldJack/p/7118396.html

有时候提交表单后,发现某个字段写错了,但是form的其他字段竟然被清空,这个万万不能接受.所有django的form后端生成form的html,渲染到前端可以解决
1.前端写form的html
2.django的form生成前端form所需的html

forms.html

#!/usr/bin/env python
# coding=utf-8

from django import forms
from django.shortcuts import render


class LoginForm(forms.Form):
    username = forms.CharField(error_messages={'required': "主机不能为空"})
    password = forms.CharField(required=True)

views.py

from django.http import HttpResponse
from django.shortcuts import render

from .forms import LoginForm


# Create your views here.


def login(request):
    "表单验证:前端自己写form的html"
    if request.method == "GET":
        return render(request, "app01/login.html")
    else:
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            username = request.POST.get('username', '')
            password = request.POST.get('password', '')
            return HttpResponse("%s:%s" % (username, password))
        return render(request, "app01/login.html", {'login_form': login_form})


def login2(request):
    "表单验证: 后端生成form的html,解决了form不清空问题"
    if request.method == "GET":
        login_form = LoginForm()
        return render(request, "app01/login2.html", {"login_form": login_form})
    else:
        login_form = LoginForm(request.POST)

        if login_form.is_valid():
            username = request.POST.get('username', '')
            password = request.POST.get('password', '')
            return HttpResponse("%s:%s" % (username, password))
        return render(request, "app01/login2.html", {'login_form': login_form})

浏览器不允许为空,可以打空格(后端form也校验不通过)
[django]form不清空问题解决