Home:ALL Converter>How do I populate my form fields with data from the database Django

How do I populate my form fields with data from the database Django

Ask Time:2019-04-20T18:24:25         Author:IceTea

Json Formatter

Hello I have a form page and I only need users to fill in certain fields, with the rest of the fields being pre-filled for them based on the module they pick.

While I can fetch the objects from my database -- i.e. the dropdown list shows Module Object (1), Module Object (2) -- I need only certain fields in these objects, which is why this similar sounding post couldn't answer my question: Populate a django form with data from database in view

Here's my forms.py

class inputClassInformation(forms.Form):
    module = forms.ModelChoiceField(queryset=Module.objects.all())
    duration = forms.CharField(disabled=True, required=False)
    description = forms.CharField()
    assigned_professors = forms.ModelChoiceField(queryset=Class.objects.filter(id='assigned_professors'))

models.py -- not the full models are shown to reduce the post's length

class Module(models.Model):
    subject = models.CharField(max_length=200, default="")

class Class(models.Model):
    module = models.ForeignKey(Module, on_delete=models.CASCADE, default="")
    duration = models.CharField(max_length=200, default="")
    description = models.CharField(max_length=200, default="")
    assigned_professors = models.CharField(max_length=200, default="")

So an expected result would be:
1) The Module field shows the subjects, instead of Module objects in its dropdown list and
2) The duration field is automatically filled in for the user, based on the module they picked. The reason is so that the user only has to manually fill in certain fields, while the rest are automatically generated.

This has had me stuck for a long while, help is appreciated. Thanks!

Author:IceTea,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/55772545/how-do-i-populate-my-form-fields-with-data-from-the-database-django
yy