Stan Reduta
Stan Reduta

Reputation: 3492

Assign foreign key when submitting Django Form

I need to assign a non-nullable foreign key field to an object without neither showing this field in the template nor listing it as a form field.

Lets say I have a some model:

class SampleRecord(models.Model):
    foreign_key = models.ForeignKey(OtherModel, blank=False)
    some_field = models.CharField(...)

URL pattern I'm calling has a parameter which determines to which OtherModel object I'll be assigning new SampleRecord thus I have no need to add foreign_key field to Form because every time responsible url pattern is called:

.../new-record/123

I know that I need to create a new instance of SampleRecord assigned to OtherModel object with pk 123. SampleRecord object may not exist without being assigned to OtherModel thus foreign_key field can not be null! Which means it has to be there when submitting the form. In this case I want to use a Form to create new SampleRecord and I don't want to determine foreign_key as field in this form because it'll require me setting a value for it:

class MyForm(forms.ModelForm):
    class Meta:
        model = SampleRecord
        fields = ['some_field']

I understand that I need to override save method inside my form, but I don't understand how to pass OtherModel object to a from a view and then assign it to new object after/during form validation.

Upvotes: 0

Views: 60

Answers (1)

Scott Glascott
Scott Glascott

Reputation: 637

I am new to Django as well but when I do this, it is done in the View not the Form. I use this method in my View:

 def post(self, request):
    form = self.form_class(request.POST)

    if form.is_valid():
        sub = form.save(commit=False)
        sub.sample_record_fk = SampleRecord.objects.get(pk=your_definition)
        sub.save()

        return redirect('Some URL')

Upvotes: 1

Related Questions