我正在尝试在我的模板中使用Django的ModelForm和内联表单。但是,我找不到任何文档可以将多个外键的数据库模型整齐地映射回同一个表。这些是我的模特:
# models.py
class Universities(models.Model):
name = models.CharField(max_length=100)
class Majors(models.Model):
name = models.CharField(max_length=80)
class Resumes(models.Model):
name = models.CharField(max_length=70)
undergrad = models.ForeignKey(Universities, related_name='undergrad_university')
undergrad_major = models.ForeignKey(Majors, related_name='undergrad_major')
grad = models.ForeignKey(Universities, related_name='grad_university')
grad_major = models.ForeignKey(Majors, related_name='grad_major')
如何让Django生成一个表单来提交简历,用户可以在其中输入他们的大学名称和专业?在保存新简历之前,所有这四个用于在各自的数据库中创建新条目(2个在大学中,2个在专业中),类似于inline formset example对于单个外键的工作方式。
答案 0 :(得分:1)
EDIT2:对于makin表格。我想我已经完成了一个覆盖save()方法的个性化表单,类似这样(forms.py):
class YourForm(forms.Form):
fname = forms.CharField(label="name",max_length=70,validators=[#Choose your validators here])
fundergrad = forms.CharField(label="fundergrad",max_length=100,validators=[#Choose your validators here])
fundergrad_major = forms.CharField(label="fundergrad_major",max_length=80,validators=[#Choose your validators here])
fgrad = forms.CharField(label="fgrad",max_length=100,validators=[#Choose your validators here])
fgrad_major = forms.CharField(label="fgrad_major",max_length=80,validators=[#Choose your validators here])
def save(self, datas):
res = Resumes()
res.name = datas['fname']
undergrad = Universities()
undergrad_major = Majors()
grad = Universities()
grad_major = Majors()
undergrad.name = datas['fundergrad']
undegrad_major.name = datas['fundergrad_major']
grad.name = datas['fgrad']
grad_major.name = datas['fgrad_major']
undergrad.save()
undergrad_major.save()
grad.save()
grad_major.save()
res.undergrad = undergrad
res.undergrad_major = undergrad_major
res.grad = grad
res.grad_major = grad_major
res.save()
return res
在views.py中:
def formView(request) :
if request.method == 'POST':
form = YourForm(request.POST)
if form.is_valid():
datas={}
datas['fundergrad']=form.cleaned_data['fundergrad']
datas['fundergrad_major']=form.cleaned_data['fundergrad_major']
datas['fgrad']=form.cleaned_data['fgrad']
datas['fgrad_major']=form.cleaned_data['fgrad_major']
form.save(datas)
#Then do what you have to do in your view
EDIT1 :(没有回答这个问题,但它可以帮助某人,所以我可以在这里解答)
我会尝试使用admin.py中的类似内容:
class UniversitiesInline1(admin.StackedInline):
model:Universities
fk_name = "undergrad"
class UniversitiesInline2(admin.StackedInline):
model = Universities
fk_name = "grad"
class MajorsInline1(admin.StackedInline):
model = Majors
fk_name = "undergrad_major"
class MajorsInline2(admin.StackedInline):
model = Majors
fk_name = "grad_major"
class ResumesAdmin(admin.ModelAdmin)
inlines = [
UniversitiesInline1,
UniversitiesInline2,
MajorsInline1,
MajorsInline2,
]
admin.site.register(Resumes, ResumesAdmin)