假设我们有一个基本的Contact
日志Call
模型:
更新:似乎我最初的问题没有提供足够的细节来解释我的问题,我已经用更完整的示例和关于我想要的详细信息对其进行了更新。
# Models.py
class Contact(model.Models):
First = ...
Last = ...
Phone = ...
class Log(model.Models):
contact = fields.Foreignkey(Contact)
date = ...
notes = ...
# urls.py
url(r'^logcall/(?P<contact_id>\d+)/$', 'myapp.views.log_call',name='log_call'),
# views.py
def log_call(request, contact_id):
formset = modelform_factory(Log)
form = formset(queryset=Log.objects.none(),initial={'contact':contact_id})
if request.method == 'POST':
form = formset(request.POST,request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/some/place')
else:
form = formset(queryset=Log.objects.none(), initial = {'contact':respondent_id,})
return render_to_response('myform.html', {'formset':form,})
# myform.html
<form method="post" action="">
{{ formset.management_form }}
{% for form in formset %}
{{ form.id }}
{{ form.callid.as_hidden }}
{{ form.contact.as_hidden }}
{{ form.date }}
{{ form.notes }}
{% endfor %}
<button>Submit</button>
</form>
我得到的是:
<form method="post" action="">
<select id="id_form-0-contact" name="form-0-contact">
<option value="" selected="selected">---------</option>
<option value="1011">1011</option>
<option value="31736">31736</option>
<option value="19729">19729</option>
<option value="8818">8818</option>
<option value="19731">19731</option>
<option value="1468">1468</option>
... and so on
...
<button>Submit</button>
</form>
我想要的是以下内容:
<form method="post" action="">
<input type="hidden" id="id_form-0-contact" name="form-0-contact" value="contact_id" />
...
<button>Submit</button>
</form>
因此,每次我加载页面时,它都会调用所有关系数据,当我只需要它包含联系人的隐藏值时,它会根据从 URL 传递的值识别 id。