The 'file' attribute has no file associated with it

Viewed 211

when I add a video from addvideo templates file its say: The 'file' attribute has no file associated with it. I want a user to be able to upload video.

when I add videos from my admin it's working fine, but when I added it from my form page its added the video in admin but its does not show the video in the home page and it's highlight my video tag src="{{video.file.url}}" saying: 'file' attribute has no file associated with it.

this is my models:

class Video(models.Model):
    file = models.FileField(upload_to='file', null=False, blank=False)

this is my views:

def addvideo(request):
    if request.method == 'POST':
        file = request.FILES.get('video')
        videos = Video.objects.create(
            file=file
        )
        return redirect('home')
    return render(request, 'addvideo.html') 

def home(request):
    videos = Video.objects.all()
    return render(request, 'home.html', {'videos': videos})

this is my addvideo templates:

        <div class="col-md-5">
            <form action="" method="POST">
                {% csrf_token %}
            <div class="card">        
                <div class="form-group m-3">
                    <label>Upload Your Video</label><br><br>
                     <input required name="video" type="file" class="form-control-file">
                </div>
                <button type="submit" class="btn btn-primary">Post</button>
            </div>
        </form>
        </div>

this is my home templates:

    <div class="container">
        {% for video in videos %}
        <div class="row justify-content-center">
            <video style="height: 500px; width: 500px;" controls src="{{video.file.url}}"> 
            </video>
        </div>
        {% endfor %}
          </div>
1 Answers

In order to submit a file with a HTML form, you need to specify how it will send the file content: you need to specify the enctype="…" [MozillaDev]. You can do this with:

<form action="" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    <div class="card">        
        <div class="form-group m-3">
            <label>Upload Your Video</label><br><br>
            <input required name="video" type="file" class="form-control-file">
        </div>
        <button type="submit" class="btn btn-primary">Post</button>
    </div>
</form>
Related