コード例 #1
0
def register(request):

    # A boolean value for telling the template whether the registration was successful.
    # Set to False initially. Code changes value to True when registration succeeds.
    registered = False

    if request.session.test_cookie_worked():
        print ">>>> TEST COOKIE WORKED!"
        request.session.delete_test_cookie()

    # If it's a HTTP POST, we're interested in processing form data.
    if request.method == 'POST':
        # Attempt to grab information from the raw form information.
        # Note that we make use of both UserForm and UserProfileForm.
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)

        # If the two forms are valid...
        if user_form.is_valid() and profile_form.is_valid():
            # Save the user's form data to the database.
            user = user_form.save()

            # Now we hash the password with the set_password method.
            # Once hashed, we can update the user object.
            user.set_password(user.password)
            user.save()

            # Now sort out the UserProfile instance.
            # Since we need to set the user attribute ourselves, we set commit=False.
            # This delays saving the model until we're ready to avoid integrity problems.
            profile = profile_form.save(commit=False)
            profile.user = user

            # Did the user provide a profile picture?
            # If so, we need to get it from the input form and put it in the UserProfile model.
            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']

            # Now we save the UserProfile model instance.
            profile.save()

            # Update our variable to tell the template registration was successful.
            registered = True

        # Invalid form or forms - mistakes or something else?
        # Print problems to the terminal.
        # They'll also be shown to the user.
        else:
            print user_form.errors, profile_form.errors

    # Not a HTTP POST, so we render our form using two ModelForm instances.
    # These forms will be blank, ready for user input.
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    # Render the template depending on the context.
    return render(request,
            'rango/register.html',
            {'user_form': user_form, 'profile_form': profile_form, 'registered': registered} )
コード例 #2
0
def register_page():
    form = UserForm()
    if session["user_id"]:
        flash('logout first', category='primary')
        return redirect('/')

    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

        new_user = User.register(username, password, email, first_name,
                                 last_name)

        db.session.add(new_user)
        try:
            db.session.commit()
        except IntegrityError:
            form.username.errors.append('Username taken.  Please pick another')
            return render_template('register.html', form=form)

        session["user_id"] = new_user.username
        flash('Account created successfully!', category='success')
        return redirect(f'/user/{new_user.username}')
    else:
        return render_template("register.html", form=form)
コード例 #3
0
ファイル: app.py プロジェクト: onrmdc/ip-operations
def index():
    result = None
    form = UserForm(request.form)
    if request.method == 'POST':

        if form.validate_on_submit():
            input_ip_address = request.form['input_ip_address']
            result = main_func(input_ip_address)

    return render_template('find-interface.html', form=form, result=result)
コード例 #4
0
def hello_world():
    uform = UserForm()
    if uform.validate_on_submit():
        name = uform.name.data
        password = uform.password.data
        phone = uform.phone.data
        icon = uform.icon.data
        filename = secure_filename(icon.filename)
        icon.save(os.path.join(UPLOAD_DIR, filename))
        return '提交成功!'

    return render_template('user.html', uform=uform)
コード例 #5
0
def boot_form_user():
    uform = UserForm()
    if uform.validate_on_submit():  # 主要通过其进行校验 校验提交方式以及form的验证
        name = uform.name.data
        password = uform.password.data
        phone = uform.phone.data
        print('name:', name, ' password:'******' phone:', phone)
        icon = uform.icon.data  # FileStorage类型
        print(type(icon))
        # 构建安全文件名 存入
        filename = secure_filename(icon.filename)
        icon.save(os.path.join(UPLOAD_DIR, filename))
        return '提交成功!'
    return render_template('user1.html', uform=uform)
コード例 #6
0
def add_users(request):
    groups = Group.objects.all()
    departments = Depart.objects.all()
    if request.method == 'GET':
        form = UserForm()

    elif request.method == 'POST':
        form = CreateUserForm(request.POST)

        if form.is_valid():
            print(form.clean())
        else:
            print(form.errors)
    context = {'groups': groups, 'departments': departments, 'form': form}
    print(int(form['usergroup'].value()) == groups[0].id)
    return render(request, 'app01/add_user.html', context=context)
