简体   繁体   中英

Django can't upload file

I'm doing a django app with a form using image file upload. I have a default image in case user doesnt choose an image. But when I save the form, my image isn't saved in my files. Any idea?

Here's my code: First my views.py

class AnimalCreateView(generic.CreateView):

model = Animal
form_class = AnimalForm
template_name = 'myApp/animal_create.html'
success_url = reverse_lazy('animal:index')

Then my models.py

class Animal(models.Model):

name= models.CharField()

animal_photo= models.ImageField(upload_to="images/",default="images/noPhoto.svg", null=False, blank=True) 

def __str__(self):
    return f'{self.name}'

And my animal_create html:

{% extends 'base.html' %}
{% load static %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-lg-8 offset-lg-2">
           
            <h4>My anmials</h4>

            <table class="table">
                <thead>
                    <tr>
                        <th>&nbsp;</th>
                        <th>Name</th>
                        <th>Photo</th>
                        
                    </tr>
                </thead>
                <tbody>
                    {% for animal in animal_list%}
                    <tr>
                        
                        <td>{{animal.name}}</td>
                 
                        <p> {{ animal.photo.url }} </p> #check url file
                        <td class="picture-thumb">
                            
                            {% if animal.photo.url %}
                            <img src="{{ animal.photo.url}}"" />
                            {% else %}
                            <img src="{% static 'images/noPhoto.svg' %}" />
                            {% endif %}
                        
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
                
            </table>
        </div>
    </div>
</div>
{% endblock content %}

When I save my file and then check my html or django admin page, all the rows of animal_photo are using the default file...

Where are you using form from context? And also, to upload an images(files) you need to set

{% if form.is_multipart %}
    <form enctype="multipart/form-data" method="post" action="/foo/">
{% else %}
    <form method="post" action="/foo/">
{% endif %}

https://docs.djangoproject.com/en/3.1/ref/forms/api/#testing-for-multipart-forms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM