简体   繁体   English

Django 无法上传文件

[英]Django can't upload file

I'm doing a django app with a form using image file upload.我正在做一个 django 应用程序,其表单使用图像文件上传。 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这是我的代码:首先是我的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然后我的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:还有我的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...当我保存我的文件然后检查我的 html 或 django 管理页面时,animal_photo 的所有行都使用默认文件...

Where are you using form from context?您在哪里使用上下文中的form 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 https://docs.djangoproject.com/en/3.1/ref/forms/api/#testing-for-multipart-forms

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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