smilebomb smilebomb - 2 months ago 10x
Python Question

Django how to relate a foreign key object on form save

How can I create a relationship between my object and foreign key from a form submit? You can skip down to the very last line of code to see my issue.


My user will not have an option to select the related model object. The related model object will be exclusively the one identified by the
which is determined from the
, i.e.

class Activity(models.Model):
id = models.AutoField(primary_key=True)

class Contact(models.Model):
id = models.AutoField(primary_key=True)
firstname = models.CharField(max_length=100, null=False, blank=False)
activity = models.ManyToManyField(Activity, blank=True)

class ContactForm(forms.ModelForm):
firstname = forms.CharField(max_length=100,

class Meta:
model = Contact

def index(request, id=None):
if id:
if request.method == 'POST':
contact_form = ContactForm(request.POST)
if contact_form.is_valid():
contact =
# link contact to activity here, activity pk is 'id'


I finally see what are you trying to do, it's pretty easy:

contact =
# link contact to activity here, activity pk is 'id'
activity = Activity.objects.get(id=id)

I was confused before because you have id as view function parameter, which people usually use to update a contact because you also have a ContactForm in method. You might make it more explicit using activity_id instead, and make the function name more explicit as well.