我是 Django 和 Python 的新手,花了几天时间尝试解决这个问题。我在这里尝试了其他线程中的几种方法,但我认为我缺少一些基本概念,因为它们都不适合我。这就是我正在尝试做的事情:
我正在使用 ModelForm,并且创建了一个用于添加包含外键的记录的表单。我希望默认设置此值以匹配我链接的页面上显示的记录。 [下面显示的代码经过编辑以显示建议的更正]。
这是views.py中的相关代码:
def add_sighting(request):
unit = request.GET.get('unit')
form = SightingForm(request.POST or None, initial={'unit':unit})
if form.is_valid():
sighting = form.save(commit=False)
sighting.save()
return redirect(index)
return render_to_response('trainapp/add_sighting_form.html',
{'unit': unit, 'sighting_form': form},
context_instance=RequestContext(request))
以下是 add_sighting_form.html 中的相关代码:
<form action="/trainapp/add_sighting/" method="post">
{% csrf_token %}
<table>
{{ sighting_form.as_table }}
</table>
<input type="submit" value="Save" />
</form>
这是我链接的模板中的相关代码:
<p><a href="/trainapp/add_sighting/?unit={{ unit.id }}">Add sighting</a></p>
最佳答案
有几种方法可能在这里起作用。
最简单的方法是在创建表单实例时使用初始参数,然后将其传递到某个 View 的上下文中。
假设您正在使用如下 View 方法:
def some_view( request ):
id = request.GET.get( 'record-id' )
# do check if id is valid...
# load some record
record = Record.objects.get( pk=id )
# create a form instance
form = RecordForm( initial={ 'some_key_field_name':record.id } )
# set up context
context = Context({
'record' : record,
'form' : form
})
# render the templateview using the above context
# and return a HttpResponse ...
如果您使用基于类的 View ,则可以重写 get_context_data 以获得类似的结果。
基于类的 View
根据您的代码,我还想建议您看看 Django 中基于类的 View 。 他们可以为您处理获取和发布表格。它甚至会为您创建(默认)表单。
发布的代码的等效内容如下:
class CreateSightingView( CreateView ):
model = Sighting
def get_context_data( self, **kwargs ):
# call the super to get the default context
data = super( CreateSightingView, self ).get_context_data( **kwargs )
# add the initial value here
# but first get the id from the request GET data
id = self.request.GET.get( 'record-id' )
# again: do some checking of id
data.get( 'form' ).initial[ 'unit' ] = id
return data
关于django - 将外键放入表单中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12829085/