Django自定义字段验证

时间:2019-12-06 20:23:58

标签: django django-forms

我的forms.py中有一个验证函数,需要满足以下条件。这是我的代码。

def clean_time框架必须检查数据库中的以下内容: 1.时间表 2.学生 3.日期

所以,如果我为学生约翰·史密斯选择上午9点的时间。您不能在同一天为学生记录相同的时间范围。我如何做到这一点?谢谢

forms.py


class K8Points_ClassroomForm(forms.ModelForm):
    class Meta:  
            model = K8Points


            fields = ('student_name', 'behavior','academic', 'time_frame','date','day','week_of','class_name')

    def clean_time_frame(self):
            time_frame = self.cleaned_data.get('time_frame')
            date = self.cleaned_data.get('date')
            student_name = self.cleaned_data.get('student_name')
            if (time_frame == ""):
                    raise forms.ValidationError('Field can not be left blank !')
            for instance in K8Points.objects.all():
                    if instance.time_frame == time_frame:
                        raise forms.ValidationError('This timeframe was already logged !' + time_frame)    
            return time_frame    

models.py


from django.db import models
from django.utils import timezone
from django.forms import ModelForm
import datetime
from datetime import date
from django.utils.translation import gettext_lazy as _
import uuid
from model_utils import Choices



# Create your models here.



class TeacherClass(models.Model):
    class_name = models.CharField(max_length = 50, default= "")


    class Meta:
       verbose_name = "Teacher Class Room"

    def __str__(self):
        return self.class_name



class Teachers(models.Model):
     teacherpsid = models.CharField(primary_key = True , default = "", max_length = 50, unique = True)
     teacher_name = models.CharField(max_length= 50)
     grade = models.CharField(max_length = 2)
     class_name = models.ManyToManyField(TeacherClass)

     class Meta:
        verbose_name = "Teacher"


     def __str__(self):
        return self.teacher_name  

class Student(models.Model):
    studentpsid= models.CharField(primary_key = True , default = "", max_length = 50, unique = True)
    student_name = models.CharField(max_length = 50)
    student_grade = models.CharField(max_length = 2, default = "")
    counseling_goal = models.CharField(max_length = 255)
    class_name = models.ManyToManyField(TeacherClass)



    def __str__(self):
        return self.student_name             

class NhsPoints(models.Model):
    date = models.DateField(default=timezone.now) 
    class_name = models.ForeignKey(TeacherClass, on_delete = models.PROTECT, default = "")
    week_of = models.IntegerField()
    day = models.CharField(max_length= 10)
    status = models.CharField(max_length= 10, default = "")


def weeknumber():
      return datetime.datetime.today().isocalendar()[1]

def dayofweek():
    weekday = datetime.datetime.today().weekday()

    if weekday == 6:
        s = 'Sunday'
        return s
    elif weekday ==0:
        m = "Monday"
        return m
    elif weekday ==1:
        t = "Tuesday"
        return t
    elif weekday ==2:
        w = "Wednesday"
        return w
    elif weekday ==3:
        th = "Thursday"
        return th
    elif weekday ==4:
        f= "Friday"
        return f
    elif weekday ==5:
        sa = "Saturday"
        return sa
    elif weekday ==6:
        su= "Sunday"       
        return su


class K8Points(models.Model):
    date = models.DateField(default=timezone.now) 
    class_name = models.ForeignKey(TeacherClass, on_delete = models.PROTECT, default = "")
    student_name = models.ForeignKey(Student,on_delete = models.CASCADE, default ="" ) 
    week_of = models.IntegerField(default=weeknumber)
    day = models.CharField(max_length= 10, default = dayofweek)
    TIME_FRAME = Choices('8:45AM - 9:00AM','9:00AM - 9:30AM','9:30AM - 10:00AM','REC. I 10:00AM -10:10AM','10:10AM-10:40AM','10:40AM-11:10AM','11:10AM-11:40AM','REC II LUNCH 11:40AM-12:20PM'
    ,'12:20PM-12:50PM','12:20PM-12:50PM', '12:50PM-1:20PM','1:20PM-1:50PM','1:50PM-2:20PM','REC. III 2:20PM-2:30PM')
    time_frame = models.CharField(max_length = 40, choices= TIME_FRAME,default="", blank = True)
    behavior = models.IntegerField(default="",null = True)
    academic = models.IntegerField(default="" , null = True)
    daily_total = models.IntegerField(default=0, null = True)


    class Meta:
        verbose_name = "K8-Points"


    def __str__(self):
        return self.student_name  

    def subtotal(self):
       return self.academic + self.behavior

@Eliakin Costa解决方案后的跟踪

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/points/k8_points_classroom

Django Version: 2.2.6
Python Version: 3.7.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'forms.apps.FormsConfig',
 'crispy_forms',
 'users.apps.UsersConfig',
 'points.apps.PointsConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "C:\Users\rzuchowski\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\rzuchowski\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\rzuchowski\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\rzuchowski\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  21.                 return view_func(request, *args, **kwargs)

File "C:\missinglink\points\views.py" in K8_Points_Classroom
  31.         if form.is_valid():

File "C:\Users\rzuchowski\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\forms.py" in is_valid
  185.         return self.is_bound and not self.errors

File "C:\Users\rzuchowski\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\forms.py" in errors
  180.             self.full_clean()

File "C:\Users\rzuchowski\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\forms.py" in full_clean
  381.         self._clean_fields()

File "C:\Users\rzuchowski\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\forms.py" in _clean_fields
  402.                     value = getattr(self, 'clean_%s' % name)()

File "C:\missinglink\points\forms.py" in clean_time_frame
  52.          if models.K8Points.objects.filter(day=day, time_frame=time_frame, student_name=student_name).exists():

Exception Type: NameError at /points/k8_points_classroom
Exception Value: name 'models' is not defined

1 个答案:

答案 0 :(得分:2)

只需更改您的清洁方法即可。

def clean(self):
    cleaned_data = super(K8Points_ClassroomForm, self).clean()

    date = cleaned_data.get("date")
    time_frame = cleaned_data.get("time_frame")
    student_name = cleaned_data.get("student_name")

    if K8Points.objects.filter(date=date, time_frame=time_frame, student_name=student_name).exists():
        raise forms.ValidationError(
            'This timeframe {} was already logged to the student {} on {}'.format(time_frame, student_name.student_name, date)
        )