我的上传照片表格不起作用。 Django的

时间:2019-02-26 17:24:22

标签: django forms

当我使用django admin提供的表单时,一切正常。但是,在创建自己的表单之后,django不会将数据写入模型。我的代码中缺少什么吗?

Models.py

class Offert(models.Model):
    name = models.CharField(max_length=50)
    file = models.FileField(upload_to='app/documents/')

forms.py

class OffertFormCV(forms.ModelForm):
    class Meta:
        model = Offert
        fields = ( 'name',
                   'file')

views.py

def my_views(request):
    if request.method == 'POST':
        form = OffertFormCV(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('app:thank_you_page'))

    else:
        form = OffertFormCV()

    context = {'form': form}
    return render(request, 'form_application.html', context)

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('app.urls', namespace='app'))
]  + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py

STATIC_URL = '/static/'

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'app/media')

form_application.html

                  <form method="post">
                    {% csrf_token %}
                    {{ form|crispy }}
                    <button type="submit" class="btn btn-primary">Send</button>
                  </form>

发送表格后,没有任何反应。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

您需要在表单中添加enctype="multipart/form-data"才能上传文件:

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form|crispy }}
    <button type="submit" class="btn btn-primary">Send</button>
</form>