Python 在Django上上传多个img到1个帖子?你怎么知道的?
我想上传多个img到Django上的一个帖子。我在models.py中使用了ImageField。但它只是可以上传一张图片到一篇文章。我如何用Django或其他方法将多个图像上传到一篇文章中来解决这个问题。非常感谢。我想你是在问内联模型,Python 在Django上上传多个img到1个帖子?你怎么知道的?,python,django,Python,Django,我想上传多个img到Django上的一个帖子。我在models.py中使用了ImageField。但它只是可以上传一张图片到一篇文章。我如何用Django或其他方法将多个图像上传到一篇文章中来解决这个问题。非常感谢。我想你是在问内联模型, 对不起,刚才的回答 我认为这是最好的办法 models.py from django.db import models from django.template.defaultfilters import slugify class Post(models.
对不起,刚才的回答 我认为这是最好的办法 models.py
from django.db import models
from django.template.defaultfilters import slugify
class Post(models.Model):
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 Files(models.Model):
post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE)
files = models.FileField(upload_to=get_image_filename, verbose_name='File')
我没有为文件创建表单,因为我们将在模板中手动编写表单
forms.py
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', )
views.py
from django.shortcuts import render
from django.contrib import messages
from django.http import HttpResponseRedirect
from .forms import PostForm
from .models import Post, Files
def post(request):
if request.method == 'POST':
print(request.FILES.getlist('files'))
postForm = PostForm(request.POST)
if postForm.is_valid():
post_form = postForm.save(commit=False)
post_form.save()
if request.FILES.getlist('files'):
for file in request.FILES.getlist('files'):
obj = Files(post=post_form, files=file)
obj.save()
messages.success(request, "Yeeew, check it out on the home page!")
return HttpResponseRedirect("/")
else:
print(postForm.errors)
else:
postForm = PostForm()
return render(request, 'index.html', {'postForm' : postForm})
index.html
<html>
<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 %}
<input type="file" id="files" name="files" multiple><br>
<input type="submit" name="submit" value="Submit" />
</form>
</html>
{%csrf_令牌%}
{%用于postForm.hidden_字段%}
{{隐藏}}
{%endfor%}
{postForm%中字段的%s}
{{field}}
{%endfor%}
我们为文件模型创建了这样一个字段,但我们没有形成该字段
<input type="file" id="files" name="files" multiple><br>
您可以选择多个文件并通过按住CTRL或Shift键上载它们。欢迎使用堆栈溢出。不幸的是,你的问题不是很清楚。您是否在问如何在ORM中建模一对多关系?或者在用户的浏览器中提供一些特定的用户界面?嗨,克里斯,我的意思是,我想用django创建表单,我可以上传多个img。我不知道怎么做。谢谢你的回复