我有一个模型,我将其转换为如下形式
模型.py
class Book(models.Model):
name = models.CharField()
description = models.TextField()
class College(models.Model):
name = models.CharField()
books = models.ManyToManyField(Book)
place = models.CharField()
表格.py
from django.forms import ModelForm
from myapp.models import College
class CollegeForm(ModelForm):
class Meta:
model = College
视图.py
def college_view(request):
form = CollegeForm()
if request.method == 'POST':
form = CollegeForm(request.POST):
if form.is_valid():
college_obj = College.objects.create(name=request.POST['name'],
place=request.POST['place'],
books= ???????)
return HttpResponseRedirect(reverse('index'))
return render_to_response('college-detail.html', {'form':form})
所以我上面所做的就是
创建了一个名为的模型,该模型
College
具有many to many
指向Book
使用 html 将模型转换为表单
ModelForm
并呈现为 html当表单与值一起提交时,鉴于我从
request.POST 获取该值并尝试保存到College
模型中。但是您可以观察到大学表格有一个
many to many
字段和两个字段CharField
,所以我已将 char 字段直接保存到表中,但我被困在表中保存多对多字段books
(即模型College
)
所以任何人都可以简单地告诉我如何将manytomany
字段保存到数据库表中我的意思是具有manytomany
字段的模型
提前致谢.....