I need to set the value of my ForeignKey dropdown = to a url parameter when the form is rendered. I am able to successfully set other form fields to this value, but not the ForeignKey.
I am trying to initialize the 'reference' form field which is a foreign key using the reference_id value which is passed via the url. I can successfully assign this value to the three other fields in the form, but not to 'reference'.
Models.py
class Manifests(models.Model):
reference = models.ForeignKey(Orders)
cases = models.IntegerField()
description = models.CharField(max_length=1000)
count = models.IntegerField()
def __str__(self):
return self.description
Forms.py
class CreateManifestForm(forms.ModelForm):
class Meta:
model = Manifests
fields = ('reference', 'cases', 'description', 'count')
Views.py
def add_manifest(request, reference_id):
if request.method == "POST":
form = CreateManifestForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
try:
order = Orders.objects.get(id=reference_id)
except Orders.DoesNotExist:
pass
instance.reference = order
instance.save()
return redirect('add_manifest', reference_id=reference_id)
#this is where my problem is
form = CreateManifestForm(initial={'reference': reference_id})
reference = request.POST.get('reference')
manifests = Manifests.objects.all().filter(reference=reference)
context = {
'form': form,
'reference_id': reference_id,
'manifests' : manifests,
}
return render(request, 'add_manifest.html', context)
And just in case it's needed:
urls.py
url(r'^add_manifest/(?P<reference_id>\d+)/$', add_manifest, name='add_manifest'),
There are no errors, but the field does not set to the value passed through the URL. Like I have said if I try
form = CreateManifestForm(initial={'cases': reference_id})
then the cases field does take on that value, so I'm just not sure how to navigate this in the case of a foreign key