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. -- 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+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/046a4b4b-57c5-45f2-bfed-84f938cf1e2d%40googlegroups.com.