コード例 #7
0
def add_user():
    admin = Admin.query.filter_by(userid=session["userid"]).first()
    if admin.is_admin == True:
        form = UserForm(request.form)
        if request.method == "POST" and form.validate:
            email = request.form["email"]
            password = '******'
            firstname = request.form["firstname"]
            lastname = request.form["lastname"]
            user = User(firstname, email, firstname, lastname, password,
                        session["accountId"], False)
            db.session.add(user)
            db.session.commit()
            all_user = AllUser(user.id, True, user.owner_id)
            all_admin = Admin(user.id, False, user.owner_id)
            alluser = UserGroup.query.filter_by(
                groupname='All User').filter_by(
                    group_id=user.owner_id).first()
            alluser.addgroup.append(user)
            db.session.add(all_user)
            db.session.add(alluser)
            db.session.add(all_admin)
            db.session.commit()
            return redirect(url_for('admin_home'))
        return render_template('create_user.html', form=form)
    else:
        return "Unauthorized!"
コード例 #8
0
ファイル: route.py プロジェクト: Shadowmaple/Doodle-TodoList
def update_user_info():
    if request.method == 'GET':
        user = User.query.filter_by(id=current_user.id).first()
        form = UserForm(
            username=user.username,
            nick_name=user.nick_name,
        )
        return render_template('user_update.html', title='用户信息', form=form)

    form = UserForm()
    if form.validate_on_submit():
        user = User.query.filter_by(id=current_user.id).first()
        user.username = form.username.data
        user.nick_name = form.nick_name.data
        db.session.commit()
        flash('update user info')
    return redirect(url_for('get_user_info'))
コード例 #9
0
 def to_form(self):
     return UserForm(name=self.name,
                     email=self.email,
                     wins=self.wins,
                     ties=self.ties,
                     total_played=self.total_played,
                     not_lose_percentage=self.not_lose_percentage,
                     points=self.points)
コード例 #10
0
ファイル: main.py プロジェクト: zongzhenh/Blog
def hello_world():
    form = UserForm(request.form)
    if form.validate():
        user = {
            "username": form.username.data,
            "email": form.email.data,
            "password": form.password.data,
            "confirm": form.confirm.data,
            "is_vip": form.is_vip.data
        }
        return generate_response(ResponseStatus.StatusCode.SUCCESS.value,
                                 ResponseStatus.StatusMessage.SUCCESS.value,
                                 user)
    else:
        return generate_response(
            ResponseStatus.StatusCode.ARGS_VALIDATE_ERROR.value,
            ResponseStatus.StatusMessage.ARGS_VALIDATE_ERROR.value, [])
コード例 #11
0
ファイル: app.py プロジェクト: BayuP/flask-postgresql
def edit_user(id):
    edit_user= User.query.filter_by(id=id).first()
    form = UserForm(obj=edit_user)
    if form.validate_on_submit():
        try:
            # Update user
            form.populate_obj(edit_user)
            db.session.add(edit_user)
            db.session.commit()
            # User info
            flash('Saved successfully', 'success')
            return redirect(url_for('users'))
        except:
            db.session.rollback()
            flash('Error update contact.', 'danger')
    return render_template(
        'edit.html',
        form=form)
コード例 #12
0
ファイル: app.py プロジェクト: pawangeek/CovidHack
def register():
    form = UserForm(request.form)
    if request.method == 'POST' and form.validate():
        fname = form.fname.data
        lname = form.lname.data
        email = form.email.data
        password = form.password.data
        confirm = form.confirm_password.data

        # ipaddr = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
        # loc = get_coords(ipaddr)

        ipaddr = '157.37.154.227' # hard coded till we deploy it
        loc = get_coords(ipaddr)
        lat, lon = loc[0], loc[1]

        emaildata = db.execute("SELECT email FROM users WHERE email=:email", {"email": email}).fetchone()

        if emaildata is not None:
            flash("Email taken", "danger")
            return render_template("userregister.html", form=form)

        if password == confirm:
            db.execute("INSERT INTO users (first_name, last_name, email, pass,lon, lat) VALUES (:fname, :lname, :email, :password, :lon,:lan)", {
                       "fname": fname, "lname": lname, "email": email, "password": password, "lon":lon, "lat":lat})
            db.commit()

            email = request.form['email']
            token = s.dumps(email, salt='email-confirm')

            msg = Message('Confirm Email', sender='*****@*****.**', recipients=[email])
            link = url_for('confirm_email', token=token, _external=True)

            msg.body = link
            mail.send(msg)
            flash("A confirmation email has been sent. Please confirm your email.", "success")
            return render_template("userregister.html", form=form)

        else:
            flash("Passwords do not match", "danger")
            return render_template("userregister.html",form=form)

    return render_template("userregister.html",form=form)
