0

I'm trying to upload a file on a model in Django framework.

class banner(models.Model):
    #id is made by Django
    name = models.CharField(max_length=255)
    created_by = models.CharField(max_length=255)
    company = models.CharField(max_length=255)
    register_date = models.DateField(auto_now_add=True)
    file = models.FileField(null=True, blank=True)
    file_name = models.CharField(max_length=255)

this is the model:

class BannerForm(forms.Form):
    name=forms.CharField(max_length=255)
    created_by=forms.CharField(max_length=255)
    company=forms.CharField(max_length=255)
    data_type=forms.CharField(max_length=255)
    register_date=forms.DateField()
    file=forms.FileField()
    file_name=forms.CharField(max_length=255)

this is the form:

def add_form(request):
    form=BannerForm()
    last=models.banner.objects.all().last()

    if request.method == "POST":
        form = forms.BannerForm(request.POST, request.FILES or None)
        if form.is_valid():
            form.cleaned_data['created_by']
            new_banner=models.banner()
            new_banner.id=last.id+1
            new_banner.name=form.cleaned_data['name']
            new_banner.register_date=form.cleaned_data['register_date']
            new_banner.company=form.cleaned_data['company']
            new_banner.file=form.cleaned_data['file']
            new_banner.file_name=new_banner.file.name
            new_banner.created_by=form.cleaned_data['created_by']
            new_banner.save()

    return render(request, "add_banner.html",{"form":form})

this is the view.

Now every time I try to add a banner, I browse the file, but after I click "submit", it is that the file must be chosen, like it doesn't recognize what I browse to the form button.

3
  • I forgot to mention: it says The submitted file is empty. Commented Aug 17, 2017 at 5:38
  • Do you have the enctype set in your form? Commented Aug 17, 2017 at 5:38
  • I have the enctype only in the add_banner.html template enctype="multipart/form-data" Commented Aug 17, 2017 at 5:41

3 Answers 3

3

well you need to specify the upload path in your models

file = models.FileField(null=True, blank=True,upload_to='files')

and make sure you have MEDIA_ROOT and MEDIA_URL defined in your settings.py

in your form

<form method="post" action="" enctype="multipart/form-data">
    {% csrf_token %}
    ...
</form>
Sign up to request clarification or add additional context in comments.

5 Comments

STATIC_ROOT=os.path.join(os.path.dirname(BASE_DIR), "static_cdn") MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn) I have those and i modify but still nothing the same thing
try the edited ans, and after adding the upload path to model, dont forget to make migrations and migrate
I was trying to upload an empty file, my dumb mistake, but question, when i try to upload the same file to a table where i have already have a row with that file it will overwritten?
if you are editing then it will overrite the old one, but the file will stay in the media folder
k, so sorry for bothering all of you with my lack of knowledge, it is the first time when i work with django. So now they store all my uploads in the main file of the project. Should i change file=models.FileField(null=True, blank=True, upload_to='files') to file=models.FileField(null=True, blank=True, upload_to='files/Media') if i wan the files to be fount the folder called Media?
1

You need to include enctype="multipart/form-data" in your form definition.

<form method="post" action="your action" enctype="multipart/form-data">
    {% csrf_token %}
    ...
</form>

1 Comment

<form action="" method= "POST", enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="button", value="Insert"> </form>
0

Try this something like this :

Models.py :

class banner(models.Model):
#id is made by Django
name = models.CharField(max_length=255)
created_by = models.CharField(max_length=255)
company = models.CharField(max_length=255)
register_date = models.DateField(auto_now_add=True)
file = models.FileField(upload_to='files/', null=True, blank=True)
file_name = models.CharField(max_length=255)

forms.py :

class BannerForm(forms.ModelForm):
    class Meta:
        model = banner #Or Banner ??
        fields = ('name', 'created_by', 'company', 'file', 'file_name' )

views.py :

from myapp.forms import BannerForm

if request.method == "POST":
    form = BannerForm(request.POST, request.FILES)
    if form.is_valid():
        entry = form.save(commit=False)
        entry.name = request.POST['name']
        entry.created_by = request.POST['created_by']
        entry.company = request.POST['company']
        entry.file_name = request.POST['file_name']
        form.save()

    else:
      form = BannerForm()

return render(request, "add_banner.html",locals())

And like already said, don't forget :

<form method="POST" action="" enctype="multipart/form-data">
    {% csrf_token %}
    {{form.name}}
    {{form.created_by}}
    {{form.company}}
    {{form.file_name}}
    {{form.file}}
    <input type="submit">
</form>

You don't have to specify these things :

new_banner.file=form.cleaned_data['file']

new_banner.register_date=form.cleaned_data['register_date'] -> useless because in your model you set auto_now_add=True, so you don't need te make a field in your HTML form.

Note : if your field created_by = models.CharField(max_length=255) is to put an existing user, so you should make a foreign key field like :

from django.contrib.auth.models import User
created_by = models.ForeignKey(User, verbose_name="Created by")

5 Comments

k, so sorry for bothering all of you with my lack of knowledge, it is the first time when i work with django. So now they store all my uploads in the main file of the project. Should i change file=models.FileField(null=True, blank=True, upload_to='files') to file=models.FileField(null=True, blank=True, upload_to='files/Media') if i wan the files to be fount the folder called Media?
You can try. Django will automatically create a folder if it doesn't exists.
For example you can try also : upload_to='media/banner/whatever/'')
And the media folder will be created in the Project folder?
I think yes. On the root of your project folder, you will find a new folder called media or whatever you called it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.