ImageField无法在表单中上传,在管理面板中上传得很好

时间:2016-02-11 18:35:13

标签: python django

我有一个注册表单,用户可以上传他们个人资料的头像,但我无法让它工作。我已正确设置媒体:

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

我的个人资料模型中有一个ImageField:

class UserProfile(models.Model):

    def is_square_png(self):
        if not self.name.endswith('.png'):
            raise ValidationError("You may only upload .png files!")
        else:
            w, h = get_image_dimensions(self)
            if not h == w:
                raise ValidationError("This picture is not square! Your picture must be equally wide as its height.")
            else:
                if not (h + w) >= 1000:
                    raise ValidationError("This picture is too small! The minimum dimensions are 500 by 500 pixels.")
                else:
                    if not (h + w) < 2000:
                        raise ValidationError("This picture is too big! The maximum dimensions are 1000 by 1000 pixels.")
        return self

    def generate_user_folder_avatar(instance, filename):
        return "users/%s/%s.png" % (instance.user, 'avatar')

    ...
    avatar = models.ImageField(upload_to=generate_user_folder_avatar,storage=OverwriteStorage(),validators=[is_square_png],blank=True)

    ...

在我的ModelForm中,我也包括它:

class  UserProfileForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(UserProfileForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'field-input-element'

    class Meta:
        model = UserProfile
        fields = ('display_name', 'avatar', 'birthday', 'usertype', 'daw', 'usergenre', 'gender')
        widgets = {
            'birthday': AdminDateWidget(),
        }

以及我的观点:

def RegisterView(request):

    registration_success = False

    if request.method == 'POST':
        user_form = UserForm(request.POST, prefix='uf')
        profile_form = UserProfileForm(request.POST, request.FILES, prefix='upf')

        if user_form.is_valid() and profile_form.is_valid():
            user_atr = user_form.save()
            user_atr.set_password(user_atr.password)
            user_atr.save()

            profile = profile_form.save(commit=False)
            profile.user = user_atr

            profile.avatar = request.FILES.get('avatar')

            profile.save()
            registration_success = True

            user_atr = authenticate(username=user_form.cleaned_data['username'],
                        password=user_form.cleaned_data['password'],
                        )
            login(request, user_atr)
            return HttpResponseRedirect("/")

        else:
            print (user_form.errors, profile_form.errors)

    else:
        user_form = UserForm(prefix='uf')
        profile_form = UserProfileForm(prefix='upf')

    return render(request, 'profile/register.html', {'profile_form': profile_form, 'user_form': user_form})

无论我做什么,当我提交表格时,就好像该字段被忽略了一样。 django不会将url添加到字段中,也不会实际上传文件。

我没有错误,没有错!它只是不上传,也不会将URL添加到模型实例。

1 个答案:

答案 0 :(得分:2)

图片已由ModelForm保存,因此您只需删除该行:

profile.avatar = request.FILES.get('avatar')

,图片将保存在profile.save()