コード例 #13
0
def login(req):
    """
    管理员登陆视图
    :param req:
    :return:
    """
    if req.method == 'POST':
        uf = UserForm(req.POST)
        if uf.is_valid():
            # 获取表单用户密码
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']
            yanzhengma = req.POST['Input_verify']
            if req.COOKIES.get('validate', '').upper() != yanzhengma.upper():
                return HttpResponse(
                    "<script type='text/javascript'>alert('验证码错误');window.location.href='login';</script>"
                )
            # 获取的表单数据与数据库进行比较
            admin = Administrator.objects.filter(adminAccount=username)
            if admin.count() == 0:
                return HttpResponse(
                    "<script type='text/javascript'>alert('用户名不存在');window.location.href='login';</script>"
                )
            if admin[0].adminPassword != password:
                # 比较失败,还在login
                return HttpResponse(
                    "<script type='text/javascript'>alert('用户名或密码错误');window.location.href='login';</script>"
                )
            else:
                # 比较成功,跳转index
                response = HttpResponseRedirect('/Seal/adminindex')
                adminid = admin[0].adminId

                # 将adminid写入浏览器cookies
                response.set_cookie('SealadminID', adminid)
                return response
        else:
            return HttpResponse(
                "<script type='text/javascript'>alert('用户名或密码不能为空!');window.location.href='login';</script>"
            )
    else:
        uf = UserForm()
        return render_to_response('Seal/login.html', {'uf': uf})
コード例 #14
0
def user_signup():
    """Create new user and add to database"""
    form = UserForm()
    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 is already taken", 'danger')
            return render_template('/user/signup.html', form=form)
        login_user(user, remember=True)
        return redirect('/')
    
    else:
        return render_template('/user/signup.html', form=form)
コード例 #15
0
def register_user():
    form = UserForm()
    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
        new_user = User.register(username, password, email, first_name, last_name)
        db.session.add(new_user)
        try:
            db.session.commit()

        except IntegrityError:
            form.username.errors.append('Username taken, Please pick another!!!!')
            return render_template('register.html', form=form)
        session['username'] = new_user.username
        flash('Welcome! Successfully create account!!')
        return redirect(f'/users/{username}')
    return render_template('register.html', form=form)
コード例 #16
0
def register(request):
    registered = False
    if request.method == 'POST':
        userform = UserForm(request.POST)
        userprofileform = UserProfileForm(request.POST)
        if userform.is_valid() and userprofileform.is_valid():
            user = userform.save()
            user.set_password(user.password)
            user.save()
            userprofile = userprofileform.save(commit=False)
            userprofile.user = user
            if 'picture' in request.FILES:
                userprofile.picture = request.FILES.get('picture')
            userprofile.save()
            registered = True
            return redirect('/watchfilm/login/')
        else:
            print userform.errors, userprofileform.errors
    else:
        userform = UserForm()
        userprofileform = UserProfileForm()
    return render(
        request, 'watchfilm/register.html', {
            'registered': registered,
            'userform': userform,
            'userprofileform': userprofileform
        })
コード例 #17
0
def register(request):
    # A boolean value for telling the template whether the registration was successful.
    # Set to False initially. Code changes value to True when registration succeeds.
    registered = False
    # If it's a HTTP POST, we're interested in processing form data
    if request.method == 'POST':

        # Attempt to grab information from the form information
        # Note that we make use of both UserForm and UserProfileForm

        user_form = UserForm(data=request.POST)
        user_profile_form = UserProfileForm(data=request.POST)

        # If the two forms are valid

        if user_form.is_valid() and user_profile_form.is_valid():
            # Save the user form data to database
            user = user_form.save()

            # Now we hash the password with the set_password method
            # Once hashed, we can update the user object

            user.set_password(user.password)
            user.save()

            # Now sort out the UserProfile instance
            # Since we need to set the user attribute ourselves, we set commit=False
            # This delays saving the model until we're ready to avoid integrity problems
            profile = user_profile_form.save(commit=False)
            profile.user = user

            # Did the user provide a profile picture?
            # If so, we need to get it from the input form and put it in the UserProfile model
            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']
            # Now we save the UserProfile model instance
            profile.save()

            # Update our variable to tell the template registration was successful
            registered = True

        # Invalid form or forms-mistakes or something else?
        # Print problems to the terminals
        # They will also be shown to the user
        else:
            print user_form.errors, user_profile_form.errors
    # Not a HTTP POST so we render our form using two ModelForm instances
    # These forms will be blank, ready for user input

    else:
        user_form = UserForm()
        user_profile_form = UserProfileForm()

    # Render the template depending on the context
    return render(
        request, 'registration.html', {
            'user_form': user_form,
            'user_profile_form': user_profile_form,
            'registered': registered
        })
