def profile(): form = ProfileForm(obj=current_user) if form.validate_on_submit(): form.populate_obj(user) user.update_at = get_current_time() db.session.commit() flash('Public profile updated.', 'success') return render_template('user/profile.html', form=form)
def modify_profile(request): """ 编辑个人信息 """ from user.forms import ProfileForm # 表单数据获取 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()) result = profile.to_dict() # 添加缓存 cache.set(f'Profile-{profile.id}', result) return render_json(result) else: return render_json(form.errors, code.ProfileError.code)
def update_profile(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile = profile_form.instance profile.user = request.user profile.save() return redirect('/') else: messages.error(request, _('Please correct the error below.')) else: user_form = UserForm(instance=request.user) profile_form = ProfileForm(instance=request.user.profile) return render(request, 'post/profile.html', { 'user_form': user_form, 'profile_form': profile_form })
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 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 set_profile(request): """修改个人资料""" user_from = UserForm(request.POST) profile_from = ProfileForm(request.POST) # 检查数据有效性 if not user_from.is_valid(): raise stat.UserFormErr(user_from.errors) if not profile_from.is_valid(): raise stat.ProfileFormErr(profile_from.errors) data = {} data.update(user_from.cleaned_data) data.update(profile_from.cleaned_data) data['birthday'] = str(data['birthday']) # 保存数据 User.objects.filter(id=request.uid).update(**user_from.cleaned_data) Profile.objects.filter(id=request.uid).update(**profile_from.cleaned_data) return render_json()
def update_profile(request): """更新个人资料""" # 定义 form 对象 user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) # 检查验证数据 if user_form.is_valid() and profile_form.is_valid(): uid = request.session['uid'] User.objects.filter(id=uid).update(**user_form.cleaned_data) Profile.objects.update_or_create(id=uid, defaults=profile_form.cleaned_data) inf_log.debug('删除旧缓存') rds.delete(keys.PROFILE_K % uid) return render_json() else: err = {} err.update(user_form.errors) err.update(profile_form.errors) raise errors.ProfileErr(data=err)
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)
def set_profile(request): ''' 修改个人资料 考虑修改什么? 基础上,request.POST.get('key')将所有的字段进行修改; 缺点:过于繁琐,不易整理,没有数据检查和清洗过程; 优化:使用form表单进行操作;[forms模块] Django提供类Form来处理提交form表单信息,并与模型进行绑定 ''' user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) # 获取form表单信息之后,查看form字段是否合法 if not user_form.is_valid(): # 用户信息提交有错误 return render_json(data=None, code=USER_DATA_ERR) if not profile_form.is_valid(): # 交友信息提交有错误 return render_json(data=None, code=PROFILE_DATA_ERR) # form表单信息合法之后,调用clean_data()方法 # 保存用户的信息 user = request.user # 字典类型的更新数据操作 # user_form.cleaned_data:查看form对象信息,字典格式 user.__dict__.update(user_form.cleaned_data) # save()方法。 # 这个方法根据表单绑定的数据创建并保存数据库对象。 ModelForm的子类可以接受 # 现有的模型实例作为关键字参数instance;如果提供此功能,则save()将更新该实例。 # 如果没有提供,save() 将创建模型的一个新实例 user.save() # 修改缓存(缓存更新的方法) key = keys.PROFILE_KEY % request.user.id rds.set(key, user.to_dict('vip_id', 'vip_expired')) user.profile.__dict__.update(profile_form.cleaned_data) return render_json()
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) # 修改用户数据 # update user set nickname='xx', gender='male' where id=uid; 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 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 get(self, request, *args, **kwargs): if request.user.is_authenticated: form = ProfileForm( data=request.POST if request.method == 'POST' else None, instance=request.user) else: form = JoinForm( data=request.POST if request.method == 'POST' else None) context = self.get_context_data(**kwargs) context.update({ 'form': form, 'title': 'Signup' if not request.user.is_authenticated else 'Update profile' }) return self.render_to_response(context)
def _set_profile_form(self, user, use_form=False): # returns the intial value of the user's # profile details on load data = { "firstname": user.firstname, "lastname": user.lastname, "address1": user.address1, "area": user.area, "email": user.email, "city": user.city, "state": user.state, "mobile": user.mobile, "date_of_birth": user.date_of_birth, "gender": user.gender, # "profile_picture": None } if use_form: return ProfileForm(initial={**data}) return data
def update_profile(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): profile_form.save() messages.success(request, ('Your profile was successfully updated!')) return HttpResponseRedirect('/') else: messages.error(request, ('Please correct the error below.')) else: user_form = UserForm(instance=request.user) profile_form = ProfileForm(instance=request.user.profile) return render(request, 'user/profile_update.html', { 'user_form': user_form, 'profile_form': profile_form })
def manageuser(request, username): user = get_object_or_404(User, username = username) user2 = Profile.objects.get(user = user.pk) profileform = ProfileForm(instance = user2) userform = UserEditForm(instance = user) args = {'profileform' : profileform, 'userform' : userform, 'user' : user2, 'data' : user} if request.method == 'POST': profileform = ProfileForm(request.POST, request.FILES, instance = user2) userform = UserEditForm(request.POST, instance = user) if profileform.is_valid() and userform.is_valid(): profileform.save() userform.save() args = {'profileform' : profileform, 'userform' : userform, 'user' : user2, } return redirect('/webmaster/user/'+user.username) else: print("errors : {}".format(profileform.errors.as_data())) print("errors : {}".format(userform.errors.as_data())) return render(request, 'webadmin/pages/manage/user/index.html',args)
def get_context_data(self, **kwargs): user = self.object # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # set the context for the profile form context["profile_form"] = ProfileForm( initial={**self._set_profile_form(user)}, disable_fields=True) # set the context for the bank form try: bank = Bank.objects.get(user=user) context["bank_form"] = BankForm(initial={ **self._set_bank_form_data(bank.bank, bank.account_number) }) context["user"] = user context["user_profile_photo"] = user.profile_picture.url except Bank.DoesNotExist: context["bank_form"] = BankForm() except ValueError: context["user_profile_photo"] = None return context
def adminusers(request): users = Profile.objects.select_related('user') profileform = ProfileForm() userform = UserForm() args = {'profile' : users, 'profileform' : profileform, 'userform' : userform} if request.method == 'POST': profileform = ProfileForm(request.POST) userform = UserForm(request.POST) if profileform.is_valid() and userform.is_valid(): profile = profileform.save(commit=False) user = userform.save() profile.user = user profile.save() else: print("errors : {}".format(profileform.errors.as_data())) print("errors : {}".format(userform.errors.as_data())) return render(request, 'webadmin/pages/database/users/index.html',args)
def profile(request): if request.method == 'POST': pform = ProfileForm(request.POST, request.FILES, instance=request.user.profile) uform = UserUpdateForm(request.POST, instance=request.user) if pform.is_valid() and uform.is_valid(): pform.save() uform.save() return HttpResponseRedirect(reverse('profile')) # return HttpResponse(request.FILES) else: pform = ProfileForm(instance=request.user.profile) uform = UserUpdateForm(instance=request.user) return render(request, 'user/profile.html', { 'pform': pform, 'uform': uform })
def UpdateProfile(request): user_instance = request.user profile_instance = user_instance.profile if request.method == "POST": profile_form = ProfileForm(request.POST, instance=profile_instance) user_form = UserUpdateForm(request.POST, instance=user_instance) if profile_form.is_valid() and user_form.is_valid(): profile_form.save() # user = user_form.save(commit=False) user_form.save() else: profile_form = ProfileForm(instance=profile_instance) user_form = UserUpdateForm(instance=user_instance) return render(request, "account/profile.html", { 'user_form': user_form, 'profile_form': profile_form })
def admindatabase(request): postform = PostForm() roleform = RoleForm() profileform = ProfileForm() userform = UserForm() publicationform = PublicationForm() args = {'postform' : postform, 'roleform' : roleform, 'publicationform' :publicationform, 'profileform' : profileform, 'userform' : userform } if request.method == "POST": if 'add_post' in request.POST: postform = PostForm(request.POST, request.FILES) if postform.is_valid(): postform.save() else: print("errors : {}".format(postform.errors.as_data())) elif 'add_role' in request.POST: roleform = RoleForm(request.POST) if roleform.is_valid(): data = roleform.cleaned_data['user_id'] data2 = roleform.cleaned_data['publication'] if Role.objects.check_role(data,data2): print("User already has role in this publication") else: roleform.save() else: print("errors : {}".format(roleform.errors.as_data())) elif 'add_publication' in request.POST: publicationform = PublicationForm(request.POST, request.FILES) if publicationform.is_valid(): publicationform.save() else: print("errors : {}".format(publicationform.errors.as_data())) elif 'add_user' in request.POST: profileform = ProfileForm(request.POST) userform = UserForm(request.POST) if profileform.is_valid() and userform.is_valid(): profile = profileform.save(commit=False) user = userform.save() profile.user = user profile.save() else: print("errors : {}".format(profileform.errors.as_data())) print("errors : {}".format(userform.errors.as_data())) return render(request, 'webadmin/pages/database/index.html',args)
def admin(request): if request.user.is_authenticated: if request.user.is_staff: # Data users = Profile.objects.select_related('user').order_by('auth_user.date_joined').reverse()[:5] posts = Post.objects.all().order_by('created').reverse()[:5] publications = Publication.objects.all().order_by('created').reverse()[:5] # Forms postform = PostForm() roleform = RoleForm() profileform = ProfileForm() userform = UserForm() publicationform = PublicationForm() searchuserform = SearchUserForm() searchpostform = SearchPostForm() searchpageform = SearchPageForm() # Counter rolecount = Role.objects.count() usercount = Profile.objects.count() pagecount = Publication.objects.count() postcount = Post.objects.count() args = {'profile' : users ,'posts' : posts, 'publications' : publications, 'postform' : postform, 'roleform' : roleform, 'publicationform' : publicationform, 'profileform' : profileform, 'userform' : userform, 'searchuser' : searchuserform, 'searchpost' : searchpostform, 'searchpage' : searchpageform, 'rolec' : rolecount, 'userc' : usercount, 'pagec' : pagecount, 'postc' : postcount,} if request.method == "POST": if 'add_post' in request.POST: postform = PostForm(request.POST, request.FILES) if postform.is_valid(): postform.save() else: print("errors : {}".format(postform.errors.as_data())) elif 'add_role' in request.POST: roleform = RoleForm(request.POST) if roleform.is_valid(): data = roleform.cleaned_data['user_id'] data2 = roleform.cleaned_data['publication'] if Role.objects.check_role(data,data2): print("User already has role in this publication") else: roleform.save() else: print("errors : {}".format(roleform.errors.as_data())) elif 'add_publication' in request.POST: publicationform = PublicationForm(request.POST, request.FILES) if publicationform.is_valid(): publicationform.save() else: print("errors : {}".format(publicationform.errors.as_data())) elif 'add_user' in request.POST: profileform = ProfileForm(request.POST) userform = UserForm(request.POST) if profileform.is_valid() and userform.is_valid(): profile = profileform.save(commit=False) user = userform.save() profile.user = user profile.save() else: print("errors : {}".format(profileform.errors.as_data())) print("errors : {}".format(userform.errors.as_data())) elif 'search_user' in request.POST: searchuserform = SearchUserForm(request.POST) if searchuserform.is_valid(): try: user = User.objects.get(username = searchuserform.cleaned_data['username']) return redirect('user/'+searchuserform.cleaned_data['username']) except User.DoesNotExist: print('User does not exist') else: print("errors : {}".format(searchuserform.errors.as_data())) elif 'search_post' in request.POST: searchpostform = SearchPostForm(request.POST) if searchpostform.is_valid(): try: post = Post.objects.get(slug = searchpostform.cleaned_data['slug']) return redirect('post/'+searchuserform.cleaned_data['slug']) except Post.DoesNotExist: print('Post does not exist') else: print("errors : {}".format(searchpostform.errors.as_data())) elif 'search_page' in request.POST: searchpageform = SearchPageForm(request.POST) if searchpageform.is_valid(): try: page = Publication.objects.get(slug = searchpageform.cleaned_data['slug']) return redirect('page/'+searchpageform.cleaned_data['slug']) except Publication.DoesNotExist: print('Page does not exist') else: print("errors : {}".format(searchpageform.errors.as_data())) elif 'dsearch_user' in request.POST: searchuserform = SearchUserForm(request.POST) if searchuserform.is_valid(): try: user = User.objects.get(username = searchuserform.cleaned_data['username']) user.delete() except User.DoesNotExist: print('User does not exist') else: print("errors : {}".format(searchuserform.errors.as_data())) elif 'dsearch_post' in request.POST: searchpostform = SearchPostForm(request.POST) if searchpostform.is_valid(): try: post = Post.objects.get(slug = searchpostform.cleaned_data['slug']) post.delete() except Post.DoesNotExist: print('Post does not exist') else: print("errors : {}".format(searchpostform.errors.as_data())) elif 'dsearch_page' in request.POST: searchpageform = SearchPageForm(request.POST) if searchpageform.is_valid(): try: page = Publication.objects.get(slug = searchpageform.cleaned_data['slug']) page.delete() except Publication.DoesNotExist: print('Page does not exist') else: print("errors : {}".format(searchpageform.errors.as_data())) return render(request, 'webadmin/index.html',args) else: return index(request) else: return redirect('/webmaster/login/')
def get(self, request): form = ProfileForm(instance=request.user) return render(request, 'user/change_profile.html', context={'form': form})
def profile(request): form = ProfileForm(request.POST) current_user = request.user mongodb = mongo_client['LOOKING'] looking = mongodb.looking temPerfil = looking.find({'username': current_user.username}) if request.method == 'GET': if temPerfil: for perfil in temPerfil: info = { 'username': current_user.username, 'nome': perfil['nome'], 'email': perfil['email'], 'rua': perfil['rua'], 'numero': perfil['numero'], 'bairro': perfil['bairro'], 'cidade': perfil['cidade'], 'bio': perfil['bio'], 'tecnologias': perfil['tecnologias'], 'ativo': perfil['ativo'] } form = ProfileForm(info) else: info = {''} if request.method == 'POST': if form.is_valid(): nome = form.cleaned_data.get('nome') email = form.cleaned_data.get('email') rua = form.cleaned_data.get('rua') numero = form.cleaned_data.get('numero') bairro = form.cleaned_data.get('bairro') cidade = form.cleaned_data.get('cidade') bio = form.cleaned_data.get('bio') tecnologias = form.cleaned_data.get('tecnologias') ativo = form.cleaned_data.get('ativo') json = { 'username': current_user.username, 'nome': nome, 'email': email, 'rua': rua, 'numero': numero, 'bairro': bairro, 'cidade': cidade, 'bio': bio, 'tecnologias': tecnologias, 'ativo': ativo } if temPerfil: looking.delete_one({'username': current_user.username}) looking = looking.insert_one(json).inserted_id else: looking = looking.insert_one(json).inserted_id cache.clear() context = {'form': form} return render(request, 'profile.html', context)
def profile(username): """ Creating the fucntion profile to process and display all the actions on profile page/template """ # Creating instances of Forms form = ProfileForm(username=username) form_tweet = Tweet() signup = Signup.query.filter_by(username=username).first() profile = Profile.query.filter_by(signup_id=signup.id).first() # Storing the photo urls profile_url = '/static/images/{}'.format(profile.profile_photo) header_url = '/static/images/{}'.format(profile.header_photo) # Logic for uploading photos and redirecting them after editing the profile if request.method == 'POST' and form.validate_on_submit(): try: profile_name = photos.save(request.files['profile_photo']) profile_url = '/static/images/{}'.format(profile_name) profile.profile_photo = profile_name except: pass try: header_name = photos.save(request.files['header_photo']) header_url = '/static/images/{}'.format(header_name) profile.header_photo = header_name except: pass signup.username = form.username.data profile.bio = form.bio.data profile.location = form.location.data profile.website = form.website.data db.session.commit() return redirect(url_for('profile', username=username)) # Find the total number of tweets total_likes = 0 tweets = Tweets.query.filter_by(username=username).order_by( Tweets.id.desc()).all() for tweet in tweets: total_likes = total_likes + tweet.likes users = Signup.query.filter(Signup.username != current_user.username).all() # finding the total number of followers and following and tweets total_attrib = [] total_attrib.append(len(tweets)) following = Following.query.filter_by(username=username).all() total_attrib.append(len(following)) followers = Followers.query.filter_by(username=username).all() total_attrib.append(len(followers)) # Displaying the 'who to follow' section and including 3 random real users in it display_users = [] if users: for i in range(3): temp = [] user = random.choice(users) signup_url = Signup.query.filter_by(username=user.username).first() user_url = '/static/images/{}'.format( signup_url.profile.first().profile_photo) temp.append(user) if Following.query.filter_by(username=current_user.username, following=user.username).first(): temp.append('Unfollow') else: temp.append('Follow') temp.append(user_url) display_users.append(temp) return render_template('timeline/profile.html', tweets=tweets, display_users=display_users, total_attrib=total_attrib, profile=profile, total_likes=total_likes, form=form, profile_url=profile_url, header_url=header_url, form_tweet=form_tweet)