Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 清洁<;fieldname>;()元';t提出验证错误;曼尼托曼尼菲尔德_Python_Django_Django Forms - Fatal编程技术网

Python 清洁<;fieldname>;()元';t提出验证错误;曼尼托曼尼菲尔德

Python 清洁<;fieldname>;()元';t提出验证错误;曼尼托曼尼菲尔德,python,django,django-forms,Python,Django,Django Forms,为了控制用户可以对任何一个问题应用多少个标记,我为这个边缘案例创建了一个validate\u tags方法,用于QuestionForm。测试后,表格接受超过4个标签限制的标签列表;它应该会引发ValidationError。标记最终会出现在表单的清理数据中 是什么导致ValidationError未引发 class Question(models.Model): title = models.CharField(unique=True, max_length=100) body

为了控制用户可以对任何一个问题应用多少个标记,我为这个边缘案例创建了一个
validate\u tags
方法,用于
QuestionForm
。测试后,表格接受超过4个标签限制的标签列表;它应该会引发ValidationError。标记最终会出现在表单的清理数据中

是什么导致ValidationError未引发

class Question(models.Model):
    title = models.CharField(unique=True, max_length=100)
    body = models.TextField()
    dated = models.DateField(auto_now_add=True)
    likes = models.IntegerField(default=0)
    user_account = models.ForeignKey(
        'users.UserAccount',
        on_delete=models.SET_NULL,
        null=True, blank=True,
        related_name="questions"
    )
    tags = models.ManyToManyField(Tag, related_name='questions')

    class Meta:
        ordering = ['dated']


你的意思是如果len(tags)>4:?也应该是
clean\u tags
而不是
validate\u tags
class QuestionForm(forms.ModelForm):
    tags = forms.ModelMultipleChoiceField(queryset=Tag.objects.all())

    def validate_tags(self):
        tags = self.cleaned_data['tags']
        if tags > 4:
            raise ValidationError(
                "Only attach a maximum of 4 tags.",
                code="tags_limit"
            )
        return tags

    def clean(self):
        cleaned_data = super().clean()
        title = cleaned_data['title']
        tags = cleaned_data['tags']
        for t in tags:
            try:
                self.Meta.model.objects.get(
                    title__exact=title, tags__name__exact=t
                )
            except self.Meta.model.DoesNotExist:
                continue
            else:
                message = "A question like this already exists."
                message += "Reformat your question and/or change your tags."
                self.add_error("body", ValidationError(
                    message, code="invalid")
                )
    class Meta:
        model = Question
        fields = ['title', 'body', 'tags']
        error_messages = {
            'name': {
                'required': "Question must be provided.",
                'unique': "Question already exists. Reformat your question.",
                'max_length': "Make your question more concise."
            },
            'body': {
                'required': "Specify context around your question"
            }
        }

class TestQuestionTagsField(TestCase):
    '''Verify that a User cannot submit a question with more than 4 tags'''

    @classmethod
    def setUpTestData(cls):
        tags = ['tag1', 'tag2', 'tag3', 'tag4', 'tag5']
        tag1, tag2, tag3, tag4, tag5 = [
            Tag.objects.create(name=tag) for tag in tags
        ]
        user = User.objects.create_user("Me")
        user_account = UserAccount.objects.create(user=user)
        data = {
            'title': "How do I render CSS files with Django?",
            'body': "No CSS is rendering in my project",
            'user_account': user_account,
            'tags': [tag1, tag2, tag3, tag4, tag5]
        }
        question_form = QuestionForm(data)
        cls.question_form_tags_error = question_form.errors.as_data()

    def test_question_tag_limit_exceeded(self):
        self.assertTrue(any(
            error.message == "Only attach a maximum of 4 tags."
            for error in self.question_form_tags_error
        ))