Django -如何在保存到模型之前操作表单数据?

xlpyo6sf  于 2023-01-03  发布在  Go
关注(0)|答案(1)|浏览(211)

这是我的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来获取值,但似乎无法保存到模型中。

hpxqektj

hpxqektj1#

您可以执行以下操作:检查字段hole_1_yardagehole_2_yardage,如果它们不为空,则重置yardage的值,而不管其中是否已经存在值。在这种情况下,将基于Golf_Tee模型创建GolfForm表单类。表单类位于forms.py文件中:

from django.forms import ModelForm
from django import forms
from .models import student
from django.core.exceptions import ValidationError

class GolfForm(ModelForm):
    class Meta:
        model = Golf_Tee
        fields = '__all__'

    def clean(self):
        cleaned_data = super().clean()
        hole_1_yardage = cleaned_data.get('hole_1_yardage')
        hole_2_yardage = cleaned_data.get('hole_2_yardage')

        if hole_1_yardage!= None and hole_2_yardage!= None:
            cleaned_data['yardage'] = hole_1_yardage + hole_2_yardage

views.py

from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from .forms import *

class MyFormCreateView(CreateView):
    template_name = 'bboard/tam_form.html'
    form_class = GolfForm
    success_url = reverse_lazy('golf')
    • 模板路径中的bboard,替换为模板所在的应用程序的名称。**

模板

<form method="post">
      {% csrf_token %}
      {{ form.as_p }}
      <input type="submit" value="adding">
</form>

urls.py

from django.urls import path
from .views import *

urlpatterns = [
        path('golf/', MyFormCreateView.as_view(), name='golf'),
    ]

相关问题