简体   繁体   中英

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 .

So, for example, when someone tries to create a new Trip , they can choose an Hotel from a dropdown.

My question is: how can we, on the Trip form, add an 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 .

Edit:

Hotel is a ForeignKey on the Trip model. And I am using ModelForm .

The objective is that you can either choose an existing Hotel or create a new one while creating a Trip .

I think you are looking for 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. To specify the inner text of each option, you have to define the following method for the Hotel class:

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. However, it is a quick and handy way of managing small projects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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