使用django-multiupload库

时间:2018-04-19 20:22:08

标签: django multi-upload

我尝试使用以下库在我的Django项目中实现多重上传。

https://github.com/Chive/django-multiupload

精品/ models.py

class Photo(models.Model):
    store = models.ForeignKey(Store)
    photo = models.FileField(null=True, blank=True, upload_to='boutique/index/%Y/%m/%d')
    url = models.CharField(max_length=40, null=True, blank=True, verbose_name='Image URL')
    created_at = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return str(self.photo)

    def get_absolute_url(self):
        return reverse('cms:photo_edit', args=[self.pk])

CMS / forms.py

from django import forms
from boutique.models import Photo
from multiupload.fields import MultiFileField

class PhotoCreateForm(forms.ModelForm):
    class Meta:
        model = Photo
        fields = ['store']

    attachments = MultiFileField(min_num=1, max_num=3, max_file_size=1024*1024*5)

CMS / views.py

class PhotoCreateView(FormView):
    model=Photo
    template_name='cms/photo_new.html'
    form_class = PhotoCreateForm
    success_url=reverse_lazy('cms:photo')
    queryset = Photo.objects.all()

    def form_valid(self, form):
        for each in form.cleaned_data['attachments']:
            Attachment.objects.create(file=each)
        return super(PhotoCreateView, self).form_valid(form)

CMS / photo_new.html

{% extends 'cms/base.html' %}
{% load staticfiles %}

{% block page-header %}Add Photo{% endblock %}

{% block content %}
  <form action="" method="post">
    {% csrf_token %}
    <table class="table table-hover store-form">
      {{ form.as_table }}
    </table>
    <input class="btn btn-success btn-block" type="submit" name="" value="Submit">
    <br>
  </form>
{% endblock %}

仅供参考,我没有使用Django默认管理员,而是我自己的自定义管理员,即名为cms的应用程序。我还在名为boutique的应用中使用模型。 当我上传照片时,没有任何反应,页面甚至没有移动到成功网址。提交文件后,文件输入字段只显示"Thie field is required",并且我没有看到数据库上的任何上传。 我的代码有什么问题吗?

1 个答案:

答案 0 :(得分:1)

您的型号名称是照片,然后您尝试在附件模型中保存照片的原因!

<强> CMS / views.py

class PhotoCreateView(FormView):
model=Photo
template_name='cms/photo_new.html'
form_class = PhotoCreateForm
success_url=reverse_lazy('cms:photo')
queryset = Photo.objects.all()

def form_valid(self, form):
    for each in form.cleaned_data['attachments']:
        Photo.objects.create(photo=each)
    return super(PhotoCreateView, self).form_valid(form)

如果您要上传任何文件或图片,则需要在HTML表单中添加 enctype =“multipart / form-data”

<强> CMS / photo_new.html

{% extends 'cms/base.html' %}
{% load staticfiles %}

{% block page-header %}Add Photo{% endblock %}

{% block content %}
    <form action="" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <table class="table table-hover store-form">
          {{ form.as_table }}
        </table>
        <input class="btn btn-success btn-block" type="submit" name="" value="Submit">
        <br>
   </form>
{% endblock %}

更新这两个文件。希望它能奏效。如果没有,请告诉我。