我知道我可能不应该为这个问题打开另一个帖子,因为在这里已经多次询问和回答。是的,我已经完成了教程并浏览了很多网页 - 我所拥有的是我的混合我在这里和其他网站找到但我很难在数据库中保存表单输入。
有人应该来救我,我一直试图让这件事完成3天,非常令人沮丧。
这是我的代码
models.py class QuestionBank(models.Model):
First_Semester ='First_Semester'
Second_Semester ='Second_Semester'
Semesters = ((First_Semester, 'First_Semester'),(Second_Semester, 'Second_Semester'))
level = models.ForeignKey(ClassLevel)
CourseTitle = models.CharField(max_length=50, null=False)
CourseCode = models.CharField(max_length=10, null=False )
CourseUnit = models.IntegerField()
Semester = models.CharField(max_length=20, choices=Semesters, default="Select_Semester")
Date = models.DateField()
question_papers = models.FileField(upload_to = 'QuestionPapers')
def __str__(self):`enter code here`
return '%s %s %s %s %s %s %s' %(self.level, self.CourseTitle, self.CourseCode, self.CourseUnit, self.Semester, self.Date, self.question_papers )
forms.py
class QuestionBankForm(forms.ModelForm):
class Meta:
model = QuestionBank
fields = ('level', 'CourseTitle', 'CourseCode', 'CourseUnit', 'Semester', 'Date', 'question_papers' )
views.py
def uploadQpapers(request):
context = RequestContext(request)
if request.method == 'POST':
Qpapers = QuestionBankForm(data=request.POST)
if Qpapers.is_valid():
Qpapers.save()
return render_to_response("Qbank/uploadQpapers.html", {'Qpapers':Qpapers}, context)
else:
return HttpResponse('INVALID')
我希望能够上传过去的问题并将其保存到数据库但是它不起作用没有错误消息,因为只有当我尝试保存时才返回else语句,我真的不知道该怎么做我需要有人帮助我。提前谢谢
答案 0 :(得分:1)
def uploadQpapers(request):
context = RequestContext(request)
Qpapers = QuestionBankForm(request.POST, request.FILES)
if request.method == 'POST':
if Qpapers.is_valid():
Upload_Qpapers = Qpapers.save(commit=False)
if 'question_papers' in request.FILES:
Upload_Qpapers.question_papers = request.FILES['question_papers']
Qpapers.save()
return HttpResponse("ALL GOOD DATA SAVED")
else:
return HttpResponse("NOT GOOD")
else:
Qpapers = QuestionBankForm()
return render_to_response("Qbank/uploadQpapers.html", {'Qpapers':Qpapers}, context)
我以前的代码错过了quest.FILES,我没有单独保存上传的文件 我希望这个解决方案可以帮助像我这样的另一个初学者