【问题标题】:Django TypeError: validate_location() missing 2 required positional arguments: 'location' and 'parcare_on'Django TypeError: validate_location() 缺少 2 个必需的位置参数:'location' 和 'parcare_on'
【发布时间】:2018-09-22 11:20:25
【问题描述】:

我正在尝试为我的模型创建验证器,但出现此错误:

validate_location() 缺少 2 个必需的位置参数:'parcare_on' 和 'location'

我想根据采摘当天==parcare_on 来验证该位置的pParking 图是否可用。 我在这里做错了什么?

def clean_fields(self, exclude=None):
    super().clean_fields(exclude=exclude)
    q = Parcare.objects.all().filter(parking_on=self.parking_on)
    if self.location in q:
        raise ValidationError(
            _('%(self.location)s is already ocuppied'),
            params={'location': self.location},
        )

我的模型:

from django.db import models
from django.urls import reverse
from django.db.models.signals import pre_save
from django.utils.text import slugify
from django.conf import settings
from django.utils import timezone
# from datetime import datetime
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from datetime import datetime, timedelta, time
today = datetime.now().date()
tomorrow = today + timedelta(1)
now = datetime.now()
l = now.hour
m=int(now.strftime("%H"))

class ParcareManager(models.Manager):

    def active(self, *args, **kwargs):
        return super(ParcareManager, self).filter(draft=False).filter(parking_on__lte=timezone.now())



class Parcare(models.Model):
    PARKING_PLOT = (
        ('P1', 'Parking #1'), ('P2', 'Parking #2'),('P3', 'Parking #3'),
        ('P4', 'Parking #4'), ('P5', 'Parking #5'),('P6', 'Parking #6'),
        ('P7', 'Parking #7'), ('P8', 'Parking #8'),('P9', 'Parking #9'),
        ('P10', 'Parking #10'),('P11', 'Parking #11'),('P12', 'Parking #12'),
        ('P13', 'Parking #13'),('P14', 'Parking #14'),('P15', 'Parking #15'),
    )
    user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, 
                            null=True, default=1, on_delete=True)
    email=models.EmailField(blank=True, null=True)
    parking_on = models.DateField(auto_now=False, auto_now_add=False,
                                  blank=True, null=True,default=tomorrow,
                                  help_text='Alege data cand doresti sa vii in office')
    parking_off = models.DateField(
        auto_now=False, auto_now_add=False, blank=True, null=True, default=tomorrow,help_text='Alege Data Plecarii')  
    numar_masina = models.CharField(max_length=8, default="IF77WXV", 
    blank=True, null=True, help_text='Introdu Numarul Masinii')
    location = models.CharField(max_length=3, blank=True, default="P1",
                                null=True, choices=PARKING_PLOT,
                                help_text='Alege Locul de Parcare Dorit')
    updated = models.DateTimeField(auto_now=True, auto_now_add=False,blank=True, null=True)
    timestamp=models.DateTimeField(auto_now=False, auto_now_add=True,blank=True, null=True)
    venire = models.TimeField(default=time(9, 00), auto_now=False,
     auto_now_add=False, help_text='Alege Ora Venirii')
    plecare = models.TimeField(default=time(
        18, 00), auto_now=False, auto_now_add=False, help_text='Alege Ora Plecarii')
    booked = models.BooleanField(default=1)
    objects = ParcareManager()

    def __str__(self):
        return self.location + " | " + str(self.parking_on) + " | " + str(self.parking_off)

    class Meta:
        verbose_name_plural = "parcare"
        ordering = ["-parking_on"]

    def clean(self):        
        q = Parcare.objects.filter(parking_on=self.parking_on)

        if self.location in q: #nu merge sa filtram si sa vedem daca locul a fost luat deja
            raise ValidationError(_('Sorry this plot is already taken!'))

        if self.parking_on == today:  # merge--vedem dak parcam azi si dak e tecut de ora 16
            raise ValidationError({'parking_on': _('Please book for a date starting tomorrow')})

        if self.parking_off < self.parking_on: #merge-vedem daca bookam in trecut
            raise ValidationError({'parking_off': _('You cant book for a past date!')})
        if m < 17: # se schimba semnul in > cand va fi in productie
            raise ValidationError({'parking_on':_('Sorry the booking session is closed!')})

    # def clean_save(safe):
    #     if self.parking_on != self.parking_off:
    #         delta=self.parking_off-self.parking_on
    #         print(delta)

    def clean_fields(self, exclude=None):
        super().clean_fields(exclude=exclude)
        q = Parcare.objects.all().filter(parking_on=self.parking_on)
        if self.location in q:
            raise ValidationError(
                _('%(self.location)s is already ocuppied'),
                params={'location': self.location},
            )

【问题讨论】:

  • 您的 validate_location 方法需要 2 个不必要的参数。尝试删除这些 arg 要求,你应该会很好。
  • 如果我删除位置和 parcare_on --> 那么我得到的 'str' 对象没有属性 'parcare_on' :(
  • 只有 def validate_location(self,parcare_on):==>validate_location() 缺少 1 个必需的位置参数:'parcare_on'
  • @shad0w_wa1k3r 我这样做了,我得到了 ==> validate_location() 缺少 1 个必需的位置参数:'location'
  • 抱歉,您应该从参数中删除 self 并保留其他 2。此外,您应该通过 docs on how to write custom validators。验证函数不必在模型类中。

标签: python django validation


【解决方案1】:

您的验证器函数将只接收一个参数,即它正在验证的字段,在您的情况下,只是location。您应该尝试在clean_fields 内进行检查,您可以在其中访问两个字段,即parcare_onlocation。如下所示。

class Parcare(models.Model):
    ...
    def clean_fields(self, exclude=None):
        super().clean_fields(exclude=exclude)
        q = Parcare.objects.all().filter(parcare_on=self.parcare_on)
        if self.location in q:
            raise ValidationError(
                _('%(self.location)s is already ocuppied'),
                params={'location': self.location},
            )

【讨论】:

  • 谢谢你!相同的 bat sh..t validate_location() 缺少 1 个必需的位置参数:'location'
  • 哦,我明白了。在这种情况下,您的验证功能将无法正常工作。您确实需要在 Model 类中使用它,并且需要在 clean_fields 模型方法调用或其他东西中专门调用 validate 函数。这样,您就可以使用self 并进行检查。
  • 谢谢..同样的问题..它就像它不知道如何根据self.parking_on过滤数据库
  • 我没有错误,尽管该位置已预订,但该项目已保存,仅此而已...我将更新我的问题中的功能。
  • @Cohen 那么这个问题应该可以帮助你进一步 - stackoverflow.com/questions/12945339/…
猜你喜欢
  • 1970-01-01
  • 2020-06-13
  • 2021-07-25
  • 2019-05-27
  • 2022-11-29
  • 2020-12-24
  • 2019-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多