[django]form不清空问题解决

Posted iiiiiher

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[django]form不清空问题解决相关的知识,希望对你有一定的参考价值。

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不清空问题解决的主要内容,如果未能解决你的问题,请参考以下文章

django模板添加旧表单数据

elementui form 表单数据不置空问题

django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE的解决办法(转)(代码片段

django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE的解决办法(转)(代码片段

如何在Django视图中使用for循环返回每次迭代[关闭]

Django模板过滤器 - 一行