E
E
Enter_a_nickname2022-02-10 17:29:46
Django
Enter_a_nickname, 2022-02-10 17:29:46

How to create a form for foreign keys of a model?

Here is what I am trying to do. I'm wondering if anyone can suggest a good approach:

models.py:

class Color(models.Model):
    name = models.CharField(...

class Speed(models.Model):
    name = models.CharField(...

class Dog(models.Model):
    name = models.CharField(...
    speed = models.ForeignKey(Speed...

class DogRequest(models.Model):
    id_name = models.PositiveSmallIntegerField()
    color = models.ForeignKey(Color...
    dog = models.ForeignKey(Dog...
    request_time = models.DateTimeField()


Now I want to have a page where the user can enter the DogRequest as well as data for the models nested in it.

I found a solution back in 2011, but it's clearly outdated and doesn't work for django 4.0
Here it is:
class DogRequestForm(ModelForm):
    class Meta:
        model = DogRequest
        fields = ('id_name','request_time','color','speed')
    color = forms.ModelChoiceField(queryset=Color.objects.all())
    speed = forms.ModelChoiceField(queryset=Speed.objects.all())


How to write a form for such a task?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sparkit, 2022-02-17
@Enter_a_nickname

Here's what Google gives as the first link for "django form from model":
https://docs.djangoproject.com/en/4.0/topics/forms...
Looks like what you were looking for for Django 4.0 as well.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question