我的django表单永远无效,为什么会发生这种情况?

pnwntuvh  于 2022-12-24  发布在  Go
关注(0)|答案(1)|浏览(140)

我有django应用程序,我希望用户能够上传视频。我的视图看起来像这样:

class CreateVideo(View):
    def post(self, request):
        videos = models.Video.objects.all().order_by('-created_on')
        form = forms.VideoUploadForm(request.POST)

        if form.is_valid():
            print('form is valid')
            video = form.save(commit=False)
            video.save()
            print('video uploaded')
        else:
            print('form not valid')

        context = {
            'video_list': videos,
            'form': form,
        }

        return redirect('index')
    def get(self, request):
        videos = models.Video.objects.all().order_by('-created_on')
        form = forms.VideoUploadForm()

        context = {
            'video_list': videos,
            'form': form,
        }
        return render(request, 'videos/upload_video.html', context)

我的表单:

class VideoUploadForm(forms.ModelForm):
    class Meta:
        model = Video
        fields = ['title', 'description', 'file']

和型号:

class Video(models.Model):
    video_id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        unique=True
    )
    title = models.CharField(max_length=50, null=True)
    description = models.CharField(max_length=500, null=True)
    file = models.FileField(null=True)
    created_on = models.DateTimeField(default=timezone.now, null=True)
    at = models.ForeignKey(at, on_delete=models.CASCADE, null=True)

和我的模板:

<div>
        <form method="post">
            {% csrf_token %}
            {{ form | crispy }}
            <button>Submit!</button>
        </form>
    </div>

当我点击提交按钮时,我得到:终端中的表单无效。2我想创建表单,但是表单永远无效。3问题出在哪里?

fdx2calv

fdx2calv1#

您在提交表单时是否设置了标题、描述和文件字段?目前,在您对模型字段设置blank=True之前,它们被视为表单所必需的(您可以在此处阅读更多信息:https://stackoverflow.com/a/8609425/7196167)。

相关问题