1

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

GXM100
  • 417
  • 6
  • 20
  • Why do you want this in the form at all? You ignore it and explicitly set the value before you save anyway. You should exclude it from the form fields. – Daniel Roseman Jul 02 '19 at 12:09

2 Answers2

1

First understand the concept here:

class Manifests(models.Model):
    # Though this reference store id from Orders
    # Its actually a Orders object
    reference = models.ForeignKey(Orders)

In Django when-ever we do foreign-key assignment, foreign object's primary key is stored in current objects column in database only, but when we access it in python code, it returns whole foreign object.

Now let's have look at your problem here:

form = CreateManifestForm(initial={'reference': reference_id})

In above code you are initializing CreateManifestFormCreate 'reference' attribute with Integer object which is wrong as it requires Orders object to be assigned.

form = CreateManifestForm(initial={'cases': reference_id})

And above code is running correctly because 'cases' accept Integer object.

So solution to your problem is:

By querying to Orders object by passing the reference_id

form = CreateManifestForm(initial={'reference': Orders.objects.get(id=reference_id)})

Hope this help !!!

Parikshit Chalke
  • 3,745
  • 2
  • 16
  • 26
0

Looking at the similar question/answer, you would need to set the Orders instance in initial for the reference field, not just the id of the related object.

Maybe you could try something like this and see if that works:

reference_pk = request.POST.get('reference', '')
reference = Orders.objects.get(pk=reference_pk)
form = CreateManifestForm(initial={'reference': reference})
Ralf
  • 16,086
  • 4
  • 44
  • 68