想为用户上传多张图片,只允许我上传一张

时间:2018-05-08 07:40:02

标签: python django django-models django-forms django-views

我希望用户能够上传多张图片,但我只能用它来上传。这是我的代码:

urls.py

from . import views
from django.urls import path


app_name = 'accounts'

urlpatterns = [
    path('login/', views.login, name='login'),
    path('logout/', views.logout, name='logout'),
    path('profile/<int:user_id>', views.profile, name='profile'),
    path('profile/<int:user_id>/upload/', views.upload_pics, name='upload_pics'),


]

这是我的观点:

def upload_pics(request, user_id):

    user_profile = get_object_or_404(User, pk=user_id)

    if request.method == "POST":

        file_list = request.FILES.getlist('files')
        for afile in file_list:

            pic = File()
            pic.user = user_profile
            pic.image = afile
            pic.save()

            return redirect("groups:index")

    else:
        render(request, 'accounts/pic_upload.html')
    return render(request, 'accounts/pic_upload.html')

最后,这是表格(pic_upload.html):

<form action="{% url 'accounts:upload_pics' user.id %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <table>
      <tr>
        <td>Select Pictures: </td><td><input name="files" type="file" size="50" accept="image/*" multiple>  </td>
        <td><button type="submit"> Upload </button> </td>
       </tr>
    </table>
</form>

这是我的模特:

from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class File(models.Model):
    image = models.FileField(upload_to='images/')
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='files')

我一直试图将这件事做好几天,但没有运气。我查看了formset,但是用于完成多个文件上传的简单方法似乎存在。关于为什么只保存1张图片的任何指导真的很感激。谢谢你

1 个答案:

答案 0 :(得分:0)

def upload_pics(request, user_id):

    user_profile = get_object_or_404(User, pk=user_id)

    if request.method == "POST":

        file_list = request.FILES.getlist('files')
        for afile in file_list:

            pic = File()
            pic.user = user_profile
            pic.image = afile
            pic.save()

            return redirect("groups:index")

    else:
        render(request, 'accounts/pic_upload.html')
    return render(request, 'accounts/pic_upload.html')

def upload_pics(request, user_id):

    user_profile = get_object_or_404(User, pk=user_id)

    if request.method == "POST":

        file_list = request.FILES.getlist('files')
        for afile in file_list:

            pic = File()
            pic.user = user_profile
            pic.image = afile
            pic.save()

        return redirect("groups:index")

    else:
        render(request, 'accounts/pic_upload.html')
    return render(request, 'accounts/pic_upload.html')

return redirect("groups:index")不应该在for阻止中,您应该在每次运行后返回,这就是为什么只保存了一个文件。