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

相关文章:

  • 2021-10-08
  • 2021-08-16
  • 2021-11-12
  • 2021-10-15
  • 2021-10-30
  • 2022-01-19
  • 2022-01-31
  • 2021-05-29
猜你喜欢
  • 2021-09-28
  • 2021-09-08
  • 2021-12-13
  • 2021-06-10
  • 2021-08-18
  • 2021-11-18
  • 2021-09-27
相关资源
相似解决方案