如何在可编辑模式下打开表单-Django

时间:2013-05-03 13:23:16

标签: django django-models django-views

views.py是

def when(request):

    if request.method == 'POST':

        reportform = ReportForm(data=request.POST)

        if reportform.is_valid():
            report = reportform.save(commit=False)
            report.save()
            return redirect('/member/media/')
    else:
        reportform = ReportForm()
    return render_to_response('incident/when.html',{
                  'newreport_menu': True, 
                  'form': reportform,
                   },
                   context_instance=RequestContext(request))

我可以在数据库中插入并保存数据。因此,在保存数据后,如果我再次打开此页面,输入的数据应该处于可编辑模式。最后输入的数据应该显示在字段中。如何执行此操作

谢谢

2 个答案:

答案 0 :(得分:0)

在表单实例化调用中使用instance参数。

答案 1 :(得分:0)

def when(request, instance_id=None):

    report = None
    if instance_id:
        report = Report.objects.get(pk=instance_id)

    if request.method == 'POST':

        reportform = ReportForm(data=request.POST, instance=report)

        if reportform.is_valid():
            report = reportform.save(commit=False)
            report.save()
            return redirect('/member/media/')
    else:
        reportform = ReportForm(instance=report)
    return render_to_response('incident/when.html',{
              'newreport_menu': True, 
              'form': reportform,
               },
               context_instance=RequestContext(request))

保留两个网址,一个用于创建,另一个用于编辑,但两个网址都将使用相同的视图。

url(r'^create/$', 'app.views.when', name='create_report'),
url(r'^edit/(?P<instance_id>\d+)/$', 'app.views.when', name='edit_report')