在ModelForm中预设外部实体关系的值 [英] Presetting values on a foreign entity relationship in a ModelForm
问题描述
我的一个表单有一个ManyToOne关系。这种形式对应于关系的一一侧,我知道(并且具有)我需要该值的ID的值。
表单生成一个包含数据库中存在的所有可能值的选择框,但我不希望用户选择。
我如何:
- 修改该特定字段的值而不依赖于接口? (我可以通过JQuery,但它不是一个优雅的方式)
- 防止选择框被显示?
这是ModelForm的代码:
class SomeModelForm ModelForm):
class Meta:
model = SomeModel
并生成形式:
def some_model_signup(request,fk_id):
SomeModelSet = modelformset_factory(SomeModel)
如果请求.method =='POST':
formset = SomeModelSet(request.POST,request.FILES)
如果formset.is_valid():
formset.save()
#do一些东西。
else:
formset = SomeModelFormSet(queryset = SomeModel.objects.none())
返回render_to_response(form.html,{
formset:formset,fk_id :fk_id,
},context_instance = RequestContext(request))
有一个 queryset
参数可以传递给 SomeModelSet
,如 docs 。
I am using ModelForm to generate some forms. One of my forms has a ManyToOne relationship. This forms corresponds to the "One" side of the relationship and I know (and have) the value of the ID I need that value to be.
The form generates a select box with all the possible values that exist in the database but I don't want the user to chose.
How can I: - Fix that value on that specific field without depending on interface? (I can do it via JQuery but it's not an elegant way) - Preventing that select box from being shown?
Here is the code for the ModelForm:
class SomeModelForm(ModelForm):
class Meta:
model = SomeModel
And to generate the forms:
def some_model_signup(request, fk_id):
SomeModelSet = modelformset_factory(SomeModel)
if request.method == 'POST':
formset = SomeModelSet(request.POST, request.FILES)
if formset.is_valid():
formset.save()
# do something.
else:
formset = SomeModelFormSet(queryset=SomeModel.objects.none())
return render_to_response("form.html", {
"formset": formset, "fk_id": fk_id,
}, context_instance=RequestContext(request))
There's a queryset
parameter you can pass to the SomeModelSet
as explained in the docs.
这篇关于在ModelForm中预设外部实体关系的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!