我正在尝试创建一个ModelForm,其中包含(但不只是)一个可以添加无限项目的字段。需要说明的是,常见的“待办事项”列表示例几乎正是我要执行的操作,其中用户可以在输入中添加项目,并在添加到“待办事项”列表中时显示给用户。在该表单中,用户可以在提交包含其他字段(例如标题和描述)的表单之前,在列表中添加任意数量的项目。
我已经看到了如何使用自定义表单来执行此操作,但是我试图掌握ModelForms,并将该学习项目中的所有表单都保留为ModelForms。
我的问题是,使用ModelForms可以吗?我以为可以创建一个数组,可以将每个添加的项附加到该数组,最后提交表单时,可以将该数组存储在db中,但实际实现这一点超出了我的技能水平。这是正确的轨道,还是有更好的方法?感谢您帮助我学习!
答案 0 :(得分:0)
您不需要在数据库中存储阵列。只需为数组项创建一个新表。在这种情况下,您必须为“ ToDo”创建一个与用户(或列表)具有多对一关系的Django模型。例如:
class UserForm(forms.ModelForm):
class Meta:
fields = [...]
model = User
class ToDoForm(forms.ModelForm):
class Meta:
fields = [...]
model = ToDo
然后创建其表单:
if request.method == 'POST':
user_form = UserForm(request.POST)
todo_form = ToDoForm(request.POST)
if user_form.is_valid() and todo_form.is_valid():
user = user_form.save()
todo_form.save()
todo_form.cleaned_data['user'] = user
return HttpResponseRedirect('/success')
if request.method == 'GET':
context = {
'user_form': user_form,
'todo_form': todo_form,
}
else:
context = {
'user_form': UserForm(),
'todo_form': ToDoForm(),
}
return TemplateResponse(request, 'your_template.html', context)
查看:
<form action="your_view" method="POST">
{% csrf_token %}
{{ user_form.as_p }}
{{ todo_form.as_p }}
<button type="submit">
</form>
模板:
print("Section 7.1 Practice Problem 1")
print("Answer to Problem 1 =")
def __init__(self):
st = LGstudent
name = input("Enter student's name: ")
st.setName(name)
midterm = float(input("Enter student's grade on midterm exam: "))
st.setMidterm(midterm)
final = float(input("Enter student's grade on final exam: "))
st.setFinal(final)
print("\nNAME\tGRADE")
print(st)
class LGstudent:
def __init__(self, name="", midterm=0, final=0):
self._name = name
self._midterm = midterm
self._final = final
def setName(self, name):
self._name = name
def setMidterm(self, midterm):
self._midterm = midterm
def setFinal(self, final):
self._final = final
def calcSemGrade(self):
average = (self._midterm + self._final) / 2
average = round(average)
if average >= 90:
return "A"
elif average >= 80:
return "B"
elif average >=70:
return "C"
elif average >=60:
return "D"
else:
return "F"
def __str__(self):
return self._name + "\t" + self.calcSemGrade()