fanne
V2EX  ›  Django

django models form 中,如何获取 ModelForm 接收 post 的值

  •  
  •   fanne · Aug 28, 2018 · 3619 views
    This topic created in 2843 days ago, the information mentioned may be changed or developed.
    from .forms import  UserAddForm
    
        def post(self, request):
            useradd_form = UserAddForm(request.POST)
            if useradd_form.is_valid():
                #此处调用了 models 的功能,可以直接对 forms 直接 save
                user_add = useradd_form.save(commit=False)
                password = useradd_form.cleaned_data['password']
                print user_add.email
                user_add.set_password(password)
                user_add.save()
                print request.user
    
                SaveLog(request.user, '添加用户:{0}'.format(user_add.username), '添加成功')
                return JsonResponse({'status':'success'})
            else:
                SaveLog(request.user, '添加用户', '添加失败')
                return JsonResponse({'status':'fail', 'msg':'错误添加'})
    

    useradd_form 里面存放了前端 post 过来的内容

    里面包括 username ,password 等信息

    那我要怎么取出 username,这个值的

    4 replies    2018-08-29 14:26:32 +08:00
    edsion996
        1
    edsion996  
       Aug 28, 2018
    官方文档没写?
    5oiR5piv5YK76YC8
        2
    5oiR5piv5YK76YC8  
       Aug 29, 2018
    StarainX
        3
    StarainX  
       Aug 29, 2018   ❤️ 2
    useradd_form.cleaned_data 里包含所有 form field 和值 的字典
    fanne
        4
    fanne  
    OP
       Aug 29, 2018
    @StarainX 多谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5905 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 06:11 · PVG 14:11 · LAX 23:11 · JFK 02:11
    ♥ Do have faith in what you're doing.