smilebomb smilebomb - 4 months ago 15
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.

edit



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
id
which is determined from the
URL
, i.e.
domain.com/myview/100


models.py


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)


forms.py


class ContactForm(forms.ModelForm):
firstname = forms.CharField(max_length=100,
widget=forms.TextInput(attrs={'placeholder':'John'}))

class Meta:
model = Contact


views.py


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

Answer

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

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

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 views.py method. You might make it more explicit using activity_id instead, and make the function name more explicit as well.