简体   繁体   English

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

[英]How do I access form fields in a template in Django?

I am using a model-based form to create a form based off a data model.我正在使用基于模型的表单来创建基于数据 model 的表单。 The insert part works fine, but I am now trying to do the "edit" page.插入部分工作正常,但我现在正在尝试执行“编辑”页面。 my problem is I need the ID/primary key of the original model for the post action and documentation (and a previous thread here) seems to have told me to try both form.id and form.instance.id, but neither seem to work.我的问题是我需要原始 model 的 ID/主键用于发布操作和文档(以及此处的前一个线程)似乎告诉我要同时尝试 form.id 和 form.instance.id,但似乎都不起作用. Any ideas or help is appreciated!任何想法或帮助表示赞赏!

Here's my template:这是我的模板:

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

Here's part of my View:这是我的观点的一部分:

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))

Any help is appreciated and if you need more info, I'll be happy to provide it.任何帮助表示赞赏,如果您需要更多信息,我很乐意提供。 I, of course, am new to Django and real programming so I'm just building off the tutorial and this to learn.当然,我是 Django 和实际编程的新手,所以我只是在构建教程和这个来学习。 Thanks!谢谢!

Update更新

relevant parts of urls.py: 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'),

The Athlete instance will be stored on the ModelForm , so you can do: Athlete实例将存储在ModelForm上,因此您可以执行以下操作:

{{ form.instance.id }}

Also, you want to pass your Athlete instance in the POST case you you'll actually update the instance (rather than create a new one).此外,您想在POST案例中传递您的Athlete实例,您实际上将更新该实例(而不是创建一个新实例)。

If you are staying on the same page during the edit process(for example http://localhost:8000/athlete/edit/1234/ ), you don't need to specify anything in the action attribute on your form, the following should work fine:如果您在编辑过程中停留在同一页面上(例如http://localhost:8000/athlete/edit/1234/ ),则无需在表单的 action 属性中指定任何内容,以下应工作正常:

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

Your form should also pass in the instance object in the POST case:您的表单还应该在 POST 案例中传入实例 object:

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))

I checked it against some code I have for editing a form, your view seems to be fine.我对照一些用于编辑表单的代码检查了它,您的视图似乎很好。 As geekam asked, what is you urls.py like?正如 geekam 所问,你的 urls.py 是什么样的? It should be something like它应该是这样的

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

edit: the regex I posted in the url capture assumes a numerical id- I don't know what your ids are编辑:我在 url 捕获中发布的正则表达式假设一个数字 id-我不知道你的 id 是什么

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM