0

我正在尝试使用下面的库在我的 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. 当我上传照片时,没有任何反应,页面甚至没有移动到成功 url。提交文件后,文件输入字段只是说"Thie field is required",我在数据库上看不到任何上传。我的代码有问题吗?

4

1 回答 1

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)

如果要上传任何文件或图像,则需要将enctype="multipart/form-data"添加到 HTML 表单中。

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

更新这两个文件。希望它会起作用。如果没有,请告诉我。

于 2018-04-20T02:22:44.943 回答