我正在尝试允许每个用户将多张图片上传到一篇博文。我一直试图找出最好的方法来做几天。这样做的最佳做法是什么?
根据我的阅读,我应该从博客文章模型中创建一个单独的图像模型并使用外键。是对的吗? 然后是如何允许他们同时上传多张图片的问题。我是否正确地假设我应该使用像drop zone这样的东西?
欢迎任何有关存储照片的最佳做法的建议。我看过亚马逊s3和cloudinary。我想创建一些可扩展的东西。
非常感谢任何帮助!
答案 0 :(得分:34)
你只需要两个型号。一个用于邮政,另一个用于图像。您的图像模型将具有Post模型的外键:
from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
class Post(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=128)
body = models.CharField(max_length=400)
def get_image_filename(instance, filename):
title = instance.post.title
slug = slugify(title)
return "post_images/%s-%s" % (slug, filename)
class Images(models.Model):
post = models.ForeignKey(Post, default=None)
image = models.ImageField(upload_to=get_image_filename,
verbose_name='Image')
您需要为每个模型创建一个表单,但它们将彼此相关,例如当用户填写表单时,他必须完成图像表单以便成功发布帖子,以及我们将在视图中执行此操作,但是现在您的表单看起来像这样
from django import forms
from .models import Post, Images
class PostForm(forms.ModelForm):
title = forms.CharField(max_length=128)
body = forms.CharField(max_length=245, label="Item Description.")
class Meta:
model = Post
fields = ('title', 'body', )
class ImageForm(forms.ModelForm):
image = forms.ImageField(label='Image')
class Meta:
model = Images
fields = ('image', )
现在这是所有内容中最重要的部分,即视图,因为这是将多个图像上传到单个魔术的地方。为了让我们能够一次上传多个图像,我们需要多个图像字段吗?这就是你爱上Django formsets的地方。我们将使用django formsets来实现这一点,你可以在Django文档中阅读有关formsets的内容,我已经链接了:)但是这里你的视图应该是这样的:
*非常重要的进口
from django.shortcuts import render
from django.forms import modelformset_factory
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import HttpResponseRedirect
from .forms import ImageForm, PostForm
@login_required
def post(request):
ImageFormSet = modelformset_factory(Images,
form=ImageForm, extra=3)
#'extra' means the number of photos that you can upload ^
if request.method == 'POST':
postForm = PostForm(request.POST)
formset = ImageFormSet(request.POST, request.FILES,
queryset=Images.objects.none())
if postForm.is_valid() and formset.is_valid():
post_form = postForm.save(commit=False)
post_form.user = request.user
post_form.save()
for form in formset.cleaned_data:
#this helps to not crash if the user
#do not upload all the photos
if form:
image = form['image']
photo = Images(post=post_form, image=image)
photo.save()
messages.success(request,
"Yeeew, check it out on the home page!")
return HttpResponseRedirect("/")
else:
print(postForm.errors, formset.errors)
else:
postForm = PostForm()
formset = ImageFormSet(queryset=Images.objects.none())
return render(request, 'index.html',
{'postForm': postForm, 'formset': formset})
在视图中我们得到了两个表单,如果表单有效,视图将检查两个表单。以这种方式,用户必须填写表格并上传所有图像,在这种情况下为3 extra=3
。只有这样才能成功创建帖子。
您的模板应如下所示:
<form id="post_form" method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
{% for hidden in postForm.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in postForm %}
{{ field }} <br />
{% endfor %}
{{ formset.management_form }}
{% for form in formset %}
{{ form }}
{% endfor %}
<input type="submit" name="submit" value="Submit" />
</form>
答案 1 :(得分:5)
分步解决方案 =>甚至,我也陷入困境。所以这就是我成功所做的。
projects.locations.clusters
,在下面的代码中实现,我实现了
这是我的笔记和图像模型-(或see full code)
Finally
这是我的表单(Link of doc. on multiple upload)-(或see full code)
class Note(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
title = models.CharField(max_length=30)
text = models.TextField(null=True,blank=True)
created_date = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
class Images(models.Model):
note = models.ForeignKey(Note,on_delete=models.CASCADE)
image = models.ImageField(upload_to=user_directory_path,null=True,blank=True)
这是我的查看文件-(或see full code)
class NoteForm(forms.ModelForm):
class Meta:
model = Note
fields = ['title','text'] #make sure to mention field here, if nothing is mentioned then all will be required.
class NoteFullForm(NoteForm): #extending form
images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
class Meta(NoteForm.Meta):
fields = NoteForm.Meta.fields + ['images',]
然后,最终我的HTML文件(be sure to bind files as said in docs)-(或see full code)
def addNoteView(request):
if request.method == "POST":
#images will be in request.FILES
form = NoteFullForm(request.POST or None, request.FILES or None)
files = request.FILES.getlist('images')
if form.is_valid():
user = request.user
title = form.cleaned_data['title']
text = form.cleaned_data['text']
note_obj = Note.objects.create(user=user,title=title,text=text) #create will create as well as save too in db.
for f in files:
Images.objects.create(note=note_obj,image=f)
else:
print("Form invalid")
答案 2 :(得分:1)
我有类似的问题。在我的模型中,文章必须具有缩略图(图像),然后我为可选图像设置了另外五个字段。当应用安全过滤器后,由于不再是HTML,图像源将无法呈现,这是一个问题,
<img src="{{article.image1.url}}" class="some class">
不起作用。我使用的一个临时解决方案是根据文章标题为图像命名。如果我在写“ django过滤器”,我将其他图像命名为djangofiltersimage1.png或djangofiltersimage2.png,这将有所帮助,因为在我的模型中,每篇文章都有一个唯一的标题。然后,我将图像源更改为:
<img src="/media/djangofiltersimage1.png" class="some class">
唯一的问题是图像的严格命名。您可以通过为Blog Images创建模型来上传更多图片。同时,我仍在寻找其他解决方案。 您可以查看我的博客here
答案 3 :(得分:0)
getlist 名称和 html 输入名称字段应该相同
用于models.py
class studentImage(models.Model):
image = models.ImageField(upload_to='media/')
def __str__(self):
return self.image
对于 views.py
def studentImageView(request):
if request.method == "POST":
images = request.FILES.getlist('images')
for image in images:
photo = studentImage.objects.create(image=image,)
photo.save()
return render(request, 'image.html')
用于模板
<form method="post" enctype="multipart/form-data" >
{% csrf_token %}
<input required name="images" type="file" multiple >
<button class="btn btn-primary" type="submit">Upload</button>
</form>
答案 4 :(得分:-1)
答案很简单。不需要太多代码。
HTML文件
<input type="file" name = "files" multiple />
VIEWS.PY
files = request.FILES.getlist('files')
for f in files:
a = Image(image=f)
a.save()