上传django中的任何文件

时间:2017-07-21 07:38:05

标签: 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

upload.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')

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:2)

这是错误行

    <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__'