我跟随Add image/avatar to users in django提示,让用户上传他们的个人资料照片,并在用户登录时显示用户的个人资料照片。
Adding profile picture to django user
但出于某种原因,它出现了一个错误:“禁止创建没有'fields'属性或'exclude'属性的ModelForm;表单UserProfileForm需要更新。”
无论如何我可以直接修改django.contrib.auth.models的用户模型,这样我只能添加个人资料图片并将其显示在index.html上吗?
没有关于此个人资料图片系统的大量信息。
自从我开始学习django和python以来,这只是几天。
任何人都可以用例子来解释,我怎么能做到这一点?
感谢。
(这是实现上述提示的forms.py)
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, get_user_model, login, logout
class UserSignupForm(forms.ModelForm):
email = forms.EmailField(label='Confirm Email')
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = [
'username',
'email',
'password'
]
def clean_email(self):
email = self.cleaned_data.get('email')
email_qs = User.objects.filter(email=email)
if email_qs.exists():
raise forms.ValidationError("This email has already been registered")
return email
from django.core.files.images import get_image_dimensions
from .models import UserProfile
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
def clean_avatar(self):
avatar = self.cleaned_data['avatar']
try:
w, h = get_image_dimensions(avatar)
#validate dimensions
max_width = max_height = 100
if w > max_width or h > max_height:
raise forms.ValidationError(
u'Please use an image that is '
'%s x %s pixels or smaller.' % (max_width, max_height))
#validate content type
main, sub = avatar.content_type.split('/')
if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']):
raise forms.ValidationError(u'Please use a JPEG, '
'GIF or PNG image.')
#validate file size
if len(avatar) > (20 * 1024):
raise forms.ValidationError(
u'Avatar file size may not exceed 20k.')
except AttributeError:
"""
Handles case when we are updating the user profile
and do not supply a new avatar
"""
pass
return avatar
答案 0 :(得分:4)
实施例: models.py:
class YouModel(models.Model):
.............You field ................
user_avatar = models.ImageField((upload_to="You/media/uploads", blank=True) # You need to configure media in settings.py
........... You fields ..............
class YouModelForm(ModelForm)
class Meta:
model = YouModel
fields = ['user_avatar']
views.py:
来自.models导入YouModel,YouModelForm
def youfunc(request):
youtemplate = YouModelForm()
if request.method == POST:
youform = YouModelForm(request.POST, request.FILES)
if youform.is_valid():
youform.save()
return HttpResponseRedirect('http://www.You.url') # or other
youquery = .objects.order_by('user_avatar').last()
return render(request, "YouProject/YouHtml.html", {'youtemplate': youtemplate, 'youquery': youquery})
我累了写。您需要配置django并从用户写入第一个文件上传。您可以访问我的网站并查看和决定 - 这是您想要的吗?我的网站http://www.webmamoffice.org/en并转到UperVote或http://www.webmamoffice.org/en/upervote