如何在Django中访问模板中的表单域?

时间:2011-04-29 18:38:40

标签: python django django-forms

我正在使用基于模型的表单来创建基于数据模型的表单。插入部分工作正常,但我现在正在尝试进行“编辑”页面。我的问题是我需要原始模型的ID /主键用于后期操作和文档(以及此前的一个帖子)似乎告诉我尝试form.id和form.instance.id,但似乎都没有工作。任何想法或帮助表示赞赏!

这是我的模板:

<form action="/athlete/edit/{{ form.mod_athlete.id }}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>

以下是我的观点的一部分:

def changeathlete(request, athlete_id):
        if request.method == 'POST': # If the form has been submitted...
                form = AthleteForm(request.POST) # A form bound to the POST data
                if form.is_valid(): # All validation rules pass
                        form.save()
                        return HttpResponse("Athlete changed!") # Redirect after POST
        else:
                mod_athlete = Athlete.objects.get(pk=athlete_id)
                form = AthleteForm(instance=mod_athlete) # An unbound form

        return render_to_response('edit.html', {
                'form': form,
        }, context_instance=RequestContext(request))

感谢任何帮助,如果您需要更多信息,我将很乐意提供。当然,我是Django的新手和真正的编程,所以我只是在构建教程并开始学习。谢谢!

更新

urls.py的相关部分:

url(r'^$', 'rosters.views.index', name='index'),
url(r'^admin/', include(admin.site.urls)),
url(r'^athlete/add/', 'rosters.views.createathlete'),
url(r'^athlete/edit/(?P<athlete_id>\d+)/', 'rosters.views.changeathlete'),
url(r'^meet/(?P<meet_slug>\w+)/', 'rosters.views.meetindex'),
url(r'^meet/(?P<meet_slug>\w+)/(?P<occurence_name>\w+)/', 'rosters.views.occurenceindex'),
url(r'^meet/(?P<meet_slug>\w+)/(?P<occurence_name>\w+)/events/', 'rosters.views.meetevents'),
url(r'^meet/(?P<meet_slug>\w+)/(?P<occurence_name>\w+)/events/(?P<event_id>\w+)/', 'rosters.views.addathletes'),

3 个答案:

答案 0 :(得分:2)

Athlete实例将存储在ModelForm上,您可以这样做:

{{ form.instance.id }}

此外,您希望在Athlete案例中传递POST实例,以便实际更新实例(而不是创建新实例)。

答案 1 :(得分:2)

如果您在编辑过程中停留在同一页面上(例如http://localhost:8000/athlete/edit/1234/),则无需在表单的action属性中指定任何内容,以下内容应该可以正常工作:

<form action="" method="post">{% csrf_token %}
  {{ form.as_p }}
  <input type="submit" value="Submit" />
</form>

您的表单还应传递POST案例中的实例对象:

def changeathlete(request, athlete_id):
    mod_athlete = Athlete.objects.get(pk=athlete_id)
    if request.method == 'POST': # If the form has been submitted...
        form = AthleteForm(request.POST, instance=mod_athlete) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            form.save()
            return HttpResponse("Athlete changed!") # Redirect after POST
    else:
        form = AthleteForm(instance=mod_athlete) # An unbound form

    return render_to_response('edit.html', {
            'form': form,
    }, context_instance=RequestContext(request))

答案 2 :(得分:0)

我根据编辑表单的一些代码检查了它,你的看法似乎很好。正如geekam所问,你是什么样的urls.py? 它应该像

(r'^athlete/edit/(?P<athlete_id>\d+)/$', changeathlete),

编辑:我在网址捕获中发布的正则表达式假定一个数字id-我不知道你的id是什么