Django - PrePopulate the Foreign Key on the web page, and use that id to save the model.

342 views
Skip to first unread message

Mayank Tripathi

unread,
Apr 12, 2020, 2:14:51 AM4/12/20
to Django users
Hi All,

I am facing an issue, to pre-populate the Foreign Key on the web page.
Actually i have two models Projects and Modules. 
To create a Module, one has to select the Project and go to Module page for create it, but there the Project is not populated.

Below are the details... Please guide me.

models.py
class Project(models.Model): 
name = models.CharField(max_length = 200, null = True)
startdate = models.DateTimeField()

def __str__(self):
return self.name

class Modules(models.Model): 
project = models.ForeignKey(Project, null = True, on_delete = models.SET_NULL)
modulename = models.CharField(max_length = 200, null = True)
modulestartdate = models.DateTimeField()

def __str__(self):
return self.modulename

forms.py
class ProjectForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = '__all__'


class ModuleForm(forms.ModelForm): 
    class Meta: 
        model = Modules
        fields = '__all__'  

views.py
def projectView (request):
if request.method == 'POST':
form = ProjectForm(request.POST) 
if form.is_valid():
form.save(commit=True)

return render(request, 'budget/projectForm.html', {'form': form})

else :
form = ProjectForm()
return render(request, 'budget/projectForm.html', {'form': form})


def modulesView (request, projectid):
project = Project.objects.get(pk=projectid)
 
if request.method == 'POST':
form = ModuleForm(request.POST) 
if form.is_valid():
form.save(commit=True)

return render(request, 'example/modulesForm.html', {'form': form})

else :
form = ModuleForm(instance=project)
return render(request, 'example/modulesForm.html', {'form': form})

urls.py
    path('testproject/', views.projectView, name='projectView'),
    path('testprojectmodule/<str:projectid>/', views.modulesView, name='modulesView'),

in html forms for both Project and Modules... just using {{ form.as_table }}.

Now after createing the Project, i used the url as http://127.0.0.1:8000/testprojectmodule/1/ 
then my Project should get pre-populated... as reached using the project id which is 1 in this case, but i am getting full drop-down. Refer attached image.
Either the Project should be pre-selected.. or can make it non-editable either will work for me.

Please help.


Capture.PNG

Antje Kazimiers

unread,
Apr 12, 2020, 4:06:19 AM4/12/20
to Django users
Hi, I think in your view modulesView() you need to pass the project id to ModuleForm:

..
else :
form = ModuleForm(projectid)
..

and then you need to overwrite the constructor of ModuleForm by adding an __init__ function:

  def __init__(self, projectid=None, *args, **kwargs):
        super(ModuleForm, self).__init__(*args, **kwargs)
        if projectid is not None:
            self.fields['project'] = forms.ModelChoiceField(
                ...
                queryset=Project.objects.filter(id=projectid)
            )
        
something like that. --Antje

_M_A_Y_A_N_K_

unread,
Apr 12, 2020, 4:58:18 PM4/12/20
to django...@googlegroups.com
Cool, thanks Antje.

Seems it is working now, the only thing is in Drop-down i will have the Project Name for which the URL is rest of the PRojects are removed from drop down.
Now will work to have pre-selected. As of now it will default display as ------ with only one required project name.

Thanks & Regards,
---------------------
Mayank Tripathi
Mo. +1 615 962 2128
"Do what you can, with what you have, where you are -by Theodore Roosevelt"



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/26744cb1-03e3-4189-a438-0b462013bb66%40googlegroups.com.

Antje Kazimiers

unread,
Apr 13, 2020, 5:27:21 AM4/13/20
to django...@googlegroups.com
you're welcome, Mayank!

Adding initial to your ModelChoiceField definition should give you the preselection.

  self.fields['project'] = forms.ModelChoiceField(
                initial=projectid,
                queryset=Project.objects.filter(id=projectid)
            )

Reply all
Reply to author
Forward
0 new messages