我尝试创建模型表单以在Django中向模型添加新记录。我有3个模型,为此模型我创建了表单,视图和模板。
(请注意,在我的项目中,我有很多代码,但是我把一些 他们在这里解释了我的问题。 )
这是我的文件:
models.py
class ResearchRecord(models.Model):
TYPE_CHOICES = (
('1','scientific_research'),
('2','conference'),
)
user = models.ForeignKey(User, on_delete=models.PROTECT)
institutes = models.ForeignKey(EducationalInstitutes, on_delete=models.PROTECT)
title = models.TextField(max_length=250, blank=False)
type = models.TextField(max_length=100, blank=False, choices=TYPE_CHOICES)
year = models.DateField(max_length=100)
upload_url = models.FileField(upload_to='research-resume-files/')
def __str__(self):
return self.title
class EducationalInstitutes(models.Model):
INSTITUTES_CHOICES = (
('1','university'),
('2','education_center'),
('3','school'),
)
name = models.TextField(max_length=100, blank=True)
type = models.TextField(max_length=100, blank=False, choices=INSTITUTES_CHOICES)
description = models.TextField(max_length=500, null=True, blank=True)
educationl_institution_pic1 = models.ImageField(upload_to='educationl-institution-pics/',null=True)
def __str__(self):
return self.name
view.py
def view_research_resume(request):
research_resume =ResearchRecord.objects.filter(user=request.user)
research_resume_dict = {'research_resume':research_resume}
return render(request,'education/job_research_education_records/research_resume/view_research_resume.html',research_resume_dict)
def add_research_resume(request):
if request.method=="POST":
form = AddResearchForm(request.POST)
if form.is_valid():
research_resume = form.save(commit=False)
research_resume.user= request.user
research_resume.save()
return redirect('view_research_resume')
else:
form = AddJobForm()
return render(request, 'education/job_research_education_records/research_resume/add_research_resume.html', {'form': form})
forms.py
class AddResearchForm(ModelForm):
class Meta:
model = ResearchRecord
fields = [
'title',
'type',
'year',
'upload_url',
]
add_research_resume.html
<form method="post" >
{% csrf_token %}
{{form.as_p }}
<button type="submit" class="btn btn-info">add</button>
</form>
urls.py
urlpatterns = [
path('edu/resume/research/', views.view_research_resume, name='view_research_resume'),
path('edu/resume/research/add', views.add_research_resume, name='add_research_resume'),]
我的真实想法是:
我测试我的表单并检查是否有效,但是我无法提交表单。
创建用于在add_research_resume视图中添加新记录的视图,该视图 指定当前用户并选择FK中的研究所 ResearchRecord模型并以表格形式显示数据字段并接收年份 ResearchRecord模型。
请注意,我做了这些事情:
- 首先,我可以成功地对我的模型进行补充,并在 我的模板正确。
- 此外,我想向模型添加新记录,但是由于我的模型 很复杂,并且与其他表相互关联,我无法 将新记录成功添加到我的模型中。