Django:表单验证 - 日期不是过去的,用户唯一的日期

我在 Django 中定义表单时遇到问题(python 3.7,django 3.0.8)


我创建了一个模型。这个模型有两个非常重要的字段:date 和 user_id。


要求:date和user_id是唯一的。


我创建了一个与模型关联的表单模型。登录用户填写表格,重要的是定义的日期不能是过去的,也不能出现在数据库中。


我的问题:


一个问题:我的验证与过去的日期相关联 WORKS CORRECT[!],但如果给出了过去的日期,则不会显示任何错误消息。


第二个问题:第二件事是我不知道如何防止定义数据,它存在于数据库中。


代码:模型.py


class MyModel(models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE)

    date = models.DateField()

    ...(other fields)


    class Meta:

        unique_together = [['user', 'date']]

代码:forms.py


class AddMyModel(forms.Form):

    date = forms.DateField(widget=DateInput(attrs={'type': 'date'}),

                           )

    def clean_date(self):

        date = self.cleaned_data['date']

        if date < timezone.now().date():

            raise ValidationError("Date cannot be in the past")



        return date

您是否知道如何设计表单以在模板中显示错误“日期不能来自过去”和错误“给定日期已定义”?


views.py


def add(request):

    if request.user.is_authenticated:

        user = request.user.id


        if request.method == 'POST':

            form = AddMyModel(request.POST)

            if form.is_valid():

                date = form['date'].value()

                mymodel= MyModel(user=User(pk=user), date=date)

                mymodel.save()

                return render(request, 'mysite/successfuladd.html', {"login": True})

        form = AddMyModel()

        return render(request, 'mysite/add.html', {'form': form, 'login': True})

    else:

        return render(request, 'mysite/homepage.html', {'login': False})


GCT1015
浏览 116回答 2
2回答

ITMISS

用日期时间试试这个:def clean_date(self):&nbsp; &nbsp; date = self.cleaned_data['date']&nbsp; &nbsp; if date < datetime.date.today():&nbsp; &nbsp; &nbsp; &nbsp; raise ValidationError(self.error_messages['Date cannot be in the past'], code='Date cannot be in the past')&nbsp; &nbsp; return date

jeck猫

我设法自己解决了这个问题。我的模型是一样的。forms.pyclass AddMyModel(forms.ModelForm):&nbsp; &nbsp; def clean_date(self):&nbsp; &nbsp; &nbsp; &nbsp; date = self.cleaned_data['date']&nbsp; &nbsp; &nbsp; &nbsp; if date < timezone.now().date():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; raise forms.ValidationError(message='Date cannot be in the past')&nbsp; &nbsp; &nbsp; &nbsp; return date&nbsp; &nbsp; class Meta:&nbsp; &nbsp; &nbsp; &nbsp; model = MyModel&nbsp; &nbsp; &nbsp; &nbsp; fields = ('date')&nbsp; &nbsp; &nbsp; &nbsp; widgets = {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'date': forms.DateInput(attrs={'type': 'date'})&nbsp; &nbsp; &nbsp; &nbsp; }views.pydef add(request):&nbsp; &nbsp; if request.user.is_authenticated:&nbsp; &nbsp; &nbsp; &nbsp; user = request.user.id&nbsp; &nbsp; &nbsp; &nbsp; if request.method == 'POST':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; form = AddMyModel(request.POST)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if form.is_valid():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; date = form['date'].value()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if MyModel(user=User(pk=user), date=date):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; unique_error = "User and date is already exist."&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return render(request, 'mysite/add.html',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {'form': form, 'login': True, 'unique_error': unique_error})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mymodel= MyModel(user=User(pk=user), date=date)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mymodel.save()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return render(request, 'mysite/successfuladd.html', {"login": True})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return render(request, 'mysite/add.html',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {'form': form, 'login': True})&nbsp; &nbsp; &nbsp; &nbsp; form = AddMyModel()&nbsp; &nbsp; &nbsp; &nbsp; return render(request, 'mysite/add.html', {'form': form, 'login': True})&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; return render(request, 'mysite/homepage.html', {'login': False})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python