python - 上传 django 中的任意文件

标签 python django file-upload

我试图在 Django 中创建一个上传文件的函数。我第一次运行代码时,无法上传文件。所以,我试图改进我的代码以及我得到的错误。我认为这个错误很奇怪,因为我一直使用它并且从未收到错误。我将展示我的代码。

models.py

class UploadFiles(models.Model):
    File = models.ImageField(upload_to = 'Images/', default='Images/')

views.py

def upload_file(request):
    if request.method == 'POST':
        form = UploadFile(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = UploadFile()
    return render(request, 'girl/upload.html', {'form': form})

forms.py

class UploadFile(forms.Form):
    title = forms.CharField(max_length=50)
    file = forms.FileField

上传.html

{% extends 'girl/base.html' %}

{% block content %}
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Upload</button>
    </form>

    <p><a href="{% url '/' %}">Return to home</a></p>
{% endblock %}

错误:

django.urls.exceptions.NoReverseMatch: Reverse for '/' not found. '/' is not a valid view function or pattern name. 

urls.py

url(r'^cat/upload/$', views.upload_file, name='uploads')

如有任何帮助,我们将不胜感激。

最佳答案

这是错误所在的行

    <p><a href="{% url '/' %}">Return to home</a></p>

更改为

    <p><a href="{% url 'name of the route' %}">Return to home</a></p>

并在您的表格中

   class UploadFile(forms.ModelForm)
        class Meta:
               model=UploadFiles
               fields ='__all__'

关于python - 上传 django 中的任意文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45231793/

相关文章:

python - 我如何像在 Illustrator 中一样在 python 中格式化文本?

python - 在matplotlib basemap 投影上绘制椭圆-如何扩展 basemap 类

java - 在 Tomcat 嵌入服务器上上传并获取图像(Heroku Deploy)Spring MVC

python - 具有动态路径的Django自定义图片上传字段

python - 如何在 django 中捕获 A 'UNIQUE constraint failed' 404

python - 在 Django 应用程序中找不到静态目录

python - 使用django上传文件

python - MultiValueDictKeyError/request.POST

c# - 上传前验证文件大小 - IE8+

python - 在 Python 代码中使用 Git 命令