这是我的views.py
def CreateCourseView(request):
TeeFormSet = inlineformset_factory(Golf_Course, Golf_Tee, form=AddTeeForm, extra=1,)
if request.method == "POST":
course_form = AddCourseForm(request.POST)
teeformset = TeeFormSet(request.POST, instance=course_form.instance)
if course_form.is_valid():
course_form.save()
if teeformset.is_valid():
teeformset.save()
return redirect("/")
else:
course_form = AddCourseForm()
teeformset = TeeFormSet()
return render(request, "Courses/add_course_form.html", {'teeformset': teeformset,'course_form': course_form,})
'
以下是我的www.example.com的简要视图models.py
'
class Golf_Tee(models.Model):
# choice list of index values
INDEX = [
(1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 5),
(6, 6),
(7, 7),
(8, 8),
(9, 9),
(10, 10),
(11, 11),
(12, 12),
(13, 13),
(14, 14),
(15, 15),
(16, 16),
(17, 17),
(18, 18),
]
# choice list of par values
PAR = [
(3, 3),
(4, 4),
(5, 5),
]
course = models.ForeignKey(Golf_Course, on_delete=models.CASCADE)
tee_name = models.CharField(max_length=255, unique=True)
course_par = models.IntegerField()
slope = models.DecimalField(decimal_places=2, max_digits=5)
rating = models.DecimalField(decimal_places=2, max_digits=5)
yardage = models.IntegerField()
hole_1_par = models.IntegerField(choices=PAR, default = PAR[1][1])
hole_1_yardage = models.IntegerField(default = 0)
hole_1_index = models.IntegerField(choices=INDEX, default = INDEX[0][0])
hole_2_par = models.IntegerField(choices=PAR, default = PAR[1][1])
hole_2_yardage = models.IntegerField(default = 0)
hole_2_index = models.IntegerField(choices=INDEX, default = INDEX[0][0])
'
我试图不让用户输入总码数,当他们已经为每个洞输入码数时。我想做的是,取hole_1_yardage + hole_2_yardage的值,并将其总和用作码数。
我尝试使用cleaned_data来获取值,但似乎无法保存到模型中。
1条答案
按热度按时间hpxqektj1#
您可以执行以下操作:检查字段
hole_1_yardage
和hole_2_yardage
,如果它们不为空,则重置yardage
的值,而不管其中是否已经存在值。在这种情况下,将基于Golf_Tee
模型创建GolfForm
表单类。表单类位于forms.py
文件中:views.py
模板
urls.py