B
B
blackbb2015-12-05 16:11:41
Django
blackbb, 2015-12-05 16:11:41

How to automatically populate a ForeignKey field in Django?

Hello. There are two models :

class Hotels(models.Model):
    vip = models.BooleanField(default = False, verbose_name = 'VIP размещение')
    title = models.CharField(max_length=200, verbose_name="Название")
    slug = models.SlugField(unique=True, verbose_name="URL")
    category = models.ForeignKey(Category, verbose_name='Раздел обьявления')
    place = models.ForeignKey(Place, verbose_name='Место расположения')

class Numbers(models.Model):
    title = models.ForeignKey(NumberTitle, verbose_name='Название')
    hotel = models.ForeignKey(Hotels, blank = True, null=True, verbose_name='Отель или гостевой дом, если есть')
    place = models.ForeignKey(Place, default="", verbose_name='Место расположения')

First, the user adds a hotel, then a number to this hotel. It is necessary that the place field in the form for adding a number is automatically filled with the place value from hotel. How to implement it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Andrey K, 2015-12-05
@blackbb

Why implement it in a form? It's better to do it in pre_save Numbers.

@receiver(pre_save, sender=Numbers)
def fill_place(sender, instance, **kwargs):
    instance.place = instance.hotel.place

S
sim3x, 2015-12-05
@sim3x

After creating the hotel, we send the user to the hotel page and by the URL it will be clear to you which hotel the room is being added to

S
some1else, 2015-12-06
@some1else

The question really needs to be asked here is why duplicate the place field in the Number model if it uniquely matches the field from hotel?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question