允许用户上传个人资料图片,但1)表单无效2)未正确保存

时间:2018-05-07 10:44:10

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

我正在尝试允许用户上传个人资料照片。我这样做是通过创建一个File模型,并添加一个引用用户的外键。用户可以上传许多文件。这是模型:

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

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

接下来,上传的表单如下所示:

from django import forms
from .models import File


class FileForm(forms.ModelForm):

    class Meta:
        model=File
        fields=('files',)
        widgets={'files':forms.FileInput(attrs={'id':'files','required':True,'multiple':True})}

最后,视图'上传图片'如下:

def upload_pics(request, user_id):
    if request.method == "POST":
        form = FileForm(request.POST)
        if form.is_valid():
            pics = form.save(commit=False)
            pics.user = request.user
            pics.files = request.Files['files']
            pics.save()
            return redirect(request, 'accounts:profile', user_id)

    else:
        form = FileForm()
        render(request, 'accounts/account_form.html', {'form':form})
    return render(request, 'accounts/account_form.html', {'form':form})

我遇到了两个问题:

  1. 表格无效,即使我点击了几张图片
  2. 图片无法正确保存

1 个答案:

答案 0 :(得分:0)

您需要将文件传递给表单。

form = FileForm(request.POST, request.FILES)

此外,您不会显示模板,但请确保使用enctype="multipart/form-data"