def register(request): """This view handles user registration.""" form = UserRegistrationForm(request.POST or None) if form.is_valid(): user = User.objects.create_user(username=form.cleaned_data["username"], email=form.cleaned_data["email"], password=form.cleaned_data["password1"], ) user.first_name = form.cleaned_data["first_name"] user.last_name = form.cleaned_data["last_name"] user.save() # XXX: email i18n?! email_subject = "Registration for %s" % settings.SITE_NAME email_body = ("A new user has registered for %s.\n" "username: %s\n" "email: %s\n" "first_name: %s\n" "last_name: %s\n" % \ (settings.SITE_NAME, form.cleaned_data["username"], form.cleaned_data["email"], form.cleaned_data["first_name"], form.cleaned_data["last_name"])) email_message = EmailMessage(subject=email_subject, body=email_body, from_email=settings.WEB_EMAIL, to=[admin[1] for admin in settings.ADMINS], headers={"Reply-To":settings.NOREPLY_EMAIL}) email_message.send() return redirect("/register_success") c = {"form":form} c.update(csrf(request)) c.update(locals()) return render_to_response("register.html", c, context_instance=RequestContext(request))
def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): # Create a new user object but avoid saving it yet new_user = form.save(commit=False) # Set the chosen password new_user.set_password( form.cleaned_data['password']) # Save the User object new_user.save() profile = Profile(user=new_user) profile.save() # 記錄系統事件 if is_event_open(request) : log = Log(user_id=new_user.id, event='註冊帳號成功') log.save() # create Message title = "請洽詢任課教師課程名稱及選課密碼" url = "/student/classroom/add" message = Message.create(title=title, url=url, time=timezone.now()) message.save() # message for group member messagepoll = MessagePoll.create(message_id = message.id,reader_id=new_user.id) messagepoll.save() return render(request, 'account/register_done.html', {'new_user': new_user}) else: form = UserRegistrationForm() return render(request, 'account/register.html', {'form': form})
def add_user(): stringvalue=["Already Have an Account", "Sign in", "User", "Admin Singin", "admin_login",] form = UserRegistrationForm() if not form.validate_on_submit(): flash('please enter valid user details') else: entrynumber = form.entryNumber.data name = form.name.data password = form.password.data emailid = form.emailId.data if request.method == 'POST' and userNotAvailabe(entrynumber) and len(entrynumber)>4 and len(name) > 3 and len(password) > 7 and '@' in emailid and not pendingAvailable(entrynumber): insertstmt = "insert into pending values ('{}', '{}', '{}', '{}',{},{},{});".format(entrynumber, name, password, emailid,0,0,0) cursor.execute(insertstmt) connection.commit() flash("Please wait till confirmation") return redirect(url_for('login_user')) elif request.method=='POST' and len(entrynumber) < 6: flash('length of userid is too sort at least 7 char') elif request.method=='POST' and len(name) < 4: flash('length of name is too sort') elif request.method=='POST' and len(password) < 8: flash('Please enter at least 8 word password') elif request.method=='POST' and ('@' not in emailid): flash('Please enter valid email id') elif request.method=='POST' and pendingAvailable(entrynumber): flash("Already signup....Please wait till confirmation") elif request.method=='POST' and not userNotAvailabe(entrynumber): flash("Userid Already taken please try different userid") return render_template('register.html',title='Register',form=form, stringvalue=stringvalue)
def user_registration(): """User Registration Page""" form = UserRegistrationForm() if form.validate_on_submit(): username = form.username.data password = form.password.data email = form.email.data first_name = form.first_name.data last_name = form.last_name.data zip_code = form.zip_code.data new_user = User.register(username, password, email, first_name, last_name, zip_code) db.session.add(new_user) try: db.session.commit() except IntegrityError: form.username.errors.append("Username is taken") return render_template('users/register.html', form=form) session["username"] = new_user.username # Keeps user logged in flash(f"Welcome {first_name}, we successfully created your account!", "success") return redirect('/') else: return render_template('users/register.html', form=form)
def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): form.save() user = auth.authenticate(email=request.POST.get('email'), password=request.POST.get('password1')) if user: auth.login(request, user) messages.success(request, "You have successfully registered") return redirect(reverse('profile')) else: messages.error(request, "unable to log you in at this time!!!") else: return render(request, 'register.html', {'form': form}) else: args = {} args.update(csrf(request)) args['form'] = UserRegistrationForm() return render(request, 'register.html', args)
def register(): form = UserRegistrationForm() pprint (form) if form.validate_on_submit(): app.logger.debug(""" username:{username}\n password:{password}\n email:{email}\n first_name:{first_name}\n last_name:{last_name}\n""".format(username=form.username.data, password=form.password.data, email=form.email.data, first_name=form.first_name.data, last_name=form.last_name.data)) user = models.User(username=form.username.data, password=form.password.data, email=form.email.data, first_name=form.first_name.data, last_name=form.last_name.data) user.save() #TODO: Exception handling return render_template('user-registration.html', form=form, user=user, registration='success') return render_template('base-bootstrap.html', web_content_marketing=web_content.marketing_content, web_content_ui=web_content.ui_elements, form=form, username='******')
def user_register(request, template_name="users/user_registration.html"): registration_form = UserRegistrationForm() if request.method == 'POST': registration_form = UserRegistrationForm(request.POST) if registration_form.is_valid(): user = registration_form.save() # generate random activation code random.seed() code = random.getrandbits(128) activation = UserActivationCode(user=user, code=code) activation.save() code_url = reverse('user_activation', args=[code]) activation_url = "http://%s%s" % (SITE_DOMAIN, code_url) send_mail(ACTIVATION_MAIL_SUBJECT, ACTIVATION_MAIL_CONTENT % activation_url, GAE_MAIL_ACCOUNT, [user.email]) return direct_to_template(request, "users/user_registration_confirm.html") extra_context = { 'registration_form': registration_form } return direct_to_template(request, template_name, extra_context=extra_context)
def add_user(request): username = request.POST.get("username") email = request.POST.get("emailid") password = request.POST.get("password") fname = request.POST.get("fname") lname = request.POST.get("lname") address = request.POST.get("address") phone = request.POST.get("phone") tech = request.POST.get("tech") print('.........address........', address) if request.method == 'GET': print('get here') form = UserRegistrationForm() # object creation else: print('form in post') form = UserRegistrationForm(request.POST) if form.is_valid(): print('user registration from valid') user = User.objects.create_user(username, email, password) user.first_name = fname user.last_name = lname user.save() a = UserProfile(user_id=user.id, address=address, phone=phone, tech=tech) a.save() print('saved') return HttpResponseRedirect('/homepage/') return render(request, 'registration.html', { 'form': form, })
def user_registration(): form = UserRegistrationForm() if form.validate_on_submit(): app.logger.debug(""" username:{username}\n password:{password}\n email:{email}\n first_name:{first_name}\n last_name:{last_name}\n""".format(username=form.username.data, password=form.password.data, email=form.email.data, first_name=form.first_name.data, last_name=form.last_name.data)) user = models.User(username=form.username.data, password=form.password.data, email=form.email.data, first_name=form.first_name.data, last_name=form.last_name.data) user.save() #TODO: Exception handling return render_template('user-registration.html', form=form, user=user, registration='success') return render_template('user-registration.html', form=form, registration='new')
def test_registration_form(self): form = UserRegistrationForm({ 'email': '*****@*****.**', 'password1': 'tester33', 'password2': 'tester33', }) self.assertTrue(form.is_valid())
def register(): """ Take care of user registration by either sending them the form, or registering them and signing them in. :return: """ form = UserRegistrationForm() if request.method == 'POST': if not form.validate(): # If the form isn't properly validated, return a json saying why return jsonify( { 'success': False, 'errors': form.errors } ) new_user = User( firstname=form.name.data, lastname=form.surname.data, email=form.email.data, username=form.username.data, ) new_user.set_password(password=form.password.data) db.session.add(new_user) db.session.commit() return redirect(url_for('login'), code=307) return render_template('register-form.html', form=form)
def test_registration_form_success(self): form = UserRegistrationForm({ 'email': '*****@*****.**', 'public_name': 'test name 1', 'password1': 'testpassword1', 'password2': 'testpassword1' }) self.assertTrue(form.is_valid())
def test_registration_form_password_missing(self): form = UserRegistrationForm({ 'email': '*****@*****.**', 'password1': 'tester40', }) self.assertFalse(form.is_valid()) self.assertRaisesMessage(forms.ValidationError, "Second Password is missing", form.full_clean())
def test_registration_form_fails_with_missing_password2(self): form = UserRegistrationForm({ 'email': '*****@*****.**', 'public_name': 'test name 4', 'password1': 'testpassword1' }) self.assertFalse(form.is_valid()) self.assertRaisesMessage(forms.ValidationError, "Passwords do not match", form.full_clean())
def test_registration_form(self): form = UserRegistrationForm({ 'username': '******', 'email': '*****@*****.**', 'password1': 'letmein1', 'password2': 'letmein1', }) self.assertTrue(form.is_valid())
def test_registration_form_passwords_not_matching(self): form = UserRegistrationForm({ 'email': '*****@*****.**', 'password1': 'tester38', 'password2': 'tester39', }) self.assertFalse(form.is_valid()) self.assertRaisesMessage(forms.ValidationError, "Passwords do not match", form.full_clean())
def test_registration_form_missing_email(self): form = UserRegistrationForm({ 'password1': 'test35', 'password2': 'test35', }) self.assertFalse(form.is_valid()) self.assertRaisesMessage(forms.ValidationError, "Please enter your email address", form.full_clean())
def test_registration_form_fails_wih_passwords_that_dont_match(self): form = UserRegistrationForm({ 'username': '******', 'email': '*****@*****.**', 'password1': 'testing1', 'password2': 'testing2' }) self.assertFalse(form.is_valid()) self.assertRaisesMessage(forms.ValidationError, "Passwords do not match", form.full_clean())
def test_registration_form_fails_with_missing_password(self): form = UserRegistrationForm({ 'username': '******', 'email': '*****@*****.**', 'password1': 'letmein1', }) self.assertFalse(form.is_valid()) self.assertRaisesMessage(forms.ValidationError, "please enter both passwords", form.full_clean())
def test_registration_form_fails_with_missing_public_name(self): form = UserRegistrationForm({ 'email': '*****@*****.**', 'password1': 'testpassword1', 'password2': 'testpassword1' }) self.assertFalse(form.is_valid()) self.assertRaisesMessage(forms.ValidationError, "Please fill in this field", form.full_clean())
def registration_view(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) userprofile_form = UserProfileRegistrationForm(request.POST) if user_form.is_valid() and userprofile_form.is_valid(): user = user_form.save(commit=False) user.is_active = False new_profile = userprofile_form.save(commit=False) #attempt = try_user_sending(request, u'Невозможно завершить регистрацию', settings.STORAGE_CREATE_USER_HOST, # user=user) #if attempt: # if something went wrong # return attempt user.save() salt = hashlib.sha1(str(random.random())).hexdigest()[:5] activation_key = hashlib.sha1(salt + user.email).hexdigest() new_profile.user = user new_profile.activation_key = activation_key activation_link = u'{}/accounts/confirm/{}'.format(request.get_host(), activation_key) email_subject = '[Томограф] Подтверждение регистрации' email_body = u"Приветствуем Вас на сайте Robo-Tom, {}!\n\ Для активации аккаунта пройдите по следующей ссылке: {}".format(user.username, activation_link) try: send_mail(email_subject, email_body, '*****@*****.**', [user.email], fail_silently=False) except BaseException as e: import traceback main_logger.error(traceback.print_exc()) main_logger.error(e) messages.warning(request, 'Произошла ошибка при отправке письма о подтверждении регистрации. Попробуйте \ зарегистрироваться повторно, указав корректный email') else: messages.success(request, 'На указанный Вами адрес было отправлено письмо. Для завершения регистрации и \ подтверждения адреса перейдите по ссылке, указанной в письме') new_profile.save() userprofile_form.save_m2m() return redirect(reverse('main:done')) else: return render(request, 'registration/registration_form.html', { 'user_form': user_form, 'userprofile_form': userprofile_form, 'caption': 'Регистрация' }) return render(request, 'registration/registration_form.html', { 'user_form': UserRegistrationForm(), 'userprofile_form': UserProfileRegistrationForm(), 'caption': 'Регистрация' })
def test_form_is_valid(self): form = UserRegistrationForm({ 'username': '******', 'email': '*****@*****.**', 'password1': 'letmein1', 'password2': 'letmein1', 'first_name': 'test', 'last_name': 'test', 'company': 'test' }) self.assertTrue(form.is_valid())
def register_view(request): if request.method=="POST": form = UserRegistrationForm(request.POST) if form.is_valid(): new_user = User.objects.create_user(**form.cleaned_data) username = request.POST.get('username') password = request.POST.get('password') print "username:"******"password",password return login_user(request, username, password) else: form = UserRegistrationForm() return render(request, 'ncqs/register.html', {'form':form})
def test_form_fails_when_missing_password2(self): form = UserRegistrationForm({ 'username': '******', 'email': '*****@*****.**', 'password1': 'letmein1', 'first_name': 'test', 'last_name': 'test', 'company': 'test' }) self.assertFalse(form.is_valid()) self.assertRaisesMessage(forms.ValidationError, "Please confirm your password")
def register_view(request): if request.method == "POST": form = UserRegistrationForm(request.POST) if form.is_valid(): new_user = User.objects.create_user(**form.cleaned_data) username = request.POST.get('username') password = request.POST.get('password') print "username:"******"password", password return login_user(request, username, password) else: form = UserRegistrationForm() return render(request, 'ncqs/register.html', {'form': form})
def test_form_fails_when_password_not_letters(self): form = UserRegistrationForm({ 'username': '******', 'email': '*****@*****.**', 'password1': '12345678', 'password2': '12345678', 'first_name': 'test', 'last_name': 'test', 'company': 'test' }) self.assertFalse(form.is_valid()) self.assertRaisesMessage(forms.ValidationError, "Password must contain at least 1 letter")
def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): form = None else: form = UserRegistrationForm() return render_to_response( 'users/register.html', RequestContext(request, { 'form': form, 'page': 'register' }) )
def test_form_fails_when_password_dont_match(self): form = UserRegistrationForm({ 'username': '******', 'email': '*****@*****.**', 'password1': 'letmein1', 'password2': 'letmein2', 'first_name': 'test', 'last_name': 'test', 'company': 'test' }) self.assertFalse(form.is_valid()) self.assertRaisesMessage(forms.ValidationError, "Passwords do not match")
def register_user(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/register_success') args = {} args.update(csrf(request)) args['form'] = UserRegistrationForm() return render_to_response('register.html', args)
def test_registration_form(self): form = UserRegistrationForm({ 'email': '*****@*****.**', 'password1': 'letmein1', 'password2': 'letmein1', 'stripe_id': settings.STRIPE_SECRET, 'credit_card_number': 4242424242424242, 'cvv': 123, 'expiry_month': 1, 'expiry_year': 2033 }) self.assertTrue(form.is_valid())
def test_form_fails_when_password_too_short(self): form = UserRegistrationForm({ 'username': '******', 'email': '*****@*****.**', 'password1': 'letme', 'password2': 'letme', 'first_name': 'test', 'last_name': 'test', 'company': 'test' }) self.assertFalse(form.is_valid()) self.assertRaisesMessage(forms.ValidationError, "Password must be at least 8 characters long")
def post(self): form = UserRegistrationForm() if form.validate_on_submit(): u = User() returnvalue = u.UserRegistration(form.username.data, form.email.data, form.password.data, 'U') if returnvalue: return make_response(render_template_string(returnvalue)) return make_response( render_template_string( "<p>There is Already An User With That Username or Email</p>" "<small class='text-muted'><a href = '/register'>Register</a></small>" ))
def register(): # caricamento dati provenienti dal form if request.method == 'POST': if request.form['password'] != request.form['confirm_password']: flash('Le password inserite sono diverse!') return redirect(url_for('auth.register')) form = UserRegistrationForm(request.form) # per il check del form devo guardare anche le tariffe tariffe = Tariffa.query(Tariffa.visibilita == True).order( Tariffa.order).fetch() my_choices = [] for i, tar in enumerate(tariffe): my_choices.append((str(i + 1), tar.tariffa)) form.tariffa.choices = my_choices # check form if form.validate(): if insert_user(form): return render_template('login/not_allowed.html') else: flash('Registration error!') return redirect(url_for('auth.register')) # caricamento vista registrazione elif request.method == 'GET': form = UserRegistrationForm() # aggiunta tariffe possibili tariffe = Tariffa.query(Tariffa.visibilita == True).order( Tariffa.order).fetch() my_choices = [] for i, tar in enumerate(tariffe): my_choices.append((str(i + 1), tar.tariffa)) form.tariffa.choices = my_choices if len(tariffe) > 0: return render_template( 'login/registration.html', form=form, len=len(tariffe), nomi_tariffe=[tar.tariffa for tar in tariffe], prezzo_tariffe=[tar.prezzo for tar in tariffe], descr_tariffe=[tar.description for tar in tariffe]) else: return render_template('login/registration.html', form=form, len=1, nomi_tariffe=["Non ci sono tariffe."], descr_tariffe=["Tutti gratis, paliazzu!!"])
def register(request): if request.method == 'POST': urf = UserRegistrationForm(request.POST) if(urf.is_valid()): urf.save() return redirect('home') else: print(urf.errors) context = RequestContext(request) context['urf'] = urf return render_to_response('register.html', context) else: return HttpResponseNotAllowed('POST requests only')
def test_registration_form_fails_wih_passwords_that_dont_match(self): form = UserRegistrationForm({ 'email': '*****@*****.**', 'password1': 'letmein1', 'password2': 'letmein2', 'stripe_id': settings.STRIPE_SECRET, 'credit_card_number': 4242424242424242, 'cvv': 123, 'expiry_month': 1, 'expiry_year': 2033 }) self.assertFalse(form.is_valid()) self.assertRaisesMessage(forms.ValidationError, "Passwords do not match", form.full_clean())
def registration(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): # Hash the password. print form.cleaned_data newUser = form.instance newUser.password = make_password(newUser.password) newUser.email = newUser.username newUser.save() return HttpResponseRedirect('/') else: form = UserRegistrationForm() return render(request, 'registration.html', {'form': form})
def test_registration_form_fails_with_missing_password(self): form = UserRegistrationForm({ 'email': '*****@*****.**', 'password1': 'letmein1', 'stripe_id': settings.STRIPE_SECRET, 'credit_card_number': 4242424242424242, 'cvv': 123, 'expiry_month': 1, 'expiry_year': 2033 }) self.assertFalse(form.is_valid()) self.assertRaisesMessage(forms.ValidationError, "Please re-type your password", form.full_clean())
def signup(): form = UserRegistrationForm() if form.is_submitted(): hashed_password = generate_password_hash(form.password.data, method='sha256') user_name = form.username.data domain = form.domain.data iroha_pvt_key, iroha_pub_key = create_users(user_name=user_name, domain=domain, pwd_hash=hashed_password) return '<h3>New user has been created!, your private key is: ' + str( iroha_pvt_key) + '</h3>' return render_template('signup.html', form=form)
def register(): if current_user.is_authenticated: return redirect(url_for('index')) user_type = request.args.get('type') form = StoreRegistrationForm() if user_type == 'store' else UserRegistrationForm() if form.validate_on_submit(): user = User(name=form.name.data, username=form.username.data, email=form.email.data, mobile=form.mobile.data) user.set_password(form.password.data) if user_type == 'store': user.userType = 1 store = Store(storeName=form.storeName.data, country=form.country.data, state=form.state.data, city=form.city.data, street=form.street.data, zipCode=form.zipCode.data, latitude=form.latitude.data, longitude=form.longitude.data) db.session.add(store) db.session.add(user) usm = UserStoreMap(userId=User.query.filter_by(username=form.username.data).first().id, storeId=Store.query.filter_by(latitude=form.latitude.data, longitude=form.longitude.data).first().storeId) # usm = UserStoreMap(userId=user.id, storeId=store.storeId) db.session.add(usm) else: user.userType = 0 db.session.add(user) db.session.commit() flash('Sign-in to continue') return redirect(url_for('login')) return render_template('register.html', title="Register", form=form, type=user_type)
def register(request): from tuition.settings import SITE_SUPPORT_EMAIL from forms import UserRegistrationForm from tuition.utils.manager import AppManager from tuition.utils.utils import URLCreator from tuition.urlPatterns import UrlPattern from tuition.utils.utils import GooglePlusService queryString = int(request.GET.get('firstLogin', 0)) loggedInEmployee = AppManager.getCurrentLoggedInUser() if not AppManager.isCurrentUserAppAdmin(): if not queryString or AppManager.getUserByEmail( AppManager.getCurrentLoggedInUser().email()): raise Exception('Unauthorized Access') else: loggedInEmployee = AppManager.getUserByEmail( AppManager.getCurrentLoggedInUser().email()) template_values = { 'form': UserRegistrationForm(), 'loggedInEmployee': loggedInEmployee, 'queryString': queryString } return render_to_response('userRegistration.html', template_values, context_instance=RequestContext(request))
def register(request, **kwargs): if request.POST: new_data = request.POST.copy() #Create form with user data account_type = int(new_data['form_type']) if account_type is UserProfile.ACCOUNT_VOLUNTEER: registration = UserRegistrationForm(new_data) elif account_type is UserProfile.ACCOUNT_ORGANIZATION: registration = OrganizationRegistrationForm(new_data) else: raise InvalidRegistrationRequest #Process data if registration.is_valid(): #Create user new_user = registration.save() try: activation_key = get_object_or_404(ActivationKey, user=new_user) except MultipleObjectsReturned: return render_to_response('confirm.djhtml', {'success': False}) #Activation URL url = request.get_host() + "/register/confirm/%u/%s" % ( new_user.id, activation_key.activation_key) #Send email send_email(new_user.username, "Activation Email", url) return render_to_response('register_thankyou.djhtml', {'url': url}) else: context = RequestContext(request, { 'errors': registration.errors, 'form': registration }) return render_to_response('register_manual.djhtml', context) #Show new form if kwargs['type'] == UserProfile.ACCOUNT_VOLUNTEER: registration = UserRegistrationForm() elif kwargs['type'] == UserProfile.ACCOUNT_ORGANIZATION: registration = OrganizationRegistrationForm() else: registration = UserRegistrationForm() context = RequestContext(request, {'form': registration}) return render_to_response('register_manual.djhtml', context)
def register_userinfo_page(request, key): if request.method != "POST" : return HttpResponseRedirect('/') else: userinfo_form = UserRegistrationForm(request.POST) if userinfo_form.is_valid(): try: user = EmailActivation.objects.get(activation_key=key) userinfo_form.clean_username() userinfo_form.clean_password2() new_user = userinfo_form.save() # Enroll Email new_user.email = user.email if User.objects.all().count() is 1: new_user.is_staff = True new_user.is_superuser = True new_user.save() # Delete Activation Key user.delete() # Self-Following UserProfile.objects.create(user=new_user) Following.objects.create(followee=new_user, followee_str = new_user.username, follower=new_user, follower_str = new_user.username) except ObjectDoesNotExist: return HttpResponseRedirect('/') return HttpResponseRedirect('/')
def userRegistration(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): try: user = form.save() user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) return HttpResponseRedirect("/tasks") except Exception as error: return HttpResponseRedirect('/?error='+str(error)[1:-1]) return HttpResponseRedirect('/') return HttpResponseRedirect('/?error=invalid_input') return HttpResponse(403)
def register(request): is_post = request.method == 'POST' if is_post: form = UserRegistrationForm(request.POST) if form.is_valid(): form.save() data = create_user_json(request) return HttpResponse(data, mimetype='application/json') return HttpResponse(status=401) args = {} args.update(csrf(request)) args['form'] = UserRegistrationForm() return render_to_response('users/register.html', args)
def register(request,**kwargs): if request.POST: new_data = request.POST.copy() #Create form with user data account_type = int(new_data['form_type']) if account_type is UserProfile.ACCOUNT_VOLUNTEER: registration = UserRegistrationForm(new_data) elif account_type is UserProfile.ACCOUNT_ORGANIZATION: registration = OrganizationRegistrationForm(new_data) else: raise InvalidRegistrationRequest #Process data if registration.is_valid(): #Create user new_user = registration.save() try: activation_key = get_object_or_404(ActivationKey,user=new_user) except MultipleObjectsReturned: return render_to_response('confirm.djhtml',{'success':False}) #Activation URL url = request.get_host() + "/register/confirm/%u/%s" % (new_user.id,activation_key.activation_key) #Send email send_email(new_user.username,"Activation Email",url) return render_to_response('register_thankyou.djhtml',{'url':url}) else: context = RequestContext(request, {'errors':registration.errors, 'form':registration}) return render_to_response('register_manual.djhtml', context) #Show new form if kwargs['type'] == UserProfile.ACCOUNT_VOLUNTEER: registration = UserRegistrationForm() elif kwargs['type'] == UserProfile.ACCOUNT_ORGANIZATION: registration = OrganizationRegistrationForm() else: registration = UserRegistrationForm() context = RequestContext(request, {'form':registration} ) return render_to_response('register_manual.djhtml', context)
def reg(request, token): if request.user.is_authenticated(): return render(request, 'index.html') else: try: activation = Activation.objects.get(token=token) except Activation.DoesNotExist: raise Exception("Неверный код") if activation.status == activation.REGISTERED: return render(request, 'login.html') elif activation.status == activation.EMAIL_SENT: raise Exception("Сначала подтвердите емейл") context = dict() email = Activation.objects.get(token=token).email shortcut = lambda: render(request, 'reg.html', context) if 'code' in request.GET and not 'vkuserid' in request.POST: code = request.GET['code'] try: access_token, user_id = vkontakte.auth_code(code, request.path) except vkontakte.AuthError as e: messages.warning(request, 'Ошибка авторизации') context['form'] = UserRegistrationForm(request.POST) return shortcut() if User.objects.filter(vkuserid=user_id).count() == 0: vkuser = vkontakte.api(access_token, 'users.get', fields=['sex', 'bdate', 'city', 'photo_max', 'contacts'])[0] vkdata = dict() vkdata['vkuserid'] = user_id vkdata['first_name'] = vkuser['first_name'] vkdata['last_name'] = vkuser['last_name'] if 'mobile_phone' in vkuser: vkdata['phone'] = vkuser['mobile_phone'] elif 'home_phone' in vkuser: vkdata['phone'] = vkuser['home_phone'] else: vkdata['phone'] = None if vkuser['sex']: if vkuser['sex'] == 2: vkdata['sex'] = 'm' elif vkuser['sex'] == 1: vkdata['sex'] = 'f' else: vkdata['sex'] = None if 'bdate' in vkuser: if len(vkuser['bdate']) >= 8: vkdata['bdate'] = vkuser['bdate'] elif vkuser['bdate'] != '': messages.warning(request, 'Неполная дата') vkdata['bdate'] = vkuser['bdate'] else: vkdata['bdate'] = '' if 'photo_max' in vkuser: url = vkuser['photo_max'] vkdata['avatar'] = url context['avatar_url'] = url context['vkdata'] = vkdata context['vkuserid'] = user_id initial = {'email': email, 'sex': vkdata['sex'], 'first_name': vkdata['first_name'], 'last_name': vkdata['last_name'], 'phone': vkdata['phone'], 'bdate': vkdata['bdate'], 'vkuserid': user_id, 'avatar': vkdata['avatar'] } context['form'] = UserRegistrationForm(initial=initial) return shortcut() else: messages.warning(request, 'Такой пользователь уже зарегестрирован в системе') if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): print form.cleaned_data user = form.save(commit=False) user.set_password(user.password) activation = Activation.objects.get(email=user.email) activation.status = activation.REGISTERED activation.save() user.save() newuser = auth.authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password']) auth.login(request, newuser) return redirect('index') else: context['form'] = form messages.success(request, "Form is not valid!") return shortcut() context['form'] = UserRegistrationForm(initial={'email': email}) return shortcut()
def registration(request): if request.method == 'POST': # If the form has been submitted... form = UserRegistrationForm(request.POST) # A form bound to the POST data if form.is_valid(): if request.user.is_authenticated(): user = User.objects.get(username__exact=request.user.username) if(user.check_password(form.cleaned_data['passw'])): if(form.cleaned_data['year'] != None) and (form.cleaned_data['month'] != None) and (form.cleaned_data['day'] != None): try: user.get_profile().birthday = datetime.date(int(form.cleaned_data['year']), int(form.cleaned_data['month']), int(form.cleaned_data['day'])) except: pass if(form.cleaned_data['bio'] != None): user.get_profile().bio = form.cleaned_data['bio'] if 'photo' in request.FILES: user.get_profile().photo = request.FILES['photo'] im = Image.open(user.get_profile().photo) else: user.get_profile().photo = 'media/unknown_user.gif' if(form.cleaned_data['gender'] != None): user.get_profile().gender = form.cleaned_data['gender'] if(form.cleaned_data['firstname'] != None): user.get_profile().firstname = form.cleaned_data['firstname'] if(form.cleaned_data['lastname'] != None): user.get_profile().lastname = form.cleaned_data['lastname'] if(form.cleaned_data['uemail'] != None): user.email = form.cleaned_data['uemail'] user.get_profile().save() context = RequestContext(request) return render_to_response('users/profile.html', context) if not request.user.is_authenticated(): #First initialize a basic user user = User.objects.create_user(form.cleaned_data['usern'], form.cleaned_data['uemail'], form.cleaned_data['passw']) user = authenticate(username=form.cleaned_data['usern'], password=form.cleaned_data['passw']) login(request, user) #Set up extended user profile user.profile.firstname = form.cleaned_data['firstname'] user.get_profile().firstname = request.POST['firstname'] user.get_profile().lastname = request.POST['lastname'] if 'photo' in request.FILES: user.get_profile().photo = request.FILES['photo'] im = Image.open(user.get_profile().photo) else: user.get_profile().photo = 'media/unknown_user.gif' user.get_profile().gender = form.cleaned_data['gender'] print form.cleaned_data['year'] print form.cleaned_data['month'] print form.cleaned_data['day'] if((form.cleaned_data['year'] is not '') and (form.cleaned_data['month'] is not '') and (form.cleaned_data['day'] is not '')): try: user.get_profile().birthday = datetime.date(int(form.cleaned_data['year']), int(form.cleaned_data['month']), int(form.cleaned_data['day'])) except: pass user.get_profile().bio = request.POST['bio'] user.get_profile().save() #Set up context context = RequestContext(request) context['Success'] = True context['UserName'] = form.cleaned_data['usern'] context['FirstName'] = form.cleaned_data['firstname'] context['LastName'] = form.cleaned_data['lastname'] context['Email'] =form.cleaned_data['uemail'] context['Bio']= form.cleaned_data['bio'] context['Gender']= form.cleaned_data['gender'] context['Birthday']= user.get_profile().birthday context['Photo'] = user.get_profile().photo return render_to_response('users/registration.html', context) else: context = RequestContext(request) context['form'] = form else: context = RequestContext(request) context['form'] = form # Populate the form if the user is logged in elif request.user.is_authenticated(): user = request.user form = UserRegistrationForm(initial={'usern': user.username, 'firstname':user.get_profile().firstname , 'lastname': user.get_profile().lastname, 'uemail': user.email, 'gender': user.get_profile().gender, 'birthday': user.get_profile().birthday, 'bio': user.get_profile().bio, 'photo': user.get_profile().photo, 'passw': user.password, 'passwr': user.password,}) context = RequestContext(request) context['form'] = form else: form = UserRegistrationForm() context = RequestContext(request) context['form'] = form return render_to_response('users/registration.html', context)