简体   繁体   English

在 Django 中使用表单时如何将对象添加到不同的模型?

[英]How to add objects to a different model when using a form in Django?

I have a few forms that retrieve objects through a ForeignKey, eg Flight , Trip .我有一些通过外键检索对象的表单,例如FlightTrip

So, for example, when someone tries to create a new Trip , they can choose an Hotel from a dropdown.因此,例如,当有人尝试创建新的Trip ,他们可以从下拉列表中选择一家Hotel

My question is: how can we, on the Trip form, add an Hotel .我的问题是:我们如何才能在Trip表单上添加一个Hotel Just like when using Django's own admin dashboard, where you get a plus sign, and you can add a new Hotel while creating a Trip .就像使用 Django 自己的管理仪表板时一样,在那里您会得到一个加号,您可以在创建Trip同时添加一个新的Hotel

Edit:编辑:

Hotel is a ForeignKey on the Trip model. HotelTrip模型上的一个外键。 And I am using ModelForm .我正在使用ModelForm

The objective is that you can either choose an existing Hotel or create a new one while creating a Trip .目标是您可以在创建Trip选择现有Hotel或创建新Hotel

I think you are looking for forms.ModelChoiceField .我认为您正在寻找forms.ModelChoiceField
It is used this way:它是这样使用的:

hotel = forms.ModelChoiceField(
    queryset=Hotel.objects.all() # or whatever queryset you want to use
    # Rest of the configuration
)

If I'm not mistaken, it will create an Html Select tag having options with pk of each Hotel object as the value.如果我没记错的话,它会创建一个 Html Select标签,其中包含以每个Hotel对象的pk作为值的选项。 To specify the inner text of each option, you have to define the following method for the Hotel class:要指定每个选项的内部文本,您必须为Hotel类定义以下方法:

def __str__(self):
    return self.name # or whatever needed


If you indeed were looking for this I have to discourage you from using it if you are building a production-grade website/app.如果您确实在寻找这个,如果您正在构建生产级网站/应用程序,我必须劝阻您不要使用它。 A better (and obviously more elaborate) approach is to get the query set of Hotels , serialize them to JSON, create a card/row/widget for each hotel for the user to search and select.更好(显然更精细)的方法是获取Hotels的查询集,将它们序列化为 JSON,为每个酒店创建一个卡片/行/小部件供用户搜索和选择。 However, it is a quick and handy way of managing small projects.但是,它是管理小型项目的一种快捷方便的方法。

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

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