簡體   English   中英

Django 無法上傳文件

[英]Django can't upload file

我正在做一個 django 應用程序,其表單使用圖像文件上傳。 我有一個默認圖像,以防用戶不選擇圖像。 但是當我保存表單時,我的圖像沒有保存在我的文件中。 任何想法?

這是我的代碼:首先是我的views.py

class AnimalCreateView(generic.CreateView):

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

然后我的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}'

還有我的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 %}

當我保存我的文件然后檢查我的 html 或 django 管理頁面時,animal_photo 的所有行都使用默認文件...

您在哪里使用上下文中的form 而且,要上傳圖片(文件),您需要設置

{% 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM