def test_ProfileForm(self): params = dict(username='******', email="*****@*****.**") form = ProfileForm(params) self.assertTrue(form.is_valid()) params2 = dict(username='******', email='*****@*****.**') form = ProfileForm(params2) self.assertFalse(form.is_valid())
def editprofile(request): if request.method == "POST": profile_form = ProfileForm(request.POST, instance=request.user.profile) user_get_ms_info = User.objects.get(username=request.user.username) user_merchant_only_form = UserMerchantOnlyForm(request.POST, instance=request.user, ms_kw=user_get_ms_info) if profile_form.is_valid() and user_merchant_only_form.is_valid(): user_merchant_only_form.save() profile_form.save() return redirect('user:browseownprofile') else: context = { 'form': profile_form, 'userform': user_merchant_only_form, 'user': request.user } return render(request, 'user/editprofile.html', context) else: profile_form = ProfileForm(instance=request.user.profile) user_merchant_only_form = UserMerchantOnlyForm(instance=request.user) context = { 'form': profile_form, 'userform': user_merchant_only_form, 'user': request.user } return render(request, 'user/editprofile.html', context)
def post(self, request): user = User.objects.get(id=request.user.id) data = request.POST.copy() # ensures that the email field is not updated data["email"] = user.email profile_form = ProfileForm(data, files=request.FILES, instance=user) if profile_form.is_valid(): profile_form.save() messages.success( request, SUCCESS_MESSAGES["operation_successful"].format("save")) return redirect("profile_url") # this ensures that whenever error(s) are displayed in the template # the bank form still retains its form displayed # else the form shows none because it can access a bank form from the context # this issue occurs because we a rerendering the page, # if we redirect to the page, then we don't need to bother about this issue, # but then again, we would loose the form errors # perhaps we can make use of messages, ie putting the errors in messages will # help us avoid this # but we currently want to show the errors withing the template input itself context = self._set_profile_context(profile_form, request, user) return render(request, template_name="dashboard/profile/profile.html", context=context)
def register(request): user_form = UserForm(request.POST or None) profile_form = ProfileForm(request.POST or None, request.FILES or None) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) try: validate_password(user_form.cleaned_data.get('password'), user) except ValidationError as e: user_form.add_error('password', e) return render(request, 'user/registration.html', context={ 'user_form': user_form, 'profile_form': profile_form, }) user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user profile.save() return render(request, 'user/registration.html', context={ 'user_form': user_form, 'profile_form': profile_form })
def CreateProfile(request): if request.method == 'POST': user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user profile.save() messages.add_message(request, messages.INFO, "Vous êtes désormais inscrit.") return redirect('/') else: user_form = UserForm() profile_form = ProfileForm() return render(request, 'registration/create.html', { 'user_form': user_form, 'profile_form': profile_form })
def edit_profile(request): #Processes 2 forms.. 1 Auth user and 1 custom model (profile) profile = Profile.objects.get(id=request.user.id) if request.method == 'POST': profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile) user_form = EditProfileForm(request.POST, instance=request.user) #return render_to_response('profile/debug.html', {'profile_form': profile_form}) if profile_form.is_valid() and user_form.is_valid(): profile_form.save() user_form.save() return redirect('/') else: return render(request, 'profile/edit_profile.html', { 'user_form':user_form, 'profile_form':profile_form, 'profile':profile } ) else: profile_form = ProfileForm(instance = request.user.profile) user_form = EditProfileForm(instance = request.user) return render(request, 'profile/edit_profile.html', { 'user_form':user_form, 'profile_form':profile_form, 'profile':profile } )
def set_profile(request): # 将提交的数据放进表单,并初始化 user_form = UserForm(request.POST) user = request.user # 判断表单是否有效 if user_form.is_valid(): # __dict__ 用来修改类对象的属性值 user.__dict__.update(user_form.cleaned_data) user.save() else: # 直接抛出实例,手动添加data raise status.UserDataErr(user_form.errors) # return render_json(data=user_form.errors, code=status.UserDataErr) profile_form = ProfileForm(request.POST) # profile = user.profile if profile_form.is_valid(): # 当你通过表单获取你的模型数据,但是需要给模型里null=False字段添加一些非表单的数据,该方法会非常有用。如果你指定commit=False, # 那么save方法不会理解将表单数据存储到数据库,而是给你返回一个当前对象。这时你可以添加表单以外的额外数据,再一起存储。 # 生成一个空对象,减少跟数据库通信的次数 profile = profile_form.save(commit=False) profile.id = user.id profile.save() # 缓存更新 key = keys.PROFILE_KEY % request.user.id # 通过删除缓存达到更新目的,还有就是被动的过期 # cache.delete(key) cache.set(key, profile.to_dict()) else: raise status.ProfileDataErr(profile_form.errors) # return render_json(data=profile_form.errors, code=status.ProfileDataErr) return render_json()
def update(request): '''修改资料''' # 从request.POST 里面得到一个类字典的对象 user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) # 如果两个提交的信息都没有问题的话: if user_form.is_valid() and profile_form.is_valid(): uid = request.session['uid'] # update `user` set nickname = 'xxx' ... where id = 123; # UserForm.cleaned_data 是更新的数据, 并且需要进行拆包, 因为这个是一个字典 User.objects.filter(id=uid).update(**user_form.cleaned_data) # 先更新, 如果没有数据可供更新的话, 创建一个新的并将 default 作为默认的写进去 Profile.objects.update_or_create(id=uid, defaults=profile_form.cleaned_data) return render_json() # 如果有异常的话: else: # 错误信息是用字典来标记的 err = {} err.update(user_form.errors) err.update(profile_form.errors) # return render_json(err, stat.ProfileErr) raise stat.ProfileErr(err)
def actualizar(request): profile=request.user.profile #primera forma de traer los datos if request.method == 'POST': form =ProfileForm(request.POST, request.FILES) #se crea una instancia de profileform if form.is_valid():#se realiza una validación #print (form.cleaned_data) data=form.cleaned_data profile.website=data['website'] profile.phone = data['phone'] profile.biog = data['biog'] print(data) #profile.picture = data['picture'] profile.save() url= reverse('user:detail', kwargs={'username':request.user.username})#se usa en vez de redirect porque ella no se deja construir recibiendo argumentos creo return redirect(url)#se modifica para cuando la url recibe argumetnos else: form=ProfileForm() return render( request=request, template_name='user/edit.html', context={ 'profile': profile, 'user': request.user, 'form': form })
def set_profile(request): '''修改个人资料''' user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) # 检查 User 的数据 if not user_form.is_valid(): raise stat.UserDataErrr(user_form.errors) # 检查 Profile 的数据 if not profile_form.is_valid(): raise stat.ProfileDataErrr(profile_form.errors) user = request.user # 保存用户的数据 user.__dict__.update(user_form.cleaned_data) user.save() # 保存交友资料的数据 user.profile.__dict__.update(profile_form.cleaned_data) user.profile.save() # 修改缓存 key = keys.PROFILE_KEY % request.user.id rds.set(key, user.profile.to_dict()) return render_json()
def set_profile(request): '''修改个人资料''' user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) # 检查数据有效性 if not user_form.is_valid(): raise stat.UserFormErr(user_form.errors) if not profile_form.is_valid(): raise stat.ProfileFormErr(profile_form.errors) # 保存数据 User.objects.filter(id=request.uid).update(**user_form.cleaned_data) Profile.objects.filter(id=request.uid).update(**profile_form.cleaned_data) # 删除旧的缓存 key = keys.PROFILE_K % request.uid rds.delete(key) # 文强 + 程超 的思路 # user = User.objects.get(id=request.uid) # user.__dict__.update(user_form.cleaned_data) # user.save() return render_json()
def edit_user_info(request): msg = None msg_type = None user = request.user if request.method == 'POST': user_form = UpdateUserForm(request.POST, instance=user) profile_form = ProfileForm(request.POST, instance=user.profile) if user_form.is_valid() and profile_form.is_valid(): password_match = check_password(request.POST['password'], user.password) if password_match: user = user_form.save() profile_form.save(user) msg = 'Changes successfully saved' msg_type = 'SUCCESS' else: msg = 'Password is incorrect' msg_type = 'ERROR' else: user_form = UpdateUserForm(instance=user) profile_form = ProfileForm(instance=user.profile) context = { 'user_form': user_form, 'profile_form': profile_form, 'password_form': PasswordForm(), 'msg': msg, 'msg_type': msg_type, } return render(request, 'user/edit_user.html', context=context)
def set_profile(request): '''修改用户信息,及用户配置''' user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) # 验证 user 表单的数据 if not user_form.is_valid(): raise stat.UserFormErr(user_form.errors) # 验证 profile 表单的数据 if not profile_form.is_valid(): raise stat.ProfileFormErr(profile_form.errors) # 修改用户数据 User.objects.filter(id=request.uid).update(**user_form.cleaned_data) # 修改 profile 数据 Profile.objects.update_or_create(id=request.uid, defaults=profile_form.cleaned_data) # 更新缓存 key = keys.MODEL_K % (Profile.__name__, request.uid) rds.delete(key) return render_json()
def update_profile(request): """Update a user's profile view.""" profile = request.user.profile if request.method == 'POST': form = ProfileForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data profile.website = data['website'] profile.phone_number = data['phone_number'] profile.biography = data['biography'] profile.picture = data['picture'] profile.save() return redirect('update_profile') else: form = ProfileForm() return render( request=request, template_name='users/update_profile.html', context={ 'profile': profile, 'user': request.user, 'form': form } )
def set_profile(request): '''修改个人资料''' user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) # 检查数据有效性 if not user_form.is_valid(): raise stat.UserFormErr(user_form.errors) if not profile_form.is_valid(): raise stat.ProfileFormErr(profile_form.errors) print('-----------------') print(user_form.cleaned_data) print(request.uid) # 保存数据 User.objects.filter(id=request.uid).update(**user_form.cleaned_data) Profile.objects.filter(id=request.uid).update(**profile_form.cleaned_data) # 删除旧的缓存 key = keys.PROFILE_K % request.uid model_user_key = 'Model-User-%s'%(request.uid) model_profile_key = 'Model-Profile-%s'%(request.uid) rds.delete(key) rds.delete(model_user_key) rds.delete(model_profile_key) #方法2 # user = User.objects.get(id=request.uid) # user.__dict__.update(user_form.cleaned_data) # user.save() return render_json()
def profile(request): if request.method == 'POST': form = ProfileForm(request.POST or None) if form.is_valid(): user_id = request.session.get('user_id', None) user = UserModel.objects.filter(id=user_id).first() if user: modified_dic = { k: v for k, v in form.cleaned_data.items() if v is not None and v != '' } for key, value in modified_dic.items(): if key == 'id' or ((key == 'active' or key == 'invite') and value == False): continue else: setattr(user, key, value) user.save() return Response(status=status.HTTP_200_OK) return Response(status=status.HTTP_404_NOT_FOUND) Response(status=status.HTTP_400_BAD_REQUEST) elif request.method == 'GET': user_id = request.session.get('user_id', None) if user_id: user = UserModel.objects.filter(id=user_id).first() if user: serializer = UserModelSerializer(user) return Response(data=serializer.data, status=status.HTTP_200_OK) return Response(status=status.HTTP_404_NOT_FOUND) else: return Response(status=status.HTTP_401_UNAUTHORIZED)
def profile_update(request): user = request.user if not hasattr(user, 'userprofile'): user_profile = UserProfile() user_profile.user = user else: user_profile = user.userprofile if request.method == "POST": form = ProfileForm(request.POST) if form.is_valid(): user.first_name = form.cleaned_data['first_name'] user.last_name = form.cleaned_data['last_name'] user.save() user_profile.phone = form.cleaned_data['phone'] user_profile.zip = form.cleaned_data['zip'] user_profile.address = form.cleaned_data['address'] user_profile.save() return HttpResponseRedirect(reverse('user:profile')) else: default_data = {'first_name': user.first_name, 'last_name': user.last_name, 'phone': user_profile.phone, 'zip': user_profile.zip, 'address':user_profile.address} form = ProfileForm(default_data) return render(request, 'account/profile_update.html', {'form': form, 'user': user})
def update_profile(request): '''修改用户配置''' profile = request.user.profile form = ProfileForm(request.POST, instance=profile) if form.is_valid(): form.save() else: raise errors.ParamsError
def set_profile(request): user = request.user form = ProfileForm(data=request.POST, instance=user.profile) if form.is_valid(): form.save() return render_json() else: return render_json(data=form.errors)
def edit_profile(request): uid = request.session.get('uid') profileform = ProfileForm(request.POST) if profileform.is_valid(): profile = profileform.save(commit=False) profile.id = uid profile.save() return render_json(profile.to_dict()) else: return render_json(profileform.errors, PROFILE_ERROR)
def set_profile(request): '''''' form = ProfileForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.id = request.session['uid'] profile.save() return render_json() else: return render_json(form.errors, errors.PROFILE_ERR)
def modify_profile(request): '''修改个人资料''' form = ProfileForm(request.POST) if form.is_valid(): user = request.user user.profile.__dict__.update(form.cleaned_data) user.profile.save() return render_json(None) else: return render_json(form.errors, error.PROFILE_ERROR)
def modify_profile(request): '''修改个人资料''' form = ProfileForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.id = request.user.id profile.save() return render_json(profile.to_dict()) else: return render_json(form.errors, errors.ProfileError.code)
def set_profile(request): '''修改个人配置''' form = ProfileForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.id = request.session['uid'] profile.save() return render_json(None) else: raise errors.ProfileErr(form.errors)
def set_profile(request): '''修改个人资料''' form = ProfileForm(request.POST) # 数据检查 if form.is_valid(): profile = form.save(commit=False) # 通过Form表单创建出model对象,但并不在数据库中创建 profile.id = request.user.id # 给profile设置id profile.save() # 保存 info_log.debug('更新缓存') return render_json(profile.to_dict()) else: raise errors.ProfileErr(form.errors)
def post(self, request): # instance参数表示用model实例来初始化表单,这样就可以达到通过表单来更新数据 form = ProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() # 添加一条信息,表单验证成功就重定向到个人信息页面 messages.add_message(request, messages.SUCCESS, '个人信息更新成功!') return redirect('user:profile') else: return render(request, 'user/change_profile.html', context={'form': form})
def post(self, request): pf = get_object_or_404(UserProfile, owner=self.request.user) form1 = ProfileForm(request.POST, instance=pf, prefix='profile') uf = get_object_or_404(User, username=self.request.user) form2 = UserForm(request.POST, instance=uf, prefix='user') if form1.is_valid() and form2.is_valid(): profile = form1.save(commit=False) # profile.owner=self.request.user profile.save() form2.save() return redirect('home:all') else: ctx = {'form1': form1, 'form2': form2} return render(request, 'user/user_profile.html', ctx)
def registrationFormExtended(request): if request.method == 'POST': user_form = UserCreationFormCustom(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() profile_form.save(user) return redirect(to=settings.LOGIN_URL) else: user_form = UserCreationFormCustom() profile_form = ProfileForm() context = {'user_form': user_form, 'profile_form': profile_form} return render(request, 'user/register.html', context=context)
def avatar(request): if Profile.objects.filter(user=request.user).exists(): profile = Profile.objects.get(user_id=request.user) if request.method == 'POST': # 上传的文件保存在 request.FILES 中,通过参数传递给表单类 profile_form = ProfileForm(request.POST, request.FILES) if profile_form.is_valid() and 'avatar' in request.FILES: profile.avatar = profile_form.cleaned_data["avatar"] profile.save() return redirect('user_info') else: return HttpResponse("上传失败,请检查网络并重试。") else: return HttpResponse("请使用GET或POST请求数据")
def set_profile(request): '''修改个人配置''' form = ProfileForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.id = request.session['uid'] profile.save() # 更新缓存 key = 'ProfileDict-%s' % profile.id cache.set(key, profile.to_dict(), 86400 * 7) return render_json(None) else: raise errors.ProfileErr(form.errors)
def profile_editor(request): context = dict() context['user'] = request.user context['edit_form'] = ProfileForm context.update(csrf(request)) if request.POST: form = ProfileForm(request.POST) context['edit_form'] = form if form.is_valid(): form.save(commit=False) user_id = request.user.id user_profile = UserProfile.objects.get(user_id=user_id) user_profile.first_name = request.POST['first_name'] user_profile.last_name = request.POST['last_name'] user_profile.birthday = request.POST['birthday'] user_profile.about_user = request.POST['about_user'] user_profile.save() return redirect('user.views.profile', user_id=user_id) else: context['form'] = form return render(request, "profile_editor.html", context)