美文网首页
django页面form添加和编辑

django页面form添加和编辑

作者: syp_xp | 来源:发表于2017-05-10 20:58 被阅读687次

    文章转载于 https://my.oschina.net/u/2723480/blog/702874

    现在要实现一个form的添加和编辑,就是说对一个数据库表的操作

    def log(request,id=0):
        assert isinstance(request, HttpRequest)
        if request.method == 'POST':
            form = app.forms.LogForm(request.POST)
            if form.is_valid():
                id = form.data['id']
                if id:
                    model = app.models.ChangeLog.objects.get(id=id)
                else:
                    model = app.models.ChangeLog()
                model.serial_number = form.cleaned_data['serial_number']
                model.name = form.cleaned_data['name']
                model.type = form.cleaned_data['type']
                model.remark = form.cleaned_data['remark']
                model.save()            
            id = 0
        else:
            if id:
                form = app.forms.LogForm(instance = app.models.ChangeLog.objects.get(id=id))
            else:
                form = app.forms.LogForm()
        return render(request,'app/log.html',{
                'title': '变更记录',
                'form': form, #获得表单对象
                'data':app.models.ChangeLog.objects.all(),
                'id': id
                })
    

    重点关注 form = app.forms.LogForm(instance = app.models.ChangeLog.objects.get(id=id)),通过模型实例化表单,可以实现文章再编辑

    相关文章

      网友评论

          本文标题:django页面form添加和编辑

          本文链接:https://www.haomeiwen.com/subject/gwngtxtx.html