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'