def setUp(self): self.user = User.objects.get(username='******') self.user_profile = UserProfile( user=self.user, ) self.user_profile.save()
class UserProfileModel(TestCase): """Test UserProfile Model""" fixtures = ['auth_user.json'] def setUp(self): self.user = User.objects.get(username='******') self.user_profile = UserProfile( user=self.user, ) self.user_profile.save() def test_user_profile_forms(self): self.assertEqual(self.user_profile.user, self.user) form = UserChangeDetailForm(self.user) form.user.last_name = "Test" form.user.first_name = "Test" form.user.save() form = UserChangeDetailExtendForm(self.user) form.user.address = "test address" form.user.save() def teardown(self): self.user_profile.delete()
def setUp(self): self.user = User.objects.get(username='******') self.dialersetting = DialerSetting.objects.get(pk=1) self.user_profile = UserProfile( user=self.user, dialersetting=self.dialersetting ) self.user_profile.save()
def create_user_profile(sender, **kwargs): # check if the save is due to creation, then if it is, # create the profile. if kwargs.get('created', None): user = kwargs.get('instance', None) if user and user.id: print("CREATING user_profile") user_profile = UserProfile(user=user) user_profile.save()
def register_company(self, request, **kwargs): corporate_name = kwargs['corporate_name'] short_name = kwargs['short_name'] website = kwargs.get('website', None) company_phone = kwargs.get('company_phone', None) company_email = kwargs['company_email'] password = kwargs['password1'] contact_person = kwargs['contact_person'] contact_person_phone = kwargs.get('contact_person_phone', None) contact_person_email = kwargs['contact_person_email'] contact_person_position = kwargs.get('contact_person_position', None) if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) new_user = RegistrationProfile.objects.create_inactive_user( company_email, company_email, password, site, send_email=False ) new_user.first_name = short_name new_user.save() new_profile = UserProfile(user=new_user, is_organization=True) new_organization = Organization( user=new_user, corporate_name=corporate_name, short_name=short_name, website=website, company_phone=company_phone, company_email=company_email, contact_person=contact_person, contact_person_phone=contact_person_phone, contact_person_email=contact_person_email, contact_person_position=contact_person_position, approved=False ) new_organization.save() new_profile.organization = new_organization new_profile.save() signals.user_registered.send( sender=self.__class__, user=new_user, request=request ) return new_user
def sign_up(request): context = {} form = SignUpForm(request.POST or None) if request.method == "POST": if form.is_valid(): user = form.save() user_profile = UserProfile(user=user) user_profile.save() login(request, user) return redirect('index') context['form'] = form return render(request, 'registration/sign_up.html', context)
def register(request): if request.method == 'POST': form = RegisterForm(data=request.POST) if form.is_valid(): form.save() user_profile = UserProfile() user_profile.user = User.objects.get( username=form.data['username']) user_profile.save() return redirect('login') else: form = RegisterForm return render(request, "main/register.html", {'form': form})
def signup_view(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() userprofile = UserProfile(user_name=user.username, description='Hello there, this is the description of yours.', user_fk=user) userprofile.save() return redirect('login') else: form = UserCreationForm() return render(request, 'user_auth/custom_signup.html')
def post(self, request, *args, **kwargs): pk = kwargs.get('pk') self.get_object() form = self.get_form() if form.is_valid(): user_role_id = int(self.request.POST[u'role']) unit_id = int(self.request.POST[u'organizationalunit']) user = form.save() user_role = UserRole.objects.get(pk=user_role_id) unit = OrganizationalUnit.objects.get(pk=unit_id) cd = form.cleaned_data add_info = cd['additional_information'] # Create if not pk: user_profile = UserProfile( user=user, user_role=user_role, organizationalunit=unit, additional_information=add_info, ) else: # Update user_profile = user.userprofile user_profile.user = user user_profile.user_role = user_role user_profile.organizationalunit = unit cd = form.cleaned_data user_profile.additional_information = add_info user_profile.save() # Send email to newly created users if not pk: try: KUEmailMessage.send_email( EmailTemplateType.system__user_created, { 'user': user, 'password': form.cleaned_data['password1'], }, [user], user ) except Exception as e: print("Error sending mail to user: %s" % e) messages.add_message( request, messages.INFO, _(u'Brugeren %s blev gemt' % user.username) ) return super(CreateUserView, self).form_valid(form) else: return self.form_invalid(form)
def update_question(request, username, question_id): """ Update a single answer for a particular profile question of a particular user """ profile = UserProfile.get_user_profile_from_username(username) # Make sure that the profile exists if profile: user = profile.user else: return form_failure_notification('User does not exist') # Make sure that a user is only able to update his profile and nobody else's. if request.user != user: return form_failure_notification('Uh oh! Something went wrong!') if request.method == 'POST': profile_answer_form = ProfileAnswerForm(request.POST) if profile_answer_form.is_valid(): new_answer = request.POST.get('answer', '') profile_answer = ProfileAnswer.get_answer(user, ProfileQuestion.objects.get(id=question_id)) profile_answer.answer = new_answer profile_answer.save() return ajax_http(form_success_notification('Question successfully updated')) else: return ajax_http(form_failure_notification('Answer too long'))
def post(request): """ Create user """ serializer = UserSerializerCreate(data=request.data, context={'request': request}) if serializer.is_valid(): user = serializer.save() user.set_password(serializer.validated_data['password']) user.is_active = False user.save() user = get_object_or_404(User, email=request.data.get('email')) code_object = UserActivationCode.objects.create(user=user) code = code_object.code current_site = get_current_site(request) mail_subject = 'Welcome To ProHealth.' message = render_to_string('user_activation.html', { 'user': user.email, 'domain': current_site.domain, 'code': code, }) to_email = user.email email = EmailMessage(mail_subject, message, to=[to_email]) email.send() UserProfile(user=user).save() DoctorProfile(user=user).save() return Response(UserSerializer(user).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def change_password(request, username): if request.method == 'POST': profile = UserProfile.get_user_profile_from_username(username) # Make sure that the profile exists if profile: user = profile.user else: raise Http404('The username {} does not exist'.format(username)) # Make sure that a user is only able to update his profile and nobody else's. if request.user != user: raise Http404('') change_password_form = ChangePasswordForm(request.POST, request=request) if change_password_form.is_valid(): new_password = change_password_form.cleaned_data.get( 'new_password') user.set_password(new_password) user.save() return redirect( reverse('view_profile', kwargs={'username': username})) else: raise Http404() raise Http404()
def update_question(request, username, question_id): """ Update a single answer for a particular profile question of a particular user """ profile = UserProfile.get_user_profile_from_username(username) # Make sure that the profile exists if profile: user = profile.user else: return form_failure_notification('User does not exist') # Make sure that a user is only able to update his profile and nobody else's. if request.user != user: return form_failure_notification('Uh oh! Something went wrong!') if request.method == 'POST': profile_answer_form = ProfileAnswerForm(request.POST) if profile_answer_form.is_valid(): new_answer = request.POST.get('answer', '') profile_answer = ProfileAnswer.get_answer( user, ProfileQuestion.objects.get(id=question_id)) profile_answer.answer = new_answer profile_answer.save() return ajax_http( form_success_notification('Question successfully updated')) else: return ajax_http(form_failure_notification('Answer too long'))
def profile_reviews(request, username): # Look up the user record who corresponds to this profile profile = UserProfile.get_user_profile_from_username(username) if profile: user = profile.user else: raise Http404('The username {} does not exist'.format(username)) # If the user looking at this profile is its owner, then we want to render a couple edit buttons if request.user == user: is_owner = True else: is_owner = False user_location = user.location user_info = { 'name': user, 'age': user.age(), 'city': user_location.city, 'state': user_location.state, 'rating': user.rating, 'username': username, } try: user_info['profile_picture'] = user.profile_picture except ObjectDoesNotExist: pass reviews = Review.objects.filter( reviewee=user.id).order_by('creation_timestamp') if reviews: most_recent_review = reviews[0] reviewer_location = most_recent_review.reviewer.location reviewer_city, reviewer_state = reviewer_location.city, reviewer_location.state most_recent_review_info = { 'name': most_recent_review.reviewer.get_short_name(), 'age': most_recent_review.reviewer.age(), 'city': reviewer_city, 'state': reviewer_state, 'contents': most_recent_review.contents, 'rating': most_recent_review.rating } else: most_recent_review_info = None return render( request, 'user_profile/profile_reviews.html', { 'user_info': user_info, 'is_owner': is_owner, 'most_recent_review_info': most_recent_review_info, 'reviews': reviews, 'form_settings': profile_answer_form_settings, }, content_type='text/html', )
def change_phone(request): # Deja un profil try: instance = UserProfile.objects.get(user=request.user) # Creation profil except UserProfile.DoesNotExist: instance = UserProfile(user=request.user) form = PhoneForm(request.POST or None, instance=instance, initial={'phone': instance.phone}) if request.method == 'POST': if form.is_valid(): form.save() messages.success(request, 'Your phone number has been changed.') return HttpResponseRedirect('') else: messages.error(request, 'An error happened.') context = { 'form': form, } return render(request, 'user_profile/change_phone.html', context)
def registerView(request): if request.method == 'GET': return render(request=request, template_name='register.html') elif request.method == 'POST': try: json_data = json.loads(request.body) # email = json_data['email'] name = json_data['username'] password = json_data['password'] except: return HttpResponse(content='Provide values', status=400) if UserProfile.objects.filter(username=email).count() > 0: return HttpResponse(content='Provide correct values', status=400) user = UserProfile(username=email, first_name=name, password=password) user.save() return HttpResponseRedirect('/login/')
def post(self, request, *args, **kwargs): email = request.data.get('email') new_user = User(username=email, email=email, is_active=False) new_user.save() new_user_profile = UserProfile(user=new_user) new_user_profile.save() registration = Registration(user=new_user_profile) registration.save() send_mail( 'Verification code', f'Please confirm the verification code {registration.code}', '*****@*****.**', [email], fail_silently=False, ) return Response(status=200)
def perform_create(self, serializer): email = self.request.data["email"] code = uuid4() send_mail( 'Motion registration code', f'Your registration code for the Motion Website is : {code}', os.environ.get('DEFAULT_FROM_EMAIL'), [email], fail_silently=False, ) new_user = User(email=email, username=code) new_user.save() new_profile = UserProfile(user=new_user) new_profile.save() serializer.save(code=code, user=new_profile)
def register_user(request): if request.user.is_authenticated(): return HttpResponse(content="Forbidden", status=403) else: args = {} args.update(csrf(request)) if request.method == 'POST': form = RegistrationForm(request.POST) args['form'] = form if form.is_valid(): form.save() # save user to database if form is valid username = form.cleaned_data['username'] email = form.cleaned_data['email'] salt = hashlib.sha1(str(random.random())).hexdigest()[:5] activation_key = hashlib.sha1(salt + email).hexdigest() key_expires = datetime.datetime.today() + datetime.timedelta(2) #Get user by username user = User.objects.get(username=username) # Create and save user profile new_profile = UserProfile(user=user, activation_key=activation_key, key_expires=key_expires) new_profile.save() # Send email with activation key email_subject = 'User account confirmation' email_body = "Hello, %s, thank you for creating your profile! \ To activate your profile please open this link within next 48h \ http://127.0.0.1:8000/user-account/submit/%s" % ( username, activation_key) send_mail(email_subject, email_body, '*****@*****.**', [email], fail_silently=False) return HttpResponseRedirect( '/user-account/account-successfully-created') else: args['form'] = RegistrationForm() return render_to_response('user_account/register.html', args, context_instance=RequestContext(request))
def register_company(self, request, **kwargs): corporate_name = kwargs['corporate_name'] short_name = kwargs['short_name'] website = kwargs.get('website', None) company_phone = kwargs.get('company_phone', None) company_email = kwargs['company_email'] password = kwargs['password1'] contact_person = kwargs['contact_person'] contact_person_phone = kwargs.get('contact_person_phone', None) contact_person_email = kwargs['contact_person_email'] contact_person_position = kwargs.get('contact_person_position', None) if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) new_user = RegistrationProfile.objects.create_inactive_user( company_email, company_email, password, site, send_email=False) new_user.first_name = short_name new_user.save() new_profile = UserProfile(user=new_user, is_organization=True) new_organization = Organization( user=new_user, corporate_name=corporate_name, short_name=short_name, website=website, company_phone=company_phone, company_email=company_email, contact_person=contact_person, contact_person_phone=contact_person_phone, contact_person_email=contact_person_email, contact_person_position=contact_person_position, approved=False) new_organization.save() new_profile.organization = new_organization new_profile.save() signals.user_registered.send(sender=self.__class__, user=new_user, request=request) return new_user
def view_profile(request, username): # Look up the user record who corresponds to this profile profile = UserProfile.get_user_profile_from_username(username) if profile: user = profile.user else: raise Http404('The username {} does not exist'.format(username)) # If the user looking at this profile is its owner, then we want to render a couple edit buttons if request.user == user: is_owner = True else: is_owner = False user_location = user.location most_recent_review = user.most_recent_review() user_info = {'name': user, 'age': user.age(), 'city': user_location.city, 'state': user_location.state, 'rating': user.rating, 'username': username, } try: user_info['profile_picture'] = user.profile_picture except ObjectDoesNotExist: pass if most_recent_review: reviewer_location = most_recent_review.reviewer.location reviewer_city, reviewer_state = reviewer_location.city, reviewer_location.state most_recent_review_info = {'name': most_recent_review.reviewer.get_short_name(), 'age': most_recent_review.reviewer.age(), 'city': reviewer_city, 'state': reviewer_state, 'contents': most_recent_review.contents, 'rating': most_recent_review.rating } else: most_recent_review_info = None # Get the profile questions and the user's answers, if they exist. profile_questions = ProfileQuestion.objects.all() question_answer_pairs = ((ProfileAnswer.get_answer(user, profile_question), profile_question) for profile_question in profile_questions) return render(request, 'user_profile/view_profile.html', {'user_info': user_info, 'is_owner': is_owner, 'question_answer_pairs': question_answer_pairs, 'most_recent_review_info': most_recent_review_info, 'form_settings': profile_answer_form_settings, }, content_type='text/html', )
def put(self, request, profile_id): data = json.loads(request.body) profile = UserProfile.get_by_id(profile_id) if profile_data_validator(data): profile.update(**data) return JsonResponse(profile.to_dict(), status=200) return HttpResponseBadRequest()
def create_user(self, username, email, role, first_name=None, last_name=None, unit=None): user = User(username=username, first_name=first_name, last_name=last_name, email=email) user.save() profile = UserProfile( user=user, user_role=UserRole.objects.filter(role=role).first(), organizationalunit=unit) profile.save() return user
def post(self, request): data = json.loads(request.body) user = User.get_by_id(data['user_id']) if user: profile = UserProfile.create(**data) if profile: return JsonResponse(profile.to_dict(), status=201) return HttpResponseBadRequest() return JsonResponse({"msg": "user no found"}, status=400)
def register(self, request, **kwargs): import hashlib from numconv import NumConv first_name, last_name = kwargs['first_name'], kwargs['last_name'] email = kwargs['email'] password = kwargs['password1'] if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) # create a hash from email in order to be user as username usname = str(hashlib.sha1(email).hexdigest()) usname = NumConv(16).str2int(usname) usname = NumConv(64).int2str(usname) # create a new User new_user = RegistrationProfile.objects.create_inactive_user( usname, email, password, site, send_email=not settings.CLOSED_BETA_ACTIVE ) new_user.first_name = first_name new_user.last_name = last_name new_user.save() if settings.CLOSED_BETA_ACTIVE: new_user.is_active = True new_user.save() new_profile = UserProfile(user=new_user) new_profile.save() signals.user_registered.send( sender=self.__class__, user=new_user, request=request ) return new_user
def profile_reviews(request, username): # Look up the user record who corresponds to this profile profile = UserProfile.get_user_profile_from_username(username) if profile: user = profile.user else: raise Http404('The username {} does not exist'.format(username)) # If the user looking at this profile is its owner, then we want to render a couple edit buttons if request.user == user: is_owner = True else: is_owner = False user_location = user.location user_info = {'name': user, 'age': user.age(), 'city': user_location.city, 'state': user_location.state, 'rating': user.rating, 'username': username, } try: user_info['profile_picture'] = user.profile_picture except ObjectDoesNotExist: pass reviews = Review.objects.filter(reviewee=user.id).order_by('creation_timestamp') if reviews: most_recent_review = reviews[0] reviewer_location = most_recent_review.reviewer.location reviewer_city, reviewer_state = reviewer_location.city, reviewer_location.state most_recent_review_info = {'name': most_recent_review.reviewer.get_short_name(), 'age': most_recent_review.reviewer.age(), 'city': reviewer_city, 'state': reviewer_state, 'contents': most_recent_review.contents, 'rating': most_recent_review.rating } else: most_recent_review_info = None return render(request, 'user_profile/profile_reviews.html', {'user_info': user_info, 'is_owner': is_owner, 'most_recent_review_info': most_recent_review_info, 'reviews': reviews, 'form_settings': profile_answer_form_settings, }, content_type='text/html', )
def edit_image(request): """ Edit the profile image for a user profile """ username = request.user.username user = User.objects.get(username=username) fullname = user.get_full_name() form = ImageForm(request.POST, request.FILES) user_profile = UserProfile.objects.filter(user=user) if len(user_profile) != 0: current_user_profile = user_profile[0] elif form.is_valid(): current_user_profile = UserProfile(user=user) current_user_profile.generate_user_id() current_user_profile.save() if form.is_valid(): photo = request.FILES["image"] if str(current_user_profile.photo) != "": delete_image(MEDIA_ROOT + str(user_profile[0].photo)) current_user_profile.photo = photo current_user_profile.save() info = True info_message = "Image Succesfully Updated !" parameters = {'info': info, 'info_message': info_message} else: error = True error_message = "Please select a valid Image" parameters = {'error': error, 'error_message': error_message} default_image = "/static/elearning_academy/img/default/user.jpg" parameters.update({ 'user_name': fullname, 'default_image': default_image, 'profile_exists': True }) user_profile_dictionary = json.loads(current_user_profile.toJson()) parameters.update(user_profile_dictionary) form = get_update_form(user) parameters.update(form) return render(request, 'user_profile/profile.html', parameters)
def AccountRegistration(request): if request.user.is_authenticated(): return HttpResponseRedirect('/profile') if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = User.objects.create_user(username=form.cleaned_data['username'], email=form.cleaned_data['email'], password=form.cleaned_data['password']) user.save() account = UserProfile(user=user) account.save() return HttpResponseRedirect('/registration/ok/') else: return render_to_response('register.html', {'form':form}, context_instance = RequestContext(request)) else: ''' pusty formularz ''' form = RegistrationForm() context ={'form': form} return render_to_response('register.html', context, context_instance = RequestContext(request))
def register(self, request, **kwargs): import hashlib from numconv import NumConv first_name, last_name = kwargs['first_name'], kwargs['last_name'] email = kwargs['email'] password = kwargs['password1'] if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) # create a hash from email in order to be user as username usname = str(hashlib.sha1(email).hexdigest()) usname = NumConv(16).str2int(usname) usname = NumConv(64).int2str(usname) # create a new User new_user = RegistrationProfile.objects.create_inactive_user( usname, email, password, site, send_email=not settings.CLOSED_BETA_ACTIVE) new_user.first_name = first_name new_user.last_name = last_name new_user.save() if settings.CLOSED_BETA_ACTIVE: new_user.is_active = True new_user.save() new_profile = UserProfile(user=new_user) new_profile.save() signals.user_registered.send(sender=self.__class__, user=new_user, request=request) return new_user
def edit_user_intro(request): """ Edit the User Intro in User Profile """ user = request.user fullname = user.get_full_name() form = AboutForm(request.POST) user_profile = UserProfile.objects.filter(user=user) if len(user_profile) != 0: current_user_profile = user_profile[0] elif form.is_valid(): current_user_profile = UserProfile(user=user) current_user_profile.generate_user_id() current_user_profile.save() if form.is_valid(): user.first_name = form.cleaned_data["first_name"] user.last_name = form.cleaned_data["last_name"] user.save() current_user_profile.about = form.cleaned_data["about"] current_user_profile.interests = form.cleaned_data["interests"] current_user_profile.save() info = True info_message = "Introduction Updated !" parameters = {'info': info, 'info_message': info_message} print "success" else: error = True error_message = "Invalid Form Entry" parameters = {'error': error, 'error_message': error_message} default_image = "/static/elearning_academy/img/default/user.jpg" parameters.update({'user_name': fullname, 'default_image': default_image, 'profile_exists': True}) user_profile_dictionary = json.loads(current_user_profile.toJson()) parameters.update(user_profile_dictionary) form = get_update_form(user) parameters.update(form) return render(request, 'user_profile/profile.html', parameters)
def create_or_find_author(self, username): """ returns a User object, rather finding it or creating it """ try: us = User.objects.get(first_name=username) except User.DoesNotExist: us = UserProfile.create_user_with_tokens( username, '', # username username, username) return us
def start(update, context): telegram_id = update.message.from_user.id now = datetime.datetime.now(TZ_MOSCOW) time_now = now.strftime("%H %M") try: profile = UserProfile.objects.get(telegram_id=telegram_id) if not profile.uuid: profile.uuid = uuid.uuid4().hex profile.save() except Exception as e: profile = None if profile: context.user_data["profile"] = profile else: profile = UserProfile() try: new_user = User.objects.create_user( username=telegram_id, email=f"{telegram_id}@workhours.ru", password=f"{uuid.uuid4()}") new_user.is_active = True new_user.save() except Exception as e: new_user = User.objects.get(email=f"{telegram_id}@workhours.ru") profile = UserProfile() profile.user = new_user profile.telegram_id = telegram_id profile.uuid = uuid.uuid4().hex profile.save() context.user_data["profile"] = profile update.message.reply_text( f"""Добро пожаловать http://{INTERFACE_URL}/{profile.uuid}/ (ваша личная страница, здесь можно посмотреть календарь сообщений).\n Время таймера московское (Cейчас у нас {time_now}).\n Введите сообщение, укажите дату и время отправки и нажмите Отправить""", reply_markup=KEYBOARD_MARKUP, ) return CHOOSING
def post(self, request): # 实例化form,验证表单数据 register_form = RegisterForm(request.POST) # 如果表单数据通过了验证 if register_form.is_valid(): user_name = request.POST.get('email', '') # 检查用户名是否已存在于数据库 # 如果用户名已经存在,则返回提示 if UserProfile.objects.filter(email=user_name): return render(request, 'register.html', { 'msg': '用户名已存在', 'register_form': register_form, }) pass_word = request.POST.get('password', '') # 实例化一个UserProfile对象,将表单数据存入数据库 new_user = UserProfile() new_user.username = user_name new_user.email = user_name # 默认激活状态为False new_user.is_active = False # 加密password保存 new_user.password = make_password(pass_word) # 保存提交 new_user.save() # 写入欢迎注册信息 user_message = UserMessage() user_message.user = new_user.id user_message.message = "欢迎注册rongbaoer慕课小站!!" user_message.save() # 发送注册激活邮件 send_register_eamil(user_name, 'register') # 跳转到登陆页面 return render(request, 'register.html', { 'register_form': register_form, 'msg': '激活链接已发送,请注意查收' }) # 邮箱注册form失败 else: return render(request, 'register.html', { 'register_form': register_form, })
def create_or_find_author(self, username): """ returns a User object, rather finding it or creating it """ try: us = User.objects.get(first_name=username) except User.DoesNotExist: us = UserProfile.create_user_with_tokens( username, '', # username username, username ) return us
def save(self, user): """ Saving a new user and creating the UserProfile :param user: Django' user model :return: """ # Saving the User model user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] # Saving the UserProfile model profile = UserProfile(user=user) profile.institution = self.cleaned_data['institution'] profile.phone = self.cleaned_data['phone'] profile.usage = self.cleaned_data['usage'] profile.status = UserProfile.WAITING_APPROBATION_STATE profile.save()
def post(self, request, *args, **kwargs): form = CreateUserForm(request.POST) if form.is_valid(): user = User(username=form.cleaned_data['username']) user.set_password(form.cleaned_data['password']) user.is_staff = ( form.cleaned_data['user_role'] == 'dealer' ) user.is_active = True user.save() user_profile = UserProfile() user_profile.user = user user_profile.notes = form.cleaned_data['notes'] user_profile.comission = form.cleaned_data['comission'] if not user.is_staff: dealer = User.objects.get(pk=form.cleaned_data['select_dealer']) user_profile.dealer = dealer user_profile.open_password = form.cleaned_data['password'] user_profile.save() return HttpResponseRedirect('/user_list.html')
def post(self, request): try: register_form = RegisterForm(request.POST) if register_form.is_valid(): username = request.POST.get('username', '') user = UserProfile.objects.filter(username=username).exists() if not user: user = UserProfile() user.username = username user.password = make_password( request.POST.get('password', '')) user.name = request.POST.get('name', '') user.is_superuser = False user.is_active = True user.is_staff = True user.save() return HttpResponse(json.dumps({ "status": "success", "msg": "人员添加成功!" }), content_type="application/json") else: return HttpResponse(json.dumps({ "status": "fail", "msg": "所添加的用户已经存在!" }), content_type="application/json") else: return render(request, 'add_staffs.html', {"register_form": register_form}) except Exception as e: return HttpResponse(json.dumps({ "status": "fail", "msg": "执行错误!" }), content_type="application/json")
def edit_user_social(request): """ Edit User social details """ user = request.user fullname = user.get_full_name() form = SocialForm(request.POST) user_profile = UserProfile.objects.filter(user=user) if len(user_profile) != 0: current_user_profile = user_profile[0] elif form.is_valid(): current_user_profile = UserProfile(user=user) current_user_profile.generate_user_id() current_user_profile.save() if form.is_valid(): current_user_profile.website_twitter = form.cleaned_data["twitter"] current_user_profile.website_facebook = form.cleaned_data["facebook"] current_user_profile.save() info = True info_message = "Social Networks Updated !" parameters = {'info': info, 'info_message': info_message} else: error = True error_message = "Invalid Form Details" parameters = {'error': error, 'error_message': error_message} default_image = "/static/elearning_academy/img/default/user.jpg" parameters.update({'user_name': fullname, 'default_image': default_image, 'profile_exists': True}) user_profile_dictionary = json.loads(current_user_profile.toJson()) parameters.update(user_profile_dictionary) form = get_update_form(user) parameters.update(form) return render(request, 'user_profile/profile.html', parameters)
def post(self, request): try: register_form = RegisterForm(request.POST) if register_form.is_valid(): username = request.POST.get('username', '') user = UserProfile.objects.filter(username=username).exists() if not user: user = UserProfile() user.username = username user.password = make_password( request.POST.get('password', '')) user.name = request.POST.get('name', '') user.is_superuser = True user.is_active = True user.is_staff = True user.save() return HttpResponseRedirect('/') else: return render(request, 'regist.html', {"msg": "用户已经存在"}) else: return render(request, 'regist.html', {"register_form": register_form}) except Exception as e: return render(request, 'regist.html', {})
def process_objects(self): # Create user passing fields user = UserProfile.create_user_with_tokens( first=self.cleaned_data['first'], last=self.cleaned_data['last'], email=self.cleaned_data['email'], password=self.cleaned_data['password'], facebook_oauth_token=self.cleaned_data.get( 'facebook_oauth_token', None ), facebook_graphid=self.cleaned_data.get('facebook_id', None), twitter_oauth_token=self.cleaned_data.get( 'twitter_oauth_token', None ), twitter_oauth_secret=self.cleaned_data.get( 'twitter_oauth_secret', None ) ) return user
def create_one_license(selling_shop,data_transfer_plan,prefix): # read current index bulk_license_manager = BulkLicenseManagement.objects.all()[0] current_index = bulk_license_manager.current_index # set up username and password username = prefix + str(current_index) password = generate_md5_hash(selling_shop.username + str(current_index)) password = password[: ( len(password)/2 ) ] new_user = User(username=username, password=password) current_index2 = BulkLicenseManagement.objects.all()[0].current_index if current_index != current_index2: raise DatabaseError() else: new_user = User.objects.create_user(username=username, password=password) # create a userprofile for the new customer new_user_profile = UserProfile() new_user_profile.user = new_user new_user_profile.is_shop = False new_user_profile.email_subscription = False new_user_profile.save() # create CustomerProfile new_customer_profile = CustomerProfile() new_customer_profile.user_profile = new_user_profile new_customer_profile.save() #create purchase object new_purchase = Purchase() new_purchase.user = new_user new_purchase.data_transfer_plan = data_transfer_plan new_purchase.remaining_allowance_frequency = data_transfer_plan.freq new_purchase.selling_shop = selling_shop # purchase.shop_debited = false is by default. new_purchase.save() new_purchase.follow_up_number = generate_md5_hash(str(new_purchase.id)) new_purchase.save() #increase the current index current_index = current_index + 1 bulk_license_manager.current_index = current_index bulk_license_manager.save() return (username,password)
def change_password(request, username): if request.method == 'POST': profile = UserProfile.get_user_profile_from_username(username) # Make sure that the profile exists if profile: user = profile.user else: raise Http404('The username {} does not exist'.format(username)) # Make sure that a user is only able to update his profile and nobody else's. if request.user != user: raise Http404('') change_password_form = ChangePasswordForm(request.POST, request=request) if change_password_form.is_valid(): new_password = change_password_form.cleaned_data.get('new_password') user.set_password(new_password) user.save() return redirect(reverse('view_profile', kwargs={'username': username})) else: raise Http404() raise Http404()
def user_circuit_list(request, user_id): """ Show a list of circuits whos author is request.user, this view assumes that my route is only show when the user is logged in and not anonymous """ circuits_per_page = circuit_settings.DEFAULT_CIRCUITS_LIMIT try: wr_user = User.objects.get(pk=user_id) except User.DoesNotExist: return HttpResponse('No Such Response') try: userprofile = wr_user.userprofile except UserProfile.DoesNotExist: userprofile = UserProfile(user=wr_user) userprofile.save() if request.is_ajax(): page = request.POST.get('page', None) if page is not None: page = int(page) else: return HttpResponse( json.dumps({'error': 'Missing POST parameter: page'}), mimetype='application/json') response = { 'page': int(page) + 1 } circuits = Circuit.objects.filter(author=wr_user ).order_by('published', '-created' )[circuits_per_page * page: circuits_per_page * (page + 1)] if circuits: html_response = u'' for circuit in circuits: html_response += render_to_string( 'circuit/circuit_list_item.html', {'circuit': circuit, 'user': request.user}) response['raw_html'] = html_response else: response['hide_button'] = True return HttpResponse(json.dumps(response), mimetype='application/json') circuits = Circuit.objects.filter( author=wr_user ).order_by('published', '-created')[:circuits_per_page] if request.user.id == int(user_id): own_profile = True else: own_profile = False embed_value = request.GET.get('embed', False) if embed_value not in EMBEDDING_FAIL_VALUES: style = request.GET.get('embedstyle', 'cards') return render(request, 'profile/embedded_circuits.html', { 'domain': settings.SITE_PREFIX, 'style': style, 'circuits': circuits, 'wr_user': wr_user, 'own_profile': own_profile, 'GOOGLE_API_KEY': settings.GOOGLE_API_KEY, }, ) return render(request, 'profile/circuits.html', { 'circuits': circuits, 'wr_user': wr_user, 'own_profile': own_profile, 'STATIC_MAPS_ROOT': settings.STATIC_MAPS_ROOT, 'GOOGLE_API_KEY': settings.GOOGLE_API_KEY, }, )
def user_favorite_routes(request, user_id): """ user_id: id of user to show the profile wr_user: Ushow shoing the display of """ circuits_per_page = circuit_settings.DEFAULT_CIRCUITS_LIMIT try: wr_user = User.objects.get(pk=user_id) except User.DoesNotExist: return HttpResponse('No Such User') try: userprofile = wr_user.userprofile except UserProfile.DoesNotExist: userprofile = UserProfile(user=wr_user) userprofile.save() if request.is_ajax(): page = request.POST.get('page', None) if page is not None: page = int(page) else: return HttpResponse(json.dumps({'error': 'Missing POST parameter: page'}), mimetype='application/json') response = { 'page': int(page) + 1, } circuits = userprofile.favorites.all( )[circuits_per_page * page: circuits_per_page * (page + 1)] if circuits: favs = [x.id for x in favs_circuits] html_response = u'' for circuit in circuits: html_response += render_to_string( 'circuits/circuit_list_item.html', {'circuit': circuit, 'user': request.user}) response['raw_html'] = html_response else: response['hide_button'] = True return HttpResponse(json.dumps(response), mimetype='application/json') fav_circuits = userprofile.favorites.all()[:circuits_per_page] favs = [x.id for x in fav_circuits] if request.user.id == int(user_id): own_profile = True else: own_profile = False return render(request, 'profile/favorites.html', { 'wr_user': wr_user, 'circuits': fav_circuits, 'favs': favs, 'own_profile': own_profile }, )
def show_profile(request, user_id): """ user_id: id of user to show the profile wr_user: User showing the display from """ #wr_user = UserProfile.objects.get(user=user_id) try: wr_user = User.objects.get(pk=user_id) except User.DoesNotExist: return HttpResponse('No Such User') try: userprofile = wr_user.userprofile except UserProfile.DoesNotExist: userprofile = UserProfile(user=wr_user) userprofile.save() followers = userprofile.get_followers() following = userprofile.get_followed_users() fav_circuits = userprofile.favorites.all() favs = [x.id for x in fav_circuits] if request.user.is_authenticated(): if user_id == str(request.user.id): own_profile = True following_wr_user = False else: own_profile = False if request.user in followers: following_wr_user = True else: following_wr_user = False else: following_wr_user = False own_profile = False user_categories = wr_user.categories.all() user_categories_ids = [str(uc.category) for uc in user_categories] circuits = Circuit.objects.filter(author=user_id).all() categories_form = make_categories_form() template_context = { 'wr_user': wr_user, 'followers': followers, 'following': following, 'following_wr_user': following_wr_user, 'own_profile': own_profile, 'sidebar_item': 'profile', 'circuits': circuits, 'favs_circuits': fav_circuits, 'user_categories': user_categories, 'user_categories_ids': user_categories_ids, 'favs': favs, 'categories_form': categories_form, } wr_user_fb = None try: wr_user_fb = UserFacebook.objects.get(user=wr_user) except UserFacebook.DoesNotExist: pass if wr_user_fb: integrator = FacebookIntegrator() fb_data = { 'fb_name': wr_user_fb.name, 'fb_link': wr_user_fb.link, 'fb_picture': \ integrator.get_profile_picture_url(wr_user_fb.facebook_graphid) } template_context['fb_data'] = fb_data wr_user_twitter = None try: wr_user_twitter = UserTwitter.objects.get(user=wr_user) except UserTwitter.DoesNotExist: pass if wr_user_twitter: integrator = TwitterIntegrator() twitter_data = { 'twitter_name': wr_user_twitter.name, 'twitter_screen_name': wr_user_twitter.screen_name, 'twitter_link': wr_user_twitter.link, 'twitter_picture': integrator.get_user_picture( wr_user_twitter.oauth_token_key, wr_user_twitter.oauth_token_secret, # Can set twitter picture size here 'bigger' ) } template_context['twitter_data'] = twitter_data return render(request, "profile/show_profile.html", template_context, )
def import_cdr(shell=False, logger=False): """ Connect to the `import_cdr` Database and import the new CDRs """ count_imported = 0 log_print(logger, shell, "in func import_cdr...") if not check_connection_sql(): log_print(logger, shell, "check_connection_sql - Error Connection") return (False, "Error Connection") # Each time the task is running we will only take CDR_IMPORT_LIMIT records to import # This define the max speed of import, this limit could be changed new_CDRs = CDRImport.objects.using('import_cdr')\ .filter(imported=False)\ .order_by('-id')[:settings.CDR_IMPORT_LIMIT] (list_newcdr, list_cdrid) = ([], []) for call in new_CDRs: # Increment counter count_imported = count_imported + 1 # Get the dialcode dialcode = get_dialcode(call.destination_number, call.dialcode) switch_info = chk_ipaddress(call.switch) # Check Destination number if len(call.destination_number) <= settings.INTERNAL_CALL or call.destination_number[:1].isalpha(): authorized = 1 country_id = None call_type = CALL_TYPE.INTERNAL else: # TODO: rename verify_auth_dest_number verify_auth_dest_number destination_data = verify_auth_dest_number(call.destination_number) authorized = destination_data['authorized'] country_id = destination_data['country_id'] call_type = CALL_TYPE.INTERNATIONAL # Sanitize direction if call.direction: direction = call.direction else: direction = CALL_DIRECTION.NOTDEFINED # Find the user for given accountcode try: user = AccountCode.objects.get(accountcode=call.accountcode).user except: # Cannot assign accountcode to an existing user, therefore we will assign to an Admin user = User.objects.filter(is_superuser=True)[0] try: user_profile = user.userprofile except: user_profile = UserProfile(user=user) user_profile.save() # Retrieve VoipPlan if user_profile: voipplan_id = user_profile.voipplan_id else: voipplan_id = False print_shell(shell, "VoipPlan doesn't exist for this user/accountcode (%s)" % call.accountcode) if call.buy_rate or call.buy_cost or call.sell_rate or call.sell_cost: buy_rate = call.buy_rate buy_cost = call.buy_cost sell_rate = call.sell_rate sell_cost = call.sell_cost elif voipplan_id: call_rate = calculate_call_cost(voipplan_id, call.destination_number, call.billsec) buy_rate = call_rate['buy_rate'] buy_cost = call_rate['buy_cost'] sell_rate = call_rate['sell_rate'] sell_cost = call_rate['sell_cost'] else: buy_rate = buy_cost = sell_rate = sell_cost = 0 hangup_cause_id = get_hangupcause_id(call.hangup_cause_id) log_print(logger, shell, "Create new CDR -> date:%s - dst:%s - duration:%s - hangup_cause:%s - sell_cost:%s" % (call.starting_date, call.destination_number, str(call.duration), str(hangup_cause_id), str(call.sell_cost))) # Create the new CDR newCDR = CDR( user=user, switch=switch_info['switch'], cdr_source_type=call.cdr_source_type, callid=call.callid, caller_id_number=call.caller_id_number, caller_id_name=call.caller_id_name, destination_number=call.destination_number, dialcode_id=dialcode, starting_date=call.starting_date, duration=call.duration, billsec=call.billsec, progresssec=call.progresssec, answersec=call.answersec, waitsec=call.waitsec, hangup_cause_id=hangup_cause_id, direction=direction, country_id=country_id, authorized=authorized, accountcode='' if call.accountcode is None else call.accountcode, buy_rate=buy_rate, buy_cost=buy_cost, sell_rate=sell_rate, sell_cost=sell_cost, call_type=call_type, data='' if call.extradata is None else call.extradata) list_newcdr.append(newCDR) list_cdrid.append(str(call.id)) if (count_imported % 100) == 0: bulk_create_cdrs(list_newcdr, list_cdrid) (list_newcdr, list_cdrid) = ([], []) # we exit the loop but we might still have some remaining CDRs to push if len(list_newcdr) > 0: bulk_create_cdrs(list_newcdr, list_cdrid) (list_newcdr, list_cdrid) = ([], []) log_print(logger, shell, 'TASK :: run_cdr_import -> func import_cdr count_imported:%d' % count_imported) return (True, count_imported)
def profile_tickets(request, username): # Look up the user record who corresponds to this profile profile = UserProfile.get_user_profile_from_username(username) if profile: user = profile.user else: raise Http404('The username {} does not exist'.format(username)) # If the user looking at this profile is its owner, then we want to render a couple edit buttons if request.user == user: is_owner = True else: is_owner = False user_location = user.location most_recent_review = user.most_recent_review() user_info = {'name': user, 'age': user.age(), 'city': user_location.city, 'state': user_location.state, 'rating': user.rating, 'username': username, } try: user_info['profile_picture'] = user.profile_picture except ObjectDoesNotExist: pass if most_recent_review: reviewer_location = most_recent_review.reviewer.location reviewer_city, reviewer_state = reviewer_location.city, reviewer_location.state most_recent_review_info = {'name': most_recent_review.reviewer.get_short_name(), 'age': most_recent_review.reviewer.age(), 'city': reviewer_city, 'state': reviewer_state, 'contents': most_recent_review.contents, 'rating': most_recent_review.rating } else: most_recent_review_info = None # Grab every ticket that this user has posted or has bid on upcoming_tickets = Ticket.upcoming_tickets(user) available_tickets = Ticket.available_tickets(user) in_progress_tickets = Ticket.in_progress_ticket(user) past_tickets = Ticket.past_tickets(user) return render(request, 'user_profile/profile_tickets.html', {'user_info': user_info, 'is_owner': is_owner, 'upcoming_tickets': upcoming_tickets, 'available_tickets': available_tickets, 'in_progress_tickets': in_progress_tickets, 'past_tickets': past_tickets, 'most_recent_review_info': most_recent_review_info, 'form_settings': profile_answer_form_settings, }, content_type='text/html', )
def customer_detail_change(request): """User Detail change on Customer UI **Attributes**: * ``form`` - UserChangeDetailForm, UserChangeDetailExtendForm, PasswordChangeForm, CheckPhoneNumberForm * ``template`` - 'frontend/registration/user_detail_change.html' **Logic Description**: * User is able to change his/her detail. """ user_detail = get_object_or_404(User, username=request.user) try: user_detail_extened = UserProfile.objects.get(user=user_detail) except UserProfile.DoesNotExist: #create UserProfile user_detail_extened = UserProfile(user=user_detail) #DEMO / Disable if not settings.DEMO_MODE: user_detail_extened.save() user_detail_form = UserChangeDetailForm(request.user, instance=user_detail) user_detail_extened_form = \ UserChangeDetailExtendForm(request.user, instance=user_detail_extened) user_password_form = PasswordChangeForm(user=request.user) check_phone_no_form = CheckPhoneNumberForm() try: dialer_set = DialerSetting.objects.get(id=request.user.get_profile().dialersetting_id) except: dialer_set = '' msg_detail = '' msg_pass = '' msg_number = '' error_detail = '' error_pass = '' error_number = '' action = '' if 'action' in request.GET: action = request.GET['action'] if request.method == 'POST': if request.POST['form-type'] == "change-detail": user_detail_form = UserChangeDetailForm( request.user, request.POST, instance=user_detail) user_detail_extened_form = \ UserChangeDetailExtendForm( request.user, request.POST, instance=user_detail_extened) action = 'tabs-1' if (user_detail_form.is_valid() and user_detail_extened_form.is_valid()): #DEMO / Disable if not settings.DEMO_MODE: user_detail_form.save() user_detail_extened_form.save() msg_detail = _('detail has been changed.') else: error_detail = _('please correct the errors below.') elif request.POST['form-type'] == "check-number": # check phone no action = 'tabs-4' check_phone_no_form = CheckPhoneNumberForm(data=request.POST) if check_phone_no_form.is_valid(): if not common_contact_authorization(request.user, request.POST['phone_number']): error_number = _('this phone number is not authorized.') else: msg_number = _('this phone number is authorized.') else: error_number = _('please correct the errors below.') else: # "change-password" user_password_form = PasswordChangeForm(user=request.user, data=request.POST) action = 'tabs-2' if user_password_form.is_valid(): #DEMO / Disable if not settings.DEMO_MODE: user_password_form.save() msg_pass = _('your password has been changed.') else: error_pass = _('please correct the errors below.') template = 'frontend/registration/user_detail_change.html' data = { 'module': current_view(request), 'user_detail_form': user_detail_form, 'user_detail_extened_form': user_detail_extened_form, 'user_password_form': user_password_form, 'check_phone_no_form': check_phone_no_form, 'msg_detail': msg_detail, 'msg_pass': msg_pass, 'msg_number': msg_number, 'error_detail': error_detail, 'error_pass': error_pass, 'error_number': error_number, 'dialer_set': dialer_set, 'dialer_setting_msg': user_dialer_setting_msg(request.user), 'action': action, } return render_to_response(template, data, context_instance=RequestContext(request))
def view_ticket(request, username, ticket_id): """ View the details for a particular ticket. This view allows us to message the user or buy the ticket from him. """ user = request.user # Look up the user record who corresponds to this profile profile = UserProfile.get_user_profile_from_username(username) if profile: profile_user = profile.user else: raise Http404('The username {} does not exist.'.format(username)) # Make sure that ticket exists try: ticket = Ticket.objects.get(pk=ticket_id) except Ticket.DoesNotExist: raise Http404() # Make sure that the username entered is the actual poster of this ticket if ticket.poster != profile_user: raise Http404('{} did not post that ticket.'.format(profile_user.user_profile.username)) if not ticket.can_view(): raise Http404('It looks like this page no longer exists. The user probably cancelled their ticket.') # If the user looking at this profile is its owner, then we want to render a couple edit buttons if user == profile_user: is_owner = True else: is_owner = False user_location = profile_user.location most_recent_review = profile_user.most_recent_review() user_info = {'name': profile_user, 'age': profile_user.age(), 'city': user_location.city, 'state': user_location.state, 'rating': profile_user.rating, 'username': username, 'user_id': profile_user.id, 'email': profile_user.email } try: user_info['profile_picture'] = profile_user.profile_picture except ObjectDoesNotExist: pass if most_recent_review: reviewer_location = most_recent_review.reviewer.location reviewer_city, reviewer_state = reviewer_location.city, reviewer_location.state most_recent_review_info = {'name': most_recent_review.reviewer.get_short_name(), 'age': most_recent_review.reviewer.age(), 'city': reviewer_city, 'state': reviewer_state, 'contents': most_recent_review.contents, 'rating': most_recent_review.rating } else: most_recent_review_info = None return render(request, 'user_profile/view_ticket.html', {'user_info': user_info, 'is_owner': is_owner, 'ticket': ticket, 'most_recent_review_info': most_recent_review_info, 'stripe_public_api_key': settings.STRIPE_PUBLIC_API_KEY, 'has_request': Request.has_requested(ticket, user.id), # We pass in user.id because otherwise the # if the user is anonymous, it would be a # SimpleLazyObject, and Django would error out 'ticket_status': ticket.status, }, content_type='text/html', )
def customer_detail_change(request): """User Detail change on Customer UI **Attributes**: * ``form`` - UserChangeDetailForm, UserChangeDetailExtendForm, UserPasswordChangeForm * ``template`` - 'user_profile/user_detail_change.html' **Logic Description**: * User is able to change their details. """ user_detail = get_object_or_404(User, username=request.user) try: user_detail_extened = UserProfile.objects.get(user=user_detail) except UserProfile.DoesNotExist: # create UserProfile user_detail_extened = UserProfile(user=user_detail) # DEMO / Disable if not settings.DEMO_MODE: user_detail_extened.save() user_detail_form = UserChangeDetailForm(request.user, instance=user_detail) user_detail_extened_form = UserChangeDetailExtendForm(request.user, instance=user_detail_extened) user_password_form = UserPasswordChangeForm(user=request.user) msg_detail = '' msg_pass = '' error_detail = '' error_pass = '' action = '' if 'action' in request.GET: action = request.GET['action'] if request.method == 'POST': if request.POST['form-type'] == "change-detail": user_detail_form = UserChangeDetailForm(request.user, request.POST, instance=user_detail) user_detail_extened_form = UserChangeDetailExtendForm(request.user, request.POST, instance=user_detail_extened) action = 'tabs-1' if user_detail_form.is_valid() and user_detail_extened_form.is_valid(): # DEMO / Disable if not settings.DEMO_MODE: user_detail_form.save() user_detail_extened_form.save() msg_detail = _('detail has been changed.') else: error_detail = _('please correct the errors below.') else: # change-password user_password_form = UserPasswordChangeForm(user=request.user, data=request.POST) action = 'tabs-2' if user_password_form.is_valid(): # DEMO / Disable if not settings.DEMO_MODE: user_password_form.save() msg_pass = _('your password has been changed.') else: error_pass = _('please correct the errors below.') data = { 'user_detail_form': user_detail_form, 'user_detail_extened_form': user_detail_extened_form, 'user_password_form': user_password_form, 'msg_detail': msg_detail, 'msg_pass': msg_pass, 'error_detail': error_detail, 'error_pass': error_pass, 'action': action, } return render_to_response('user_profile/user_detail_change.html', data, context_instance=RequestContext(request))
def customer_detail_change(request): """User Detail change on Customer UI **Attributes**: * ``form`` - UserChangeDetailForm, UserChangeDetailExtendForm, PasswordChangeForm * ``template`` - 'cdr/registration/user_detail_change.html' **Logic Description**: * User is able to change his/her detail. """ if not request.user.is_superuser: # not superuser if not chk_account_code(request): return HttpResponseRedirect('/?acc_code_error=true') user_detail = User.objects.get(username=request.user) try: user_detail_extened = UserProfile.objects.get(user=user_detail) except UserProfile.DoesNotExist: #create UserProfile user_detail_extened = UserProfile(user=user_detail) user_detail_extened.save() user_detail_form = UserChangeDetailForm(request.user, instance=user_detail) user_detail_extened_form = UserChangeDetailExtendForm(request.user, instance=user_detail_extened) user_password_form = PasswordChangeForm(user=request.user) check_phone_no_form = CheckPhoneNumberForm() try: user_ds = UserProfile.objects.get(user=request.user) except: dialer_set = '' # Define no of records per page PAGE_SIZE = settings.PAGE_SIZE try: PAGE_NUMBER = int(request.GET['page']) except: PAGE_NUMBER = 1 col_name_with_order = {} # default col_name_with_order['message'] = '-message' col_name_with_order['notice_type'] = '-notice_type' col_name_with_order['sender'] = '-sender' col_name_with_order['added'] = '-added' sort_field = variable_value(request, 'sort_by') if not sort_field: sort_field = 'message' # default sort field sort_order = '-' + sort_field # desc else: if "-" in sort_field: sort_order = sort_field col_name_with_order[sort_field] = sort_field[1:] else: sort_order = sort_field col_name_with_order[sort_field] = '-' + sort_field user_notification = \ notification.Notice.objects.filter(recipient=request.user) # Search on sender name q = (Q(sender=request.user)) if q: user_notification = user_notification.filter(q) user_notification = user_notification.order_by(sort_order) msg_detail = '' msg_pass = '' msg_number = '' msg_note = '' error_detail = '' error_pass = '' error_number = '' action = '' if 'action' in request.GET: action = request.GET['action'] if request.GET.get('msg_note') == 'true': msg_note = request.session['msg_note'] # Mark all notification as read if request.GET.get('notification') == 'mark_read_all': notification_list = notification.Notice.objects.filter(unseen=1, recipient=request.user) notification_list.update(unseen=0) msg_note = _('All notifications are marked as read.') if request.method == 'POST': if request.POST['form-type'] == "change-detail": user_detail_form = UserChangeDetailForm(request.user, request.POST, instance=user_detail) user_detail_extened_form = UserChangeDetailExtendForm(request.user, request.POST, instance=user_detail_extened) action = 'tabs-1' if user_detail_form.is_valid() and user_detail_extened_form.is_valid(): user_detail_form.save() user_detail_extened_form.save() msg_detail = _('Detail has been changed.') else: error_detail = _('Please correct the errors below.') else: # "change-password" user_password_form = PasswordChangeForm(user=request.user, data=request.POST) action = 'tabs-2' if user_password_form.is_valid(): user_password_form.save() msg_pass = _('Your password has been changed.') else: error_pass = _('Please correct the errors below.') template = 'cdr/registration/user_detail_change.html' data = { 'module': current_view(request), 'user_detail_form': user_detail_form, 'user_detail_extened_form': user_detail_extened_form, 'user_password_form': user_password_form, 'user_notification': user_notification, 'PAGE_SIZE': PAGE_SIZE, 'msg_detail': msg_detail, 'msg_pass': msg_pass, 'msg_note': msg_note, 'error_detail': error_detail, 'error_pass': error_pass, 'notice_count': notice_count(request), 'action': action, 'col_name_with_order': col_name_with_order, } return render_to_response(template, data, context_instance=RequestContext(request))
def customer_detail_change(request): """User Detail change on Customer UI **Attributes**: * ``form`` - UserChangeDetailForm, UserChangeDetailExtendForm, PasswordChangeForm, CheckPhoneNumberForm * ``template`` - 'frontend/registration/user_detail_change.html' **Logic Description**: * User is able to change his/her detail. """ user_detail = User.objects.get(username=request.user) try: user_detail_extened = UserProfile.objects.get(user=user_detail) except UserProfile.DoesNotExist: # create UserProfile user_detail_extened = UserProfile(user=user_detail) user_detail_extened.save() user_detail_form = UserChangeDetailForm(request.user, instance=user_detail) user_detail_extened_form = UserChangeDetailExtendForm(request.user, instance=user_detail_extened) user_password_form = PasswordChangeForm(user=request.user) check_phone_no_form = CheckPhoneNumberForm() try: user_ds = UserProfile.objects.get(user=request.user) dialer_set = DialerSetting.objects.get(id=user_ds.dialersetting.id) except: dialer_set = "" user_notification = notification.Notice.objects.filter(recipient=request.user) # Search on sender name q = Q(sender=request.user) if q: user_notification = user_notification.filter(q) msg_detail = "" msg_pass = "" msg_number = "" msg_note = "" error_detail = "" error_pass = "" error_number = "" action = "" if "action" in request.GET: action = request.GET["action"] if request.GET.get("msg_note") == "true": msg_note = request.session["msg_note"] # Mark all notification as read if request.GET.get("notification") == "mark_read_all": notification_list = notification.Notice.objects.filter(unseen=1, recipient=request.user) notification_list.update(unseen=0) msg_note = _("All notifications are marked as read.") if request.method == "POST": if request.POST["form-type"] == "change-detail": user_detail_form = UserChangeDetailForm(request.user, request.POST, instance=user_detail) user_detail_extened_form = UserChangeDetailExtendForm( request.user, request.POST, instance=user_detail_extened ) action = "tabs-1" if user_detail_form.is_valid() and user_detail_extened_form.is_valid(): user_detail_form.save() user_detail_extened_form.save() msg_detail = _("Detail has been changed.") else: error_detail = _("Please correct the errors below.") elif request.POST["form-type"] == "check-number": # check phone no action = "tabs-5" check_phone_no_form = CheckPhoneNumberForm(data=request.POST) if check_phone_no_form.is_valid(): if not common_contact_authorization(request.user, request.POST["phone_number"]): error_number = _("This phone number is not authorized.") else: msg_number = _("This phone number is authorized.") else: error_number = _("Please correct the errors below.") else: # "change-password" user_password_form = PasswordChangeForm(user=request.user, data=request.POST) action = "tabs-2" if user_password_form.is_valid(): user_password_form.save() msg_pass = _("Your password has been changed.") else: error_pass = _("Please correct the errors below.") template = "frontend/registration/user_detail_change.html" data = { "module": current_view(request), "user_detail_form": user_detail_form, "user_detail_extened_form": user_detail_extened_form, "user_password_form": user_password_form, "check_phone_no_form": check_phone_no_form, "user_notification": user_notification, "msg_detail": msg_detail, "msg_pass": msg_pass, "msg_number": msg_number, "msg_note": msg_note, "error_detail": error_detail, "error_pass": error_pass, "error_number": error_number, "notice_count": notice_count(request), "dialer_set": dialer_set, "dialer_setting_msg": user_dialer_setting_msg(request.user), "action": action, } return render_to_response(template, data, context_instance=RequestContext(request))
def customer_detail_change(request): """User Detail change on Customer UI **Attributes**: * ``form`` - UserChangeDetailForm, UserChangeDetailExtendForm, PasswordChangeForm, CheckPhoneNumberForm * ``template`` - 'frontend/registration/user_detail_change.html' **Logic Description**: * User is able to change his/her detail. """ user_detail = User.objects.get(username=request.user) try: user_detail_extened = UserProfile.objects.get(user=user_detail) except UserProfile.DoesNotExist: #create UserProfile user_detail_extened = UserProfile(user=user_detail) user_detail_extened.save() user_detail_form = UserChangeDetailForm(request.user, instance=user_detail) user_detail_extened_form = UserChangeDetailExtendForm(request.user, instance=user_detail_extened) user_password_form = PasswordChangeForm(user=request.user) check_phone_no_form = CheckPhoneNumberForm() try: user_ds = UserProfile.objects.get(user=request.user) dialer_set = DialerSetting.objects.get(id=user_ds.dialersetting.id) except: dialer_set = '' user_notification = \ notification.Notice.objects.filter(recipient=request.user) # Search on sender name q = (Q(sender=request.user)) if q: user_notification = user_notification.filter(q) msg_detail = '' msg_pass = '' msg_number = '' msg_note = '' error_detail = '' error_pass = '' error_number = '' action = '' if 'action' in request.GET: action = request.GET['action'] if request.GET.get('msg_note') == 'true': msg_note = request.session['msg_note'] # Mark all notification as read if request.GET.get('notification') == 'mark_read_all': notification_list = notification.Notice.objects.filter(unseen=1, recipient=request.user) notification_list.update(unseen=0) msg_note = _('All notifications are marked as read.') if request.method == 'POST': if request.POST['form-type'] == "change-detail": user_detail_form = UserChangeDetailForm(request.user, request.POST, instance=user_detail) user_detail_extened_form = UserChangeDetailExtendForm(request.user, request.POST, instance=user_detail_extened) action = 'tabs-1' if user_detail_form.is_valid() and user_detail_extened_form.is_valid(): user_detail_form.save() user_detail_extened_form.save() msg_detail = _('Detail has been changed.') else: error_detail = _('Please correct the errors below.') elif request.POST['form-type'] == "check-number": # check phone no action = 'tabs-5' check_phone_no_form = CheckPhoneNumberForm(data=request.POST) if check_phone_no_form.is_valid(): if not common_contact_authorization(request.user, request.POST['phone_number']): error_number = _('This phone number is not authorized.') else: msg_number = _('This phone number is authorized.') else: error_number = _('Please correct the errors below.') else: # "change-password" user_password_form = PasswordChangeForm(user=request.user, data=request.POST) action = 'tabs-2' if user_password_form.is_valid(): user_password_form.save() msg_pass = _('Your password has been changed.') else: error_pass = _('Please correct the errors below.') template = 'frontend/registration/user_detail_change.html' data = { 'module': current_view(request), 'user_detail_form': user_detail_form, 'user_detail_extened_form': user_detail_extened_form, 'user_password_form': user_password_form, 'check_phone_no_form': check_phone_no_form, 'user_notification': user_notification, 'msg_detail': msg_detail, 'msg_pass': msg_pass, 'msg_number': msg_number, 'msg_note': msg_note, 'error_detail': error_detail, 'error_pass': error_pass, 'error_number': error_number, 'notice_count': notice_count(request), 'dialer_set': dialer_set, 'dialer_setting_msg': user_dialer_setting_msg(request.user), 'action': action, } return render_to_response(template, data, context_instance=RequestContext(request))
def save_form(form): user = User.objects.create_user(form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password']) user_prof = UserProfile(user=user, address=form.cleaned_data['address'], phone_number=form.cleaned_data['phone_number']) user_prof.save()
def testUserProfile(self): obj = UserProfile(user_id=1, address='xyz', city='abc') obj.save() self.assertEquals(1, obj.user_id) self.assertNotEquals(obj.id, None) obj.delete()
def customer_detail_change(request): """User Detail change on Customer UI **Attributes**: * ``form`` - UserChangeDetailForm, UserChangeDetailExtendForm, PasswordChangeForm * ``template`` - 'frontend/registration/user_detail_change.html' **Logic Description**: * User is able to change their details. """ if not request.user.is_superuser: # not superuser if not chk_account_code(request): return HttpResponseRedirect("/?acc_code_error=true") user_detail = get_object_or_404(User, username=request.user) try: user_detail_extened = UserProfile.objects.get(user=user_detail) except UserProfile.DoesNotExist: # create UserProfile user_detail_extened = UserProfile(user=user_detail) user_detail_extened.save() user_detail_form = UserChangeDetailForm(request.user, instance=user_detail) user_detail_extened_form = UserChangeDetailExtendForm(request.user, instance=user_detail_extened) user_password_form = PasswordChangeForm(user=request.user) msg_detail = "" msg_pass = "" error_detail = "" error_pass = "" action = "" if "action" in request.GET: action = request.GET["action"] if request.method == "POST": if request.POST["form-type"] == "change-detail": user_detail_form = UserChangeDetailForm(request.user, request.POST, instance=user_detail) user_detail_extened_form = UserChangeDetailExtendForm( request.user, request.POST, instance=user_detail_extened ) action = "tabs-1" if user_detail_form.is_valid() and user_detail_extened_form.is_valid(): user_detail_form.save() user_detail_extened_form.save() msg_detail = _("Detail has been changed.") else: error_detail = _("Please correct the errors below.") else: # change-password user_password_form = PasswordChangeForm(user=request.user, data=request.POST) action = "tabs-2" if user_password_form.is_valid(): user_password_form.save() msg_pass = _("Your password has been changed.") else: error_pass = _("Please correct the errors below.") template = "frontend/registration/user_detail_change.html" data = { "module": current_view(request), "user_detail_form": user_detail_form, "user_detail_extened_form": user_detail_extened_form, "user_password_form": user_password_form, "msg_detail": msg_detail, "msg_pass": msg_pass, "error_detail": error_detail, "error_pass": error_pass, "notice_count": notice_count(request), "action": action, } return render_to_response(template, data, context_instance=RequestContext(request))