My django form is never valid. Why is this happening?

I have django application where I want user to be able to upload videos. My view looks like this:

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)

My form:

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

and model:

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)

and my template:

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

When I click submit button, I get: form not valid in terminal. I want form to be created, but form is just never valid. Where is the problem?

Are you setting the title, description and file fields when submitting the form? For now, they're considered required by your form until you set blank=True on the model's fields (you can read more about it here: https://stackoverflow.com/a/8609425/7196167).

Back to Top