def signup(): """Handle user signup. Create new user and add to DB. Redirect to home page. If form not valid, present form. If the there already is a user with that username: flash message and re-present form. """ if CURR_USER_KEY in session: del session[CURR_USER_KEY] signup_form = UserSignupForm() login_form = UserLoginForm() # Signup form validation if signup_form.validate_on_submit(): try: user = User.signup( username=signup_form.username.data, first_name=signup_form.first_name.data, password=signup_form.password.data, image_url=signup_form.image_url.data or User.image_url.default.arg, ) db.session.commit() except IntegrityError as e: # Flash errors and reload page flash("Username already taken", 'danger signup-form-error') return render_template('no_user/no_user_home.html', signup_form=signup_form, login_form=login_form) # If it worked -> do login and say hello do_login(user) flash(f"Hello, {user.first_name}!", "success") # Go to User Home return redirect("/home") else: #If form not valid fields = [field for field in signup_form] errors = {} #Capture errors in dict for field in fields: if field.errors: errors[field.name] = field.errors #Create error message string to display errors on redirect error_message = "<i class='far fa-frown-open error-sad-icon'></i><span class='error-sad-title'>Dang it! It didn't work...</span>" for name, error in errors.items(): error_message += f"<p><b>*</b> {name} : {error[0]}</p>" flash(f"{error_message}", 'danger signup-form-error') return redirect('/')
def show_signup(): form = UserSignupForm() if form.validate_on_submit(): new_user = User.register(username=form.username.data, password=form.password.data, email=form.email.data, first_name=form.first_name.data, last_name=form.last_name.data) try: db.session.add(new_user) db.session.commit() except IntegrityError: db.session.rollback() return render_template('signup.html', form=form)
def homepage_search_results(): """Show List of search results from recipe search""" #Need forms here too signup_form = UserSignupForm() login_form = UserLoginForm() #collect query term from args search = request.args.get('q') offset_number = request.args.get('offset') or SEARCH_RESULTS offset = int(offset_number) + int(SEARCH_RESULTS) #set params for API, capture response, set response to JSON params = { "apiKey": API_KEY, "query": search, "number": SEARCH_RESULTS, "offset": offset } response = requests.get(API_SEARCH_BASE, params=params) res = response.json()['results'] if g.user: #If the user is logged in go to user search results page return render_template('user/search_results.html', results=res, offset=offset, search=search) #No user search results page return render_template('no_user/no_user_search_results.html', results=res, offset=offset, search=search, signup_form=signup_form, login_form=login_form)
def get(self, request): if request.user.is_authenticated(): return HttpResponseRedirect(reverse('accounts:index')) form = UserSignupForm() return render(request, 'accounts/signup.html', { 'form': form, })
def index(request, referring_user_id=None): referring_user = None has_registered = False referrer_count = None if request.method == 'POST': form = UserSignupForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] user = DefaultBackend().register( request, password1 = None, email = email, username = email, ) request.session['username'] = user.username SocialLaunchProfile.objects.create_from_request(user, request) messages.success(request, user_successfully_created_msg) return redirect('social_launch_referral', referring_user_id=user.id) else: form = UserSignupForm() form.fields['referrer_url'].initial = request.META.get('HTTP_REFERER', '') if referring_user_id is not None: try: referring_user = get_object_or_404(User, id=referring_user_id) except ValueError: raise Http404 has_registered = request.user.is_authenticated() or request.session.get('username', '') if has_registered: referrer_count = SocialLaunchProfile.objects.filter(referring_user=referring_user).count() form = None else: form = UserSignupForm() if referrer_url_session_key not in request.session: request.session[referrer_url_session_key] = request.META.get('HTTP_REFERER', '') if referring_user_id_session_key not in request.session: request.session[referring_user_id_session_key] = referring_user_id if referring_user_id is not None else '' return render(request, 'social_launch/index.html', {'form' : form, 'has_registered' : has_registered, 'referrer_count' : referrer_count})
def post(self, request): form = UserSignupForm(request.POST) if form.is_valid(): form.save() # data = form.cleaned_data # request.session['post_register_user'] = data username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) return HttpResponseRedirect(reverse('accounts:post_register')) else: return render(request, 'accounts/signup.html', { 'form': form, })
def signup(): """ Create and secure new account""" form = UserSignupForm() if form.validate_on_submit(): try: user = User.signup(username=form.username.data, password=form.password.data, email=form.email.data) db.session.commit() except IntegrityError: flash('Username alredy taken') return render_template('users/signup.html', form=form) login(user) return redirect('/books') else: return render_template('users/signup.html', form=form)
def homepage(): """Homepage view with simple search bar and login/signup forms""" if g.user: return redirect("/home") #Apply forms to homepage view signup_form = UserSignupForm() login_form = UserLoginForm() return render_template('no_user/no_user_home.html', signup_form=signup_form, login_form=login_form, cuisines=CUISINES)
def signup(request): if request.user.is_authenticated(): return HttpResponseRedirect(reverse('accounts:index')) if request.method == 'POST': form = UserSignupForm(request.POST) if form.is_valid(): form.save() request.session['post_register_user'] = form.cleaned_data return HttpResponseRedirect(reverse('accounts:post_register')) else: form = UserSignupForm() return render(request, 'accounts/signup.html', { 'form': form, })
def post(self, request): """Handles POST requests to 'register' named route. Raw data posted from form is received here,bound to form as dictionary and sent to unrendered django form for validation. Returns: A HttpResponse with a register template, otherwise, redirects to the login page. """ usersignupform = UserSignupForm(request.POST) # get the user email address email = request.POST.get('email') signup_new_user = User.objects.filter(email__exact=email) if signup_new_user: args = {} args.update(csrf(request)) mssg = "Email already taken please signup with another email" messages.add_message(request, messages.INFO, mssg) return render(request, 'authentication/register.html', args) if usersignupform.is_valid(): usersignupform.save() new_user = User.objects.get(email__exact=email) # generate an activation hash url for new user account activation_hash = Hasher.gen_hash(new_user) activation_hash_url = request.build_absolute_uri( reverse( 'activate_account', kwargs={'activation_hash': activation_hash}, ) ) # compose the email activation_email_context = RequestContext( request, {'activation_hash_url': activation_hash_url, 'username': new_user.username, }, ) activation_email = SendGrid.compose( sender='Troupon <*****@*****.**>', recipient=new_user.email, subject='Troupon: ACTIVATE ACCOUNT', html=loader.get_template( 'authentication/activate_account_email.html' ).render(activation_email_context), text=loader.get_template( 'authentication/activate_account_email.txt' ).render(activation_email_context), ) # send mail to new_user activation_status = SendGrid.send(activation_email) # inform the user of activation mail sent if activation_status == 200: new_user_email = new_user.email messages.add_message( request, messages.INFO, new_user_email) return redirect(reverse('confirm_registration')) else: args = {} args.update(csrf(request)) return render(request, 'authentication/register.html', {'form': usersignupform})
def post(self, request): """Handles POST requests to 'register' named route. Raw data posted from form is received here,bound to form as dictionary and sent to unrendered django form for validation. Returns: A HttpResponse with a register template, otherwise, redirects to the login page. """ usersignupform = UserSignupForm(request.POST) # get the user email address email = request.POST.get('email') signup_new_user = User.objects.filter(email__exact=email) if signup_new_user: args = {} mssg = "Email already taken please signup with another email" messages.add_message(request, messages.INFO, mssg) return render(request, 'register.html', args) if usersignupform.is_valid(): usersignupform.save() new_user = User.objects.get(email__exact=email) if request.POST.get('is_merchant', False): new_user.userprofile.is_merchant = True new_user.userprofile.save() # generate an activation hash url for new user account activation_hash = Hasher.gen_hash(new_user) url_str = str(reverse_lazy('activate_account', kwargs={'activation_hash': activation_hash})) activation_hash_url = request.build_absolute_uri(url_str) # compose the email activation_email_context = RequestContext( request, {'activation_hash_url': activation_hash_url, 'username': new_user.username, }, ) receipient = str(new_user.email) subject, from_email, to = 'TheEventDiary: ACTIVATE ACCOUNT', EMAIL_SENDER, receipient html_content=loader.get_template('activate_account_email.html').render(activation_email_context) text_content=loader.get_template('activate_account_email.txt').render(activation_email_context) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") response = msg.send() # inform the user of activation mail sent if response == 1: new_user_email = new_user.email messages.add_message(request, messages.INFO, new_user_email) return redirect(reverse_lazy('confirm_registration')) else: user_form = UserSignupForm() args = {} args["signupform"] = user_form return render(request, 'register.html', args)
def post(self, request): """Handles POST requests to 'register' named route. Raw data posted from form is received here,bound to form as dictionary and sent to unrendered django form for validation. Returns: A HttpResponse with a register template, otherwise, redirects to the login page. """ usersignupform = UserSignupForm(request.POST) # get the user email address email = request.POST.get('email') signup_new_user = User.objects.filter(email__exact=email) if signup_new_user: args = {} mssg = "Email already taken please signup with another email" messages.add_message(request, messages.INFO, mssg) return render(request, 'register.html', args) if usersignupform.is_valid(): usersignupform.save() new_user = User.objects.get(email__exact=email) if request.POST.get('is_merchant', False): new_user.userprofile.is_merchant = True new_user.userprofile.save() # generate an activation hash url for new user account activation_hash = Hasher.gen_hash(new_user) url_str = str( reverse_lazy('activate_account', kwargs={'activation_hash': activation_hash})) activation_hash_url = request.build_absolute_uri(url_str) # compose the email activation_email_context = RequestContext( request, { 'activation_hash_url': activation_hash_url, 'username': new_user.username, }, ) receipient = str(new_user.email) subject, from_email, to = 'TheEventDiary: ACTIVATE ACCOUNT', EMAIL_SENDER, receipient html_content = loader.get_template( 'activate_account_email.html').render(activation_email_context) text_content = loader.get_template( 'activate_account_email.txt').render(activation_email_context) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") response = msg.send() # inform the user of activation mail sent if response == 1: new_user_email = new_user.email messages.add_message(request, messages.INFO, new_user_email) return redirect(reverse_lazy('confirm_registration')) else: user_form = UserSignupForm() args = {} args["signupform"] = user_form return render(request, 'register.html', args)