コード例 #18
0
ファイル: views.py プロジェクト: cyrilsx/smart_cms
def edit_user(request, username=None):
    if username != None:
        edituser = User.objects.get(username=username)
        form = UserForm(request.POST, instance=edituser)
    else:
        edituser = None
        form = UserForm(request.POST)
    data = {}
    data["form"] = form

    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        email = form.cleaned_data['email']

        if edituser == None:
            user = User.objects.create_user(username, email, password)
            user.is_staff = False
            user.is_active = False
        
        user.save()
        return HttpResponseRedirect("/users/edit/" + user.username)
        
    return render_to_response(USER_TEMPLATE + 'edit.html', data, context_instance=RequestContext(request))
コード例 #19
0
def login(request):
    if request.session.get('is_login', None):
        return redirect("/index/")
    if request.method == "POST":
        login_form = UserForm(request.POST)
        message = "请检查填写的内容!"
        if login_form.is_valid():
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            try:
                user = models.User.objects.get(name=username)
                if user.password == password:
                    request.session['is_login'] = True
                    request.session['user_id'] = user.id
                    request.session['user_name'] = user.name
                    return redirect('/index/')
                else:
                    message = "密码不正确!"
            except:
                message = "用户不存在!"
        return render(request, 'login/login.html', locals())

    login_form = UserForm()
    return render(request, 'login/login.html', locals())
コード例 #20
0
ファイル: views.py プロジェクト: grv07/clat
def user_action(request):
	post_req_data = request.POST
	# print post_req_data
	data = {}
	user_form = UserForm(data=request.POST)
	register_form = StudentRegistrationForm(data=post_req_data)
	student_model = StudentModel(data=post_req_data)
	if  user_form.is_valid() and register_form.is_valid():
		try:
			if student_model.is_valid():
				address_model = AddressModel(data=post_req_data)
				if address_model.is_valid():
					try:
						city = City.objects.get(city_name = post_req_data.get('city', ''))
						assert city,'AssertError: city not found in database'
						address = address_model.save(commit = False)
						address.city_obj = city
						address.save()
					except Exception as e:
						logger.error('under student.view.user_action '+str(e.args))
						messages.error(request,'Error when trying to create the user. Please try again.')
						data = {'form': register_form,'register_error':True,'value_state':post_req_data.get('state', ''),'value_city':post_req_data.get('city', ''),'mailing_addr':post_req_data.get('mailing_address', '')}
						return render(request, 'register.html', data)

					try:
						user = user_form.save()
						# print user.password
						user.set_password(user.password)
						user.email = post_req_data.get('email',None)
						# print user.email
						user.save()
						import uuid
						student = student_model.save(commit=False)
						student.student = user           
						student.address = address
						student.uuid_key = 'eq' + str(uuid.uuid4().fields[-1])[:8]
						student_pass = post_req_data.get('password',None)
						student.gender = post_req_data.get('gender',None)
						p_date = post_req_data.get('d_o_b',None)
						
						if p_date:
							import datetime
							d_o_b = datetime.datetime.strptime(p_date, '%m/%d/%Y').date()
							student.d_o_b = d_o_b
						else:
							pass
						student.higher_education = post_req_data.get('higher_education',None)
						student.i_agree = post_req_data.get('i_agree')
						student.save()
						kawrgs = {'student_pass' : student_pass,'student_uname' : user.username,'phone_number' : student.phone_number, 'full_name' : student.full_name, 'uuid_key' : student.uuid_key}
						verification_mail(user = user.id,domain = request.META['HTTP_HOST'],**kawrgs)
						return user_actions.login_user(request)
					except Exception as e:
						logger.error('under student.view.user_action '+str(e.args))
				else:
					data = {'form': address_model,'register_error':True,'value_state':post_req_data.get('state', ''),'value_city':post_req_data.get('city', ''),'mailing_addr':post_req_data.get('mailing_address', '')}
			else:
				data = {'form': student_model,'register_error':True , 'value_state':post_req_data.get('state', ''),'value_city':post_req_data.get('city', ''),'mailing_addr':post_req_data.get('mailing_address', '')}
		
		except Exception as e:
			logger.error('under student.view.user_action '+str(e.args))
	else:
		messages.error(request,'Error when trying to create the User.')
		data = {'form': register_form,'register_error':True,'value_state':post_req_data.get('state', ''),'value_city':post_req_data.get('city', ''),'mailing_addr':post_req_data.get('mailing_address', '')}
	return render(request, 'register.html', data)
コード例 #21
0
def boot_form_user():
    uform = UserForm()
    return render_template('user1.html', uform=uform)
コード例 #22
0
ファイル: app.py プロジェクト: ChinnYu/flask_test
def hello_world():
    uform = UserForm()
    return render_template('user.html', uform=uform)
コード例 #23
0
ファイル: app.py プロジェクト: randyxu0711/wpSBOOT-1
def submit():
    form = UserForm()
    #basepath = os.path.dirname(__file__)
    # 收到表單
    if request.method == 'POST':

        # 抓取時間,格式化後轉成字串
        time = datetime.datetime.now()
        timeStr = time.strftime('%y%m%d%H%M%S')

        # 檢驗表單資料格式、缺失
        if form.validate_on_submit():

            # 以 email+datetime 作為filename(需唯一)
            if request.form.get('email'):
                email = str(form.email.data)
            else:
                email = 'test'
            filename = email.replace('.', '') + timeStr

            # 處理textarea
            if request.form['seqs']:
                text = request.form['seqs']
               # target = os.path.join(os.getcwd(), '/static/uploads/'+filename)
                fo = open('/home/ubuntu/wpSBOOT/static/uploads/'+filename,'w+')
                #print("filename :"+filename)
                fo.write(text)
                fo.close()
            elif request.files['file'] :
                # 處理file儲存
                f = request.files['file']
               # filename = secure_filename(f.filename)
                f.save(os.path.join(basepath, 'static/uploads', filename))
            else :
                return redirect(url_for('index'))

            # create cmd line
            # -i input
            cmd_list.append('-i')
            cmd_list.append('./static/uploads/'+filename)
            # -o output
            cmd_list.append('-o')
            cmd_list.append(filename)
            # -p path
            cmd_list.append('-p')
            cmd_list.append('./static/UserData/'+filename)
            #print(cmd_list)

            # 判斷option, aligner selector
            opcount = 0		
		#mafft
            if request.form.get('mafft'):
                cmd_list.append('-m')
                cmd_list.append('mafft')
                opcount += 1
		#msucle
            if request.form.get('muscle'):
                cmd_list.append('-m')
                cmd_list.append('muscle')
                opcount += 1
		#clustalw
            if request.form.get('clustalw'):
                cmd_list.append('-m')
                cmd_list.append('clustalw')
                opcount += 1
		#tcoffee
            if request.form.get('t-coffee'):
                cmd_list.append('-m')
                cmd_list.append('tcoffee')
                opcount += 1
            # if the number of aligners less than 2 (fatal error)
            if opcount < 2:
                return redirect(url_for('index'))

            # 執行 cmd line
            p = subprocess.Popen(cmd_list)
            p.communicate()
            
            #session
            if email != 'test':
                session['mail'] = email.replace('.', '')
                session.permanent = True

            # Mail
            link = url_for('result', fid=filename, _external=True)
            msg = Message(
                subject='wpSBOOT alignment result',
                recipients=[email],
                html='Hello,<br>'
                     '<blockquote>Your alignment has been completed.<br>'
                     'Please click <a href="{link}">here</a> to view your results.<br><br>'
		     'If you have question or report problems, do not reply to this message,and write instead to '
		     '<a href="mailto:[email protected] ">[email protected]</a></blockquote>'
                     '<br>Cheers,<br>'
                     'wpSBOOT team'.format(link=link)
            )
            mail.send(msg)

            return redirect(url_for('result', fid=filename))
    else:
        return redirect(url_for('index'))
コード例 #24
0
ファイル: app.py プロジェクト: randyxu0711/wpSBOOT-1
def index():
    form = UserForm()
    return render_template('index.html', form=form)