django 测试模型形式 - ValidationError 不是有效的 UUID

django test a modelform - ValidationError not a valid UUID

我正在测试模型并收到 ValidationError。我的模型、视图和测试如下:

型号

class Course(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    course_name = models.CharField(max_length=30)
    grade_level = models.CharField(max_length=4, default="SEC")

查看

@ method_decorator([login_required, teacher_required], name='dispatch')
class CourseUpdateView(PermissionRequiredMixin, UpdateView):
    raise_exceptions = True
    permission_required = 'gradebook.change_course'
    permission_denied_message = "You don't have access to this."

    model = Course
    fields = ['course_name', 'grade_level', ]
    template_name_suffix = '_update'

    def get_success_url(self, *args, **kwargs):
        return reverse('gradebook:coursedetail', kwargs={'course_pk': self.object.pk})

形式

class CourseForm(ModelForm):
    class Meta:
        model = Course
        fields = ('course_name', 'grade_level',)

    def __init__(self, user, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.qc = Course.objects.filter(user=user)

    def clean(self):
        super(CourseForm, self).clean()
        course_name = self.cleaned_data.get('course_name')
        if course_name and self.qc.filter(course_name__iexact=course_name).exists():
            raise ValidationError("A course with that name already exists.")
        if len(course_name) > 20:
            if len(course_name) > 10:
                raise ValidationError(
                    "Your course name cannot be longer than 20 characters")

        return self.cleaned_data

测试

class CourseUpdateTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.user = CustomUser.objects.create_user(
            username='tester',
            email='tester@email.com',
            password='tester123',
            is_teacher=True,
            is_active=True,
        )
        cls.user.save()

    def test_CourseUpdate_valid(self):
        request = HttpRequest()
        request.POST = {
            'user': self.user,
            'id': '4d192045-07fa-477f-bac2-5a99fe2e7d46',
            'course_name': "Science",
            'grade_level': "SEC"
        }
        form = CourseForm(request.POST)
        self.assertTrue(form.is_valid())

我得到的错误:

Raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ["“{'user': <CustomUser: tester>, 'id': '4d192045-07fa-477f-bac2-5a99fe2e7d46', 'course_name': 'Science', 'grade_level': 'SEC'}” is not a valid UUID."]

我试过不把 id 放在 request.POST 中,但得到了同样的错误。

我最初尝试使用以下方法测试有效表单:

def test_CourseUpdate_valid(self):
        form = CourseForm(data={
            'user': self.user,
            'id': '4d192045-07fa-477f-bac2-5a99fe2e7c04',
            'course_name': "Science",
            'grade_level': "SEC"
        },)
        self.assertTrue(form.is_valid())

虽然这没有用,给我错误 TypeError: __init__() missing 1 required positional argument: 'user'

您原来的解决方案不好,因为您在表单初始化函数中缺少 user 位置参数。

其次,如果您想将其余字段(iduser)传递给表单,您的 CourseForm class 应该指定它们。

您可能只是不将 iduser 传递给测试中的 CourseForm 数据,因为它们不相关。

这应该有效:

def test_CourseUpdate_valid(self):
        form = CourseForm(self.user, data={
            'course_name': "Science",
            'grade_level': "SEC"
        },)
        self.assertTrue(form.is_valid())

你能试试吗?如果问题仍然存在,请告诉我?