【问题标题】:Django handle photo uploadDjango处理照片上传
【发布时间】:2017-11-06 13:20:04
【问题描述】:

我的模特有照片附件。

class Forum_message(models.Model):
    text = models.TextField()
    photo = models.ImageField(upload_to= 'forum_attachments')

我有我的表单(我更喜欢用纯 html 编写表单,所以我可以完全访问修改它们)

<form action="/forum_new" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input id="img_msg" type="file">
    <textarea name="new_msg"></textarea>
    <input type="submit" value="Submit"/>
</form>

我在函数中写什么 在views.py 中def forum_new(request): 处理文件上传并将新论坛消息保存到数据库?

【问题讨论】:

  • 您是否尝试过寻找解决方案?有很多资源都在讨论如何在 Django 中处理表单提交。

标签: python django python-3.x


【解决方案1】:

views.py 中,您可以使用 django 网站上建议的内容 (https://docs.djangoproject.com/en/1.11/topics/http/file-uploads/) 如果图片不是很大,可以直接如下处理:

def forum_new(request):
    if request.method == 'POST':
        form = your_form_here(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('/bar.html/')
    else:
        form = your_form_here()
    return render(request, 'url.html', {'form': form})

该文件应保存在 forum_attachments

文件夹中的媒体文件中

【讨论】:

    【解决方案2】:

    我需要这样的东西:

    def forum_new(request):
        msg = Forum_message()
        msg.user = request.user
        if 'image' in request.FILES:
            msg.photo = request.FILES['image']
    
        msg.text = request.GET.get('text')
        msg.save()
    

    【讨论】:

      猜你喜欢
      • 2015-03-11
      • 2011-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      • 2016-07-30
      • 2012-04-27
      • 2010-09-09
      相关资源
      最近更新 更多