How to pre-populate a form field with model's foreignkey field's value at form load in Django
I have the following models:
class Member(models.Model):
member_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
class Photo(models.Model):
photo_id = models.AutoField(primary_key=True)
member_photo = models.ImageField(upload_to='member/', null=True, blank=True)
member = models.ForeignKey(Member, on_delete=models.CASCADE)
I have created model form, generic views for creating and updating the Member class.
From here, I want to be able to upload members' photos to the second model 'Photo' directly from the ListView for "Member", by adding a link to the CreateView for uploading the photo.
The ModelForm and CreateView for adding the photos are:
ModelForm
class MemberPhotoAddForm(forms.ModelForm):
class Meta:
model = Photo
fields = ('member', 'member_photo')
widgets = {
'member': forms.TextInput(attrs={'placeholder': 'Type name...', }),
'member_photo': forms.FileInput(attrs={'onchange': 'readURL(this)'}),
}
CreateView
class PhotoUpload(CreateView):
template_name = "member_photo_add.html"
model = Photo
form_class = MemberPhotoAddForm
success_url = reverse_lazy('member_list') # URL for the ListView for Member class
# I am trying to use method 'get_inital()' to pass 'member_id' to the form to add a 'Photo'
def get_initial(self):
member = self.request.GET.get('Member')
return {
'member': member,
}
In urls.py, I have:
...
path('member_acct/photos/add/<int:pk>', views.PhotoUpload.as_view(), name='member_photo_add'),
...
In my template I am traversing thru' the fields in order to display the fields (and their values).
However, as I am intending to do, I am unable to populate the member's primary key value, when the form is loaded (for adding photo) - the field remains blank.
(In a post on SO I have read some poster telling to the effect that
manually go through all the fields you might be not displaying the initial value
But resorting to using the plain form.as_p
also did not help.
Is what I am trying to is the right way? Some guidance would be much appreciated.
Solved it by modifying the CreateView
this way:
def get_initial(self):
member = self.kwargs['pk'] # << Here
return {
'member': member,
}