[oldboy-django][2深入django]班级管理(Form)--添加

1.需求: 添加班级,当有某个输入框数据格式不对时,会保留所有输入框的上次输入数据, 同时给出错误信息

2.视图

def add_class(request):
    # 提交数据都要用form来实现,因为要利用django的csrf防御{% csrf_token%}
    if request.method == "GET":
        obj = ClassForm()
        return render(request, 'app01_add_class.html', {'obj':obj})
        # 利用Form组件来生成input输入框,不必自己在前端写,
        # 前端只需要{{ obj.title }} {{ obj.errors.title.0 }}
    else:
        obj = ClassForm(request.POST)
        if obj.is_valid():
            # obj.cleaned_data是一个字典
            # django orm 插入数据(当数据类型为字典时,**dict)
            models.Classes.objects.create(**obj.cleaned_data)
            return redirect("/app01/classes")
        else:
            return render(request, 'app01_add_class.html', {'obj': obj})
View Code

3.模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h4>增加班级</h4>
<form action="/app01/add_class" method="POST">
    {% csrf_token %}
    {{ obj.title }}{{ obj.errors.title.0 }}
    <p><input type="submit" value="提交"></p>
</form>
</body>
</html>
View Code
原文地址:https://www.cnblogs.com/liuzhipenglove/p/7862330.html