如何在表单完成期间设置外键(python / django) [英] how to set foreign key during form completion (python/django)
问题描述
在表单处理期间,我希望能够在模型对象上设置外键字段,而无需用户从下拉列表中选择键。
例如:
#models.py
class AAA(models.Model):
some_field = models.TextField()
class BBB(models.Model):
another_field = models.TextField()
key_field = models.ForeignKey('AAA')
用户将从显示 AAA实例的视图导航到将创建的create_object样式视图给定参数 AAA的 BBB实例。在代码中设置了外键以指向 AAA实例。
django注释框架似乎可以做到这一点,但我不知道怎么做。 / p>
有什么想法吗?我确信它应该很简单。
您可以排除 key_field
从模型表单中保存,用 commit = False
保存,然后在视图中设置 key_field
,然后保存到数据库。
class BBBForm(forms.ModelForm):
class Meta:
model = BBB
exclude =( key_field,)
def create_view(request,** kwargs):
if request.method == POST:
aaa =#get来自网址,会话或其他地方的aaa
form = BBBForm(request.POST)
if form.is_valid():
bbb = form.save(commit = False)
bbb .key_field = aaa
bbb.save()
return HttpResponseRedirect( / success-url /)
...
During form processing I'd like to be able to set a foreign key field on a model object without the user having to select the key from a dropdown.
For instance:
#models.py
class AAA(models.Model):
some_field = models.TextField()
class BBB(models.Model):
another_field = models.TextField()
key_field = models.ForeignKey('AAA')
The user will navigate from a view showing an instance of 'AAA' to a create_object style view that will create an instance of 'BBB' given a parameter referring to 'AAA'. The foreign key is set in code to point back to the 'AAA' instance.
The django comments framework seems to do this but I can't figure out how.
Any ideas? I'm sure it should be quite simple.
You can exclude the key_field
from your model form, save with commit=False
, then set key_field
in your view before saving to the database.
class BBBForm(forms.ModelForm):
class Meta:
model = BBB
exclude = ("key_field",)
def create_view(request, **kwargs):
if request.method == "POST":
aaa = # get aaa from url, session or somewhere else
form = BBBForm(request.POST)
if form.is_valid():
bbb = form.save(commit=False)
bbb.key_field = aaa
bbb.save()
return HttpResponseRedirect("/success-url/")
...
这篇关于如何在表单完成期间设置外键(python / django)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!