Django如何关联表单上的外键对象保存

时间:2016-08-02 19:10:32

标签: python django

如何从表单提交中创建对象和外键之间的关系?您可以跳到最后一行代码来查看我的问题。

修改

我的用户无法选择相关的模型对象。相关模型对象将完全由id标识的对象,该URLdomain.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'

navigator.push

1 个答案:

答案 0 :(得分:2)

我终于看到你想做什么,这很容易:

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

之前我感到困惑,因为您有id作为视图函数参数,人们通常会用它来更新contact,因为您在views.py方法中也有ContactForm。您可以使用activity_id使其更明确,并使函数名称更加明确。