我正在尝试使用以下库在我的 Django 项目中实现多上传。
https://github.com/Chive/django-multiupload
精品店/型号.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])
内容管理系统/表格.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)
内容管理系统/视图.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"
,我在数据库上看不到任何上传。我的代码有问题吗?
您的模型名称是照片,那么为什么您尝试在附件模型保存照片!
内容管理系统/视图.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 %}
更新这两个文件。希望它能起作用。如果没有,请告诉我。