【发布时间】:2016-08-12 02:10:24
【问题描述】:
我刚刚开始学习 django,但遇到了一个问题。我不知道如何更新 数据库行(字段)。目前,当我调用 form_valid 时,我的数据库表正在添加额外信息。
是的,我读到了这个:How to update an object from edit form in Django?
但这对我不起作用。它仍然每次都在添加更多信息。
View.py
def form_valid(self, form, **kwargs):
print 'heeee'
students = Student.objects.all()
studies = Student_in_Subgroup.objects.all()
subgroups = Subgroup.objects.all()
lists = self.request.POST.getlist('studs[]')
sum = 0
for student in students:
for l in lists:
if student.id == int(l):
for studie in studies:
if studie.student_Id.id == student.id:
for subgroup in subgroups:
if studie.subgroup_Id.id == subgroup.id:
print student.id
studentId = student.id
key = subgroup.student_group_id
sum = sum + 1
if subgroup.number == None:
continue
subgroupId = studie.subgroup_Id.id
if (self.request.POST.get('act1')=='add'):
#problem sowhere here I THINK
instance = get_object_or_404(Subgroup, id=subgroupId)
form = ApplicationFormaFull1(self.request.POST or None, instance=instance)
form.save()
#problem sowhere here I THINK
xxx=form['sub']
xxx.student_group = StudentGroup.objects.get(id=key)
xxx.number = self.request.POST.get('act2')
xxx.type = self.request.POST.get('act3')
xxx.stundent_count = sum
xxx.save()
yyy=form['stud_sub']
yyy.subgroup_Id = Subgroup.objects.get(id=subgroupId)
yyy.student_Id = Student.objects.get(id=studentId)
yyy.save()
else:
print('no')
return super(IndexView, self).form_valid(form)
Form.py
class FormSubgroup(forms.ModelForm):
class Meta:
model = Subgroup
exclude = ['student_group','number','type','student_count']
class FormStudent_in_Subgroup(forms.ModelForm):
class Meta:
model = Student_in_Subgroup
exclude = ['subgroup_Id','student_Id']
class ApplicationFormaFull1(MultiModelForm):
form_classes = {
'sub': FormSubgroup,
'stud_sub': FormStudent_in_Subgroup
}
也许有人知道解决方案
【问题讨论】:
-
您需要让我们知道您所说的“额外信息”是什么意思。
-
例如我想添加一个新行(学生姓名,姓......)
标签: python django database forms