Python Can';t将多对多字段的值插入django中的其他表中
我正在使用django 1.8。我试图在django中使用CreateView向数据库中插入一个值。我可以把数据插入数据库。问题是插入一个字段的值(多对多)。该字段用于插入另一个表。我将在下面简要解释 型号.pyPython Can';t将多对多字段的值插入django中的其他表中,python,django,postgresql,django-class-based-views,Python,Django,Postgresql,Django Class Based Views,我正在使用django 1.8。我试图在django中使用CreateView向数据库中插入一个值。我可以把数据插入数据库。问题是插入一个字段的值(多对多)。该字段用于插入另一个表。我将在下面简要解释 型号.py class Model1(models.Model): name = models.CharField() address = models.CharField() first_name = models.ManytoManyField(Model2) c
class Model1(models.Model):
name = models.CharField()
address = models.CharField()
first_name = models.ManytoManyField(Model2)
class Model2(models.Model):
first_name = models.CharField()
class sampleForm(forms.ModelForm):
name = forms.TextInput()
address = forms.TextInput()
first_name = forms.TextInput()
class Create(CreateView):
model = Model1
form = sampleForm
def form_valid(form):
form.save()
return super(Create,self).form_valid(form)
forms.py
class Model1(models.Model):
name = models.CharField()
address = models.CharField()
first_name = models.ManytoManyField(Model2)
class Model2(models.Model):
first_name = models.CharField()
class sampleForm(forms.ModelForm):
name = forms.TextInput()
address = forms.TextInput()
first_name = forms.TextInput()
class Create(CreateView):
model = Model1
form = sampleForm
def form_valid(form):
form.save()
return super(Create,self).form_valid(form)
视图.py
class Model1(models.Model):
name = models.CharField()
address = models.CharField()
first_name = models.ManytoManyField(Model2)
class Model2(models.Model):
first_name = models.CharField()
class sampleForm(forms.ModelForm):
name = forms.TextInput()
address = forms.TextInput()
first_name = forms.TextInput()
class Create(CreateView):
model = Model1
form = sampleForm
def form_valid(form):
form.save()
return super(Create,self).form_valid(form)
当我尝试向数据库中插入值时,名称和地址成功地插入到一个表中。“第一个名称”字段需要插入到另一个表中。但它没有插入。有人能帮我做这个吗。在你的视图文件中,我想你可以用这个代码来做
class Create(CreateView):
model = Model1
form = sampleForm
def form_valid(form):
form.save(commit=false)
form.save()
form.save_m2m()
return super(Create,self).form_valid(form)
什么是
sampleForm
?sampleForm表示forms.py文件中的类名。为什么不显示它?问题可能与此有关。现在我已经发布了它…您的期望是错误的:多对多字段允许您关联表。它不会将插入表中的一行的部分副本创建到相关表中。请解释你想要达到的目标。