我一直在尝试将一些用户上传的个人资料图片添加到我的网站。 当我从管理员执行此操作时,它正常工作,显示图像并且所有引擎似乎都正常工作(图像转到正确的上传位置等等)。问题是当我尝试从我的观点做同样的事情时。
我注意到 print(“upload_location”)仅在我从管理员处执行时才会出现。奇怪的是,我的个人资料模型中的所有其他字段都正常工作(如名称“foo”更新为“foobar”),不仅在管理员中,而且在视图中。 问题仅出在ImageField上。
我相信它可能与我正在处理form.is_valid()的方式有关,但我一直在玩那个而且没有任何改变(我知道它在某种程度上有效,因为HttpResponseRedirect是工作
有什么想法吗?
views.py
un1 <- unique(df2$group)
cbind(group = rep(paste(un1[-length(un1)], un1[-1], sep="-"), each = 4),
head(df2,-4)[-3]- tail(df2,-4)[-3])
# group a b
#1 1-2 -13 4
#2 1-2 -13 1
#3 1-2 -13 3
#4 1-2 -15 2
#5 2-3 -15 -10
#6 2-3 -17 -11
#7 2-3 -20 -17
#8 2-3 -23 -37
#9 3-4 -28 -24
#10 3-4 -33 -50
#11 3-4 -37 14
#12 3-4 -38 -11
forms.py
...
@login_required
def profile_update(request, username=None):
obj = get_object_or_404(User, username=username)
user = obj.profile
form = ProfileForm(request.POST or None, instance = user)
context = {
"form": form
}
if form.is_valid():
form.save()
return HttpResponseRedirect('/profiles/{username}'.format(username=user.user))
template = 'profile_update.html'
return render(request, template, context)
models.py
from django import forms
from .models import Profile
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = [
"profilePic",
"nome",
...
]
def profile(self, request, user):
print('printing forms')
user.uf = self.cleaned_data['uf']
user.cidade = self.cleaned_data['cidade']
user.telefone = self.cleaned_data['telefone']
user.save()
template.html
...
User = settings.AUTH_USER_MODEL # 'auth.User'
def upload_location(instance, filename):
print("upload_location")
return "%s/%s" %(instance.user, filename)
class Profile(models.Model):
user = models.OneToOneField(User)
id = models.AutoField(primary_key=True)
width = models.IntegerField(default=0, null=True, blank=True,)
height = models.IntegerField(default=0, null=True, blank=True,)
profilePic = models.ImageField(
upload_to = upload_location,
blank=True, null=True,
verbose_name = 'Foto de Perfil',
width_field="width",
height_field="height",
)
...
答案 0 :(得分:1)
您需要将FILES添加到表单中。
form = ProfileForm(request.POST or None, request.FILES or None, instance = user)
文档:https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/