在usersApp下配置urls
from django.conf.urls import url from .views import UserInfoView, UploadImageView, UpdatePwdView, UserinfoView urlpatterns = [ # 用户个人资料页 url(r'^info/$', UserInfoView.as_view(), name='user_info'), # 用户修改头像 url(r'^image/up_load$', UploadImageView.as_view(), name='up_load'), # 用户修改密码 url(r'^update/pwd/$', UpdatePwdView.as_view(), name='update_pwd'), # 用户修改资料 url(r'^update/user_info/$', UserinfoView.as_view(), name='user_info'), ]
编写forms
class UserInfoForm(forms.ModelForm): class Meta: model = UserProfile fields = ['nick_name', 'profession', 'gender', 'address', 'mobile']
编写视图函数
class UserinfoView(LoginRequiredMixin, View): """ 用户个人信息 """ def get(self, request): return render(request, 'usercenter-info.html', {}) def post(self, request): user_info_form = UserInfoForm(request.POST, instance=request.user) if user_info_form.is_valid(): user_info_form.save() return render(request, 'usercenter-info.html', { 'msg': '修改成功' }) else: return render(request, 'usercenter-info.html', { 'user_info_form': user_info_form })
修改头像
编写forms
class UploadImageForm(forms.ModelForm): """ 处理用户上传头像 """ class Meta: model = UserProfile fields = ['image']
编写视图函数
class UploadImageView(LoginRequiredMixin, View): """ 用户修改头像 """ def post(self, request): image_form = UploadImageForm(request.POST, request.FILES, instance=request.user) if image_form.is_valid(): image_form.save() return HttpResponse('{"status":"success"}', content_type='application/json') else: return HttpResponse('{"status":"fail"}', content_type='application/json')
修改密码
编写form
class ModifyPwdForm(forms.Form): """ 用户修改密码 """ password1 = forms.CharField(required=True, min_length=5) password2 = forms.CharField(required=True, min_length=5)
视图函数
class UpdatePwdView(LoginRequiredMixin, View): """ 用户修改密码 """ def post(self, request): modify_form = ModifyPwdForm(request.POST) if modify_form.is_valid(): pwd1 = request.POST.get('password1', '') pwd2 = request.POST.get('password2', '') if pwd1 != pwd2: return HttpResponse('{"status":"fail", "msg": "密码不一致"}', content_type='application/json') user = request.user user.password = make_password(pwd2) user.save() return HttpResponse('{"status":"success"}', content_type='application/json') else: return HttpResponse(json.dumps(modify_form.errors), content_type='application/json')