Example #1
0
def add_user(username, password, email, qq, icp, nickname, sex):
    password = hashlib.md5(password).hexdigest()
    u = User(username=username, password=password, email=email)
    u.save()
    up = UserProfile(user=u, sex=sex, nickname=nickname, qq=int(qq), icp=icp)
    up.save()
    return up
Example #2
0
def addProfile():
    #Adds new user profile
    form= UserProfile()
    if request== "POST":
        if form.validate_on_submit:
        
            userid= str(uuid.uuid4())
            firstname= request.form['firstname']
            lastname=request.form['lastname']
            username=request.form['username']
            age=request.form['age']
            biography=request.form['biography']
            gender= request.form["gender"]
            image=request.form['image']
            
            file_folder= app.config['UPLOAD_FOLDER']
            filename= secure_filename(image.filename)
            image.save(os.path.join(file_folder, filename))
            created_on = time.strftime("%a %d %B %Y")

            user= UserProfile(userid=userid,firstname=firstname,lastname=lastname,age=age,biography=biography,username=username)
            db.session.add(user)
            db.session.commit()
            
            flash("New user created")
    return render_template('newprofile.html')   
Example #3
0
def login_view(request):
    elem = {
        'title':'Login',
    }
    #inloggade användare behöver inte se login view
    if request.user.is_authenticated():
        return HttpResponseRedirect('/home/')
    if request.method == 'POST':
        loginform = LoginForm(request.POST)
        loginAuth(request)
        if loginform.is_valid():
            if request.user.is_authenticated():
                #endast för admin, som saknar user profile från början, underlättar testning
                up = UserProfile.objects.filter(user=request.user)
                if not up.exists():
                    new_profile = UserProfile(user=request.user, description=16*"admin")
                    new_profile.save()
                return HttpResponseRedirect('/home/')
        else:
            return HttpResponseRedirect('')    
            loginform = LoginForm()
            elem.update({'error':'inloggning misslyckades','login_form':loginform})
            print "aha"
            return render_to_response("login.html",elem,context_instance=RequestContext(request))
    else:
        loginform = LoginForm()
    elem.update({'login_form':loginform})
    return render_to_response("login.html",elem,context_instance=RequestContext(request))
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            first_name = form.cleaned_data['first_name']
            last_name = form.cleaned_data['last_name']

            user = User.objects.create_user(email, #email is username
                                            email, #email
                                            password)
            user.first_name = first_name
            user.last_name = last_name
            user.save()

            up = UserProfile(user=user)
            up.save()

            #request.session['next'] = '/'

            return authenticate(request, email, password)
    else:
        form = RegistrationForm()
    
    return render_to_response("login.html", {
            'form': form,
        },
        context_instance = RequestContext(request)
    )
Example #5
0
def create_profile(current_user):
    if request.content_type == 'application/json':
        data = request.get_json()
        emp_id = current_user.id
        first_name = data.get('first_name')
        last_name = data.get('last_name')
        designation = data.get('designation')
        experience = data.get('experience')
        gender = data.get('gender')
        skills = data.get('skills')
        client = data.get('client')
        location = data.get('location')
        address = data.get('address')
        mobile = data.get('mobile')
        image_url = data.get('image_url')
        linked_in = data.get('linked_in')
        github = data.get('github')
        slack = data.get('slack')
        joining_date = data.get('joining_date')
        dob = data.get('dob')

        if emp_id:
            user_profile = UserProfile(emp_id, first_name, last_name, designation, experience, gender, skills, client,
                                       location, address, mobile, image_url, linked_in, github, slack, joining_date,
                                       dob)
        else:
            return {"message": "unprocessible entity"}, 422

        try:
            user_profile.save()
            return {
                       "message": "Profile added successfully"
                   }, 200
        except:
            return {"message": "unable to add profile"}, 500
Example #6
0
def user_add(request):
    if request.method == 'POST':
        form = UserCreateForm(request.POST)
        if form.is_valid():
            u = User(first_name=form.cleaned_data['first_name'],
                     last_name=form.cleaned_data['last_name'],
                     email=form.cleaned_data['email'],
                     is_active=True)

            # Generate the username
            username = None
            while True:
                username = shortuuid.ShortUUID().random(length=25).upper()
                if not get_user_model().objects.filter(
                        username=username).exists():
                    break
            u.username = username

            u.set_password(form.cleaned_data['password'])
            u.save()

            up = UserProfile(
                permission_mode=form.cleaned_data['permission_mode'])
            up.user = u
            up.save()

            return HttpResponseRedirect(reverse("admin_user_list"))
    else:
        form = UserCreateForm()
    return render(request, "admin/admin_user_detail.html", {
        "form": form,
        "create": True
    })
Example #7
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('investments.dashboard', username=current_user.username))
    form = RegistrationForm()
    if form.validate_on_submit():
        email = form.email.data
        username = form.username.data
        # date_of_birth = form.date_of_birth.data or None
        date_of_birth = None
        first_name = form.first_name.data
        last_name = form.last_name.data or None
        password = form.password.data
        user = UserProfile(username=username, email=email, first_name=first_name,
                           password=password, last_name=last_name, date_of_birth=date_of_birth)
        db.session.add(user)
        db.session.commit()
        token = user.get_reset_password_token()
        send_email('Activate your account',
                   sender=current_app.config['ADMINS'][0],
                   recipients=[user.email],
                   text_body=render_template('account_activate.txt', user=user, token=token),
                   html_body=render_template('account_activate_email_format.html', user=user, token=token))
        flash('Thanks for registering with us!Please check you mail for activating you account.')
        return redirect(url_for('accounts.login'))
    else:
        print(form.errors)
    return render_template('register.html', form=form)
Example #8
0
def register(request):
	
	if request.user.is_authenticated():
		response = HttpResponse()
		response.status_code = 303
		response['location'] = 'account'
		return response

	userExists = False

	if request.method == 'POST':

		data = request.POST

		username = data['username']

		u = User.objects.filter(username=username)

		if not u.exists():

			first_name = data['firstname']
			last_name = data['lastname']
			password = data['password']
			email = data['email']
			address1 = data['address1']
			address2 = data['address2']
			ccn = data['ccn'].replace(" ","")
			ccnexp = datetime.strptime(data['ccnexp'],'%Y-%m')

			user = User(username=username,password=password,email=email,first_name=first_name,last_name=last_name)
			user.save()
			user.set_password(user.password)
			user.save()

			extra = UserProfile(address1=address1,address2=address2,ccn=ccn, ccnexp=ccnexp)
			extra.user = user
			extra.save()

			user = authenticate(username=username,password=password)
			if user is not None:
				if user.is_active:
					auth_login(request,user)
					
					response = HttpResponse()
					response.status_code = 303
					response['location'] = 'account'
					return response

				else:
					print("non-active user")
			else:
				print('incorrect login')

		else:
			userExists = True


	return render(request, 'app/register.html', {"userExists":userExists})
Example #9
0
 def form_valid(self, form):
     res = super(FrietjesRegistrationView, self).form_valid(form)
     # TODO: Fix this mess
     user = User.objects.get(username=form.cleaned_data['username'])
     user_profile = UserProfile(user_id=user.pk, company=self.invite.company)
     user_profile.save()
     self.invite.used_on = datetime.datetime.now()
     self.invite.save()
     return res
Example #10
0
    def save_model(self, request, obj, form, change):
        result = super(MyUserAdmin, self).save_model(request, obj, form,
                                                     change)

        if not UserProfile.objects.filter(user=obj):
            profile = UserProfile(user=obj)
            profile.save()

        return result
Example #11
0
    def setUp(self):

        now = datetime.datetime.now()
        UserProfile.objects(username='******').update(
            upsert=True,
            set__username='******',
            set__password=
            '******',
            last_login=now,
        )
        self.login('123', '15d77445c11f15134e765d6acaea7a68')
Example #12
0
def insert(username, password):
    obj = UserProfile.objects(username=username).first()
    print("账号:{}".format(username))
    pass_hashed = get_password(password)
    # pass_save = flask_bcrypt.generate_password_hash(pass_hashed)

    if obj:
        obj.set_password(password=pass_hashed)
    else:
        obj = UserProfile(username=username).save()
        obj.set_password(password=pass_hashed)
    print("密码:{}".format(password))
    return 0
Example #13
0
def profile():
    addprofile = addProfile()

    if request.method == 'POST':
        if addprofile.validate_on_submit():
            fname = addprofile.fname.data
            lname = addprofile.lname.data
            gender = addprofile.gender.data
            email = addprofile.email.data
            location = addprofile.location.data
            bio = addprofile.bio.data
            date = datetime.datetime.now()
            created_on = date.strftime("%B %d, %Y")

            photo = addprofile.photo.data

            filename = secure_filename(photo.filename)
            photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

            user = UserProfile(first_name=fname,
                               last_name=lname,
                               gender=gender,
                               email=email,
                               location=location,
                               bio=bio,
                               photo=filename,
                               created_on=created_on)
            db.session.add(user)
            db.session.commit()

            flash('File Uploaded', 'success')
            return redirect(url_for('profiles'))

    flash_errors(addprofile)
    return render_template('profile.html', form=addprofile)
def add_profile():
    """Either (GET) provide profile form or (POST) create the profile"""
    form = ProfileForm()
    if form.validate_on_submit():
        # Get values from form
        fname = request.form['first_name']
        lname = request.form['last_name']
        gender = request.form['gender']
        email = request.form['email']
        location = request.form['location']
        bio = request.form['bio']

        try:
            """Idea for now: need to save the picture, and save the filename. Store items to database"""
            p_filename = save_photo(
                request.files['profile_picture'])  # profile photo filename
            profile = UserProfile(fname, lname, gender, email, location, bio,
                                  p_filename)
            db.session.add(profile)
            db.session.commit()
            flash('User successfully created', 'success')
            return redirect(url_for('view_profiles'))
        except:
            flash("User could not be created", 'danger')
    return render_template('add_profile.html', form=form)
Example #15
0
def profile():
    form = ProfileForm()
    if request.method == "POST" and form.validate_on_submit():

        # fname = form.fname.data
        # lname = form.lname.data
        # email = form.email.data
        # location = form.location.data
        # gender = form.gender.data
        # biography = form.biography.data

        file = form.image.data
        filename = secure_filename(file.filename)
        file.save(os.path.join(path, filename))

        user = UserProfile(
            request.form['fname'],
            request.form['lname'],
            request.form['email'],
            request.form['location'],
            request.form['gender'],
            request.form['bio'],
            filename,
            # datetime.datetime.now()
            datetime.datetime.now().strftime("%B %d, %Y"))

        db.session.add(user)
        db.session.commit()

        flash('Profile Saved', 'success')
        return redirect(url_for("profiles"))
    return render_template("profile.html", form=form)
Example #16
0
def profile():

    form = profileForm()

    if request.method == "POST" and form.validate_on_submit():
        #collect from data
        fname = form.firstName.data
        lname = form.lastName.data
        gender = form.gender.data
        email = form.email.data
        location = form.location.data
        bio = form.biography.data
        date_joined = datetime.now().strftime("%B %d, %Y")
        img = form.photo.data

        filename = secure_filename(img.filename)

        #set custom file name for reference
        if filename.endswith('.' + "png"):
            photo_name = "pic_" + fname + "_" + email + ".png"
        elif filename.endswith('.' + "jpg"):
            photo_name = "pic_" + fname + "_" + email + ".jpg"

        img.save(os.path.join(app.config['UPLOAD_FOLDER'], photo_name))

        #connect to database and save data
        user_profile = UserProfile(fname, lname, gender, email, location, bio,
                                   date_joined, photo_name)
        db.session.add(user_profile)
        db.session.commit()

        flash("Your profile has been sucessfully added!", "success")
        return redirect(url_for('profiles'))

    return render_template('add_profile.html', form=form)
Example #17
0
def profile():
    form = MyForm()

    if request.method == "POST":
        file_folder = app.config['UPLOAD_FOLDER']

        if form.validate_on_submit():
            fname = request.form['fname']
            lname = request.form['lname']
            username = request.form['username']
            age = request.form['age']
            biography = request.form['biography']
            gender = request.form['gender']
            image = request.files['image']

            imagename = secure_filename(image.filename)
            image.save(os.path.join(file_folder, imagename))

            userid = randint(100000, 999999)
            created_on = datetime.date.today()

            new_profile = UserProfile(userid, fname, lname, username, age,
                                      gender, biography, imagename, created_on)
            db.session.add(new_profile)
            db.session.commit()

            flash("Created Successfully", "success")
            return redirect(url_for("profile"))
    """Render the website's profile_form page."""
    return render_template('profile_form.html', form=form)
def login():
    form = LoginForm()
    if request.method == "POST" and form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        
        userlog=get_user(username)
        if userlog:
            user = UserProfile(userlog['Username'],userlog['Password'])
            
            
            if user is not None and check_password_hash(user.password, password):
                remember_me = False
                # get user id, load into session
                login_user(user,remember_me)
                flash('Login successful.', 'success')
                
                print('login sucessfull',user.password)
                session['USERNAME'] = user.username
                return redirect(url_for('profile'))
            
            else:
                flash('username or Password is incorrect.', 'danger')
        else:
            flash('Username or password is incorrect.', 'danger')

    return render_template("login.html", form=form)
Example #19
0
def profile():
    myform = SignupForm()
    if request.method == "POST":
        if myform.validate_on_submit():
            first = myform.firstname.data
            last = myform.lastname.data
            gen = myform.gender.data
            email = myform.email.data
            loc = myform.location.data
            bio = myform.biography.data
            pic = request.files['file']
            now = datetime.now()
            signdate = now.strftime("%B") + " " + str(now.day) + ", " + str(
                now.year)
            photoname = secure_filename(pic.filename)
            pic.save(os.path.join(app.config['UPLOAD_FOLDER'], photoname))

            user = UserProfile(first, last, gen, email, loc, bio, signdate,
                               photoname)
            db.session.add(user)
            db.session.commit()

            flash("Profile Successfully Created", "success")
            return redirect("/")
        else:
            flash("Failed to create profile", "danger")
    return render_template('profile.html', myform=myform)
Example #20
0
def add_profile():
    """GET provides the profile form while POST stores profile"""
    profileform = ProfileForm()
    if request.method == 'POST' and profileform.validate_on_submit():
        # Get values from form
        fname = request.form['first_name']
        lname = request.form['last_name']
        gender = request.form['gender']
        email = request.form['email']
        location = request.form['location']
        bio = request.form['bio']

        file = profileform.photo.data
        filename = secure_filename(file.filename)
        file.save(os.path.join(path, filename))

        try:
            profile = UserProfile(fname, lname, gender, email, location, bio,
                                  filename)
            db.session.add(profile)
            db.session.commit()
            flash('Profile Saved', 'success')
            return redirect(url_for('view_profiles'))
        except:
            flash("Profile failed to save", 'danger')
    return render_template('add_profile.html', form=profileform)
Example #21
0
def profile():
    form = ProfileForm()
    if request.method == "POST" and form.validate_on_submit():

        #userid  = str
        first_name = request.form.data['first_name']
        last_name = request.form.data['last_name']
        gender = request.form.data['gender']
        email = request.form.data['email']
        location = request.form.data['location']
        biography = request.form.data['biography']
        created_on = time.strftime('%Y/%b/%d')

        photo = request.files.data['file']
        if photo:
            filename = secure_filename(photo.filename)
            photo.save(os.path.join(app.config['UPLOAD FOLDER'], filename))

        user = UserProfile(first_name='first_name',
                           last_name='last_name',
                           gender='gender',
                           email='email',
                           location='location',
                           biography='biography',
                           photo='photo',
                           created_on='created_on')
        db.session.add(user)
        db.session.commit()
    return render_template('profile.html', form=form)
Example #22
0
def profile():
    form = ProfileForm()
    if request.method == "POST" and form.validate_on_submit():
        profilePhoto = form.photo.data
        filename = secure_filename(profilePhoto.filename)
        profilePhoto.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        newUser = UserProfile(
            # first_name = form.first_name.data,
            # last_name = form.last_name.data,
            # email = form.email.data,
            # location = form.location.data,
            # gender = form.gender.data,
            # biography = form.biography.data,
            # profilePhoto = filename,
            request.form['first_name'],
            request.form['last_name'],
            request.form['email'],
            request.form['location'],
            request.form['gender'],
            request.form['biography'],
            filename,
            created_on=datetime.now().strftime("%B %d, %Y"))
        db.session.add(newUser)
        db.session.commit()
        flash('You have successfully added a new profile.', 'success')
        return redirect(url_for('profiles'))
    return render_template('profile.html', form=form)
Example #23
0
def profile():
    form = ProfileForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            firstname = form.firstname.data
            lastname = form.lastname.data
            email = form.email.data
            biography = form.biography.data
            location = form.location.data
            gender = form.gender.data

            created_on = format_date_joined()

            photo = form.photo.data
            filename = secure_filename(photo.filename)
            photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

            User = UserProfile(firstname=firstname,
                               lastname=lastname,
                               email=email,
                               location=location,
                               gender=gender,
                               created_on=created_on,
                               filename=filename,
                               biography=biography)
            db.session.add(User)
            db.session.commit()

            flash("User Created Successfully!")
            return redirect(url_for("viewprofiles"))
        else:
            flash_errors(form)

    return render_template('profile.html', form=form)
Example #24
0
def addProperty():
    form= UserForm()
    if request.method == "POST":
        if form.validate_on_submit() == True:
            #Gets the user input from the form
            proptitle = form.propertytitle.data
            description = form.description.data
            noofrooms = form.noofrooms.data
            noofbathrooms = form.noofbathrooms.data
            price = form.price.data
            proptype = form.propertytype.data
            location = form.location.data
            filename = uploadPhoto(form.property_picture.data)

            #create user object and add to database
            user = UserProfile(proptitle,description,noofrooms,noofbathrooms,price,proptype, location, filename)
            db.session.add(user)
            db.session.commit()

             # remember to flash a message to the user
            flash('Property information uploaded successfully.', 'success')
        else:
            flash('Property information not uploaded', 'danger')
        return redirect(url_for("properties"))  # they should be redirected to a secure-page route instead
    return render_template("addproperty.html", form=form)
Example #25
0
def register():
    form = RegistrationForm()
    if request.method == 'POST' and form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        #password is already hashed in the models.py...consider removing the line below
        #password=generate_password_hash(password, method='pbkdf2:sha256', salt_length=8)
        firstname = form.firstname.data
        lastname = form.lastname.data
        email = form.email.data
        location = form.location.data
        biography = form.biography.data
        profile_picture = form.profile_picture.data
        filename = secure_filename(profile_picture.filename)
        profile_picture.save(
            os.path.join(app.config['UPLOAD_FOLDER'], filename))
        joined = format_date_joined()

        user = UserProfile(username, password, firstname, lastname, email,
                           location, biography, filename, joined)
        db.session.add(user)
        db.session.commit()

        return jsonify({"message": "User successfully registered"}), 201
    return make_response(jsonify(error=form_errors(form)), 400)
Example #26
0
def register():
    """ Renders user registration page"""
    form = ProfileForm()

    if request.method == 'POST' and form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        firstname = form.firstname.data
        lastname = form.lastname.data
        location = form.location.data
        email = form.email.data
        biography = form.biography.data

        photo = form.profile_photo.data
        filename = secure_filename(photo.filename)
        #photo.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
        photo.save(
            os.path.join("./app", app.config['PROFILE_IMG_UPLOAD_FOLDER'],
                         filename))

        date_created = datetime.datetime.now().strftime("%B %d, %Y")

        new_user = UserProfile(username=username,
                               password=password,
                               firstname=firstname,
                               lastname=lastname,
                               biography=biography,
                               profile_photo=filename,
                               location=location,
                               joined_on=date_created,
                               email=email)
        db.session.add(new_user)
        db.session.commit()

        return jsonify(message="User successfully registered")
Example #27
0
def addprofile():
    form = ProfileForm()
    filefolder = app.config["UPLOAD_FOLDER"]

    file = request.files['picture']
    filename = secure_filename(file.filename)
    file.save(os.path.join(filefolder, filename))
    flash('File uploaded')

    img = "./static/uploads/" + filename
    date = str(datetime.date.today())
    username = form.username.data
    firstname = form.firstname.data
    lastname = form.lastname.data
    gender = form.gender.data
    age = form.age.data
    bio = form.bio.data
    password = form.password.data

    user = UserProfile(first_name=firstname,
                       last_name=lastname,
                       username=username,
                       password=password,
                       age=age,
                       bio=bio,
                       img=img,
                       date=date,
                       gender=gender)
    db.session.add(user)
    db.session.commit()

    return render_template(url_for('profiles'))
Example #28
0
def profile():
    """Render the website's profile page"""
    form = ProfileForm()
    us_Id = len(UserProfile.query.all())

    if request.method == "POST" and form.validate_on_submit():

        first_name = form.first_name.data
        last_name = form.last_name.data
        gender = form.gender.data
        location = form.location.data
        email = form.email.data
        bio = form.biography.data
        date = format_date(get_date())
        image = form.image.data
        imageName = first_name + last_name + str(us_Id + 1)

        newUser = UserProfile(first_name=first_name,
                              last_name=last_name,
                              gender=gender,
                              location=location,
                              email=email,
                              biography=bio,
                              created_on=date,
                              profilePic=imageName)
        db.session.add(newUser)
        db.session.commit()

        image.save("app/static/profilepictures/" + imageName + ".png")

        flash("New User Profile Created", "success")
        return redirect(url_for("profiles"))

    return render_template("profile.html", form=form)
Example #29
0
def profile():
    form = ProfileForm()

    if request.method == 'POST':
        print(form)

        #if form.validate_on_submit():
        if True:

            firstname = form.firstname.data
            lastname = form.lastname.data
            gender = form.gender.data
            email = form.email.data
            location = form.location.data
            bio = form.bio.data
            image = form.image.data
            filename = secure_filename(image.filename)
            image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            user = UserProfile(firstname, lastname, gender, email, location,
                               bio, filename)
            db.session.add(user)
            db.session.commit()

            flash('Your profile was sucessfully created!')
            return redirect('/profiles')
        flash_errors(form)
    return render_template('profile_form.html', form=form)
Example #30
0
def profile():
    form1 = ProfileForm()
    form2 = PasswordForm()
    user = User.query.filter_by(UserAccountId=current_user.get_id()).first()

    if form1.submit.data and form1.validate_on_submit():
        if user.Profile == None:
            user_profile = UserProfile(FirstName=form1.first_name.data, LastName=form1.last_name.data, DOB=form1.dob.data, \
                Phone=form1.phone.data, Address=form1.address.data, Country=form1.country.data, owner=user)
            db.session.add(user_profile)
            db.session.commit()
        else:
            user.Profile.FirstName = form1.first_name.data
            user.Profile.LastName = form1.last_name.data
            user.Profile.DOB = form1.dob.data
            user.Profile.Phone = form1.phone.data
            user.Profile.Address = form1.address.data
            user.Profile.Country = form1.country.data
            db.session.commit()
        flash('Changes succesfully saved!')
        return redirect(url_for('profile'))

    if form2.update.data and form2.validate_on_submit():
        if user is None or not user.check_password(form2.password.data):
            flash('Invalid current password')
            return redirect(url_for('profile'))
        user.set_password(form2.new_password.data)
        db.session.commit()
        flash('Password succesfully updated!')
        return redirect(url_for('profile'))

    return render_template('account-profile.html',
                           title='Profile',
                           form1=form1,
                           form2=form2)
def profile():
    profileForm = ProfileForm()
    if request.method == "POST":
        if profileForm.validate_on_submit():
            profilepic = profileForm.profilePic.data
            filename = secure_filename(profilepic.filename)
            profilepic.save(os.path.join(app.config['UPLOAD_FOLDER'],
                                         filename))

            firstName = profileForm.firstName.data
            lastName = profileForm.lastName.data
            gen = profileForm.gender.data
            email = profileForm.email.data
            loc = profileForm.location.data
            bio = profileForm.biography.data
            date_joined = format_date_joined()

            user = UserProfile(firstName, lastName, gen, email, loc, bio,
                               filename, date_joined)

            db.session.add(user)
            db.session.commit()

            flash('Profile was created successfully', 'success')
            return redirect(url_for('profiles'))
        else:
            flash(flash_errors(profileForm))

    return render_template('profile.html', form=profileForm)
Example #32
0
def submit():
    form = ProfileForm()

    # if form.validate_on_submit():

    if request.method == 'POST':

        req = request.form

        file = request.files.get('photo')

        filename = secure_filename(file.filename)

        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

        new_profile = UserProfile(firstname=req.get('firstName'),
                                  lastname=req.get('lastName'),
                                  email=req.get('email'),
                                  bio=req.get('biography'),
                                  location=req.get('location'),
                                  photo=file.filename,
                                  gender=req.get('gender'),
                                  photo_data=file.read())

        db.session.add(new_profile)
        db.session.commit()
        return redirect(url_for('profiles'))
    else:
        return redirect(url_for('profile'))
Example #33
0
def register_user():
    payload = request.get_json()
    name, email = payload['name'], payload['email']
    password = bcrypt.generate_password_hash(
        payload['password']).decode('utf8')

    added_user = User(name, email, password)
    profile_added = UserProfile()
    added_user.profile.append(profile_added)

    try:
        db.session.add(added_user)
        db.session.commit()
    except exc.IntegrityError:
        db.session().rollback()
        raise BadRequest("Invalid: the username or email already exist!")

    confirmation_token = generate_confirmation_token(added_user.id,
                                                     added_user.email)
    global token_whitelist
    token_whitelist[confirmation_token] = 1
    send_confirmation_email(added_user.email, confirmation_token)

    return jsonify(
        message=
        'Thanks for registering! Please check your email to confirm your email address.',
        added_user=added_user.serialize)
Example #34
0
def profile():
    profile = UserProfile.query.filter_by(user_id=current_user.id).first()
    form = ProfileForm(obj=profile)
    if form.validate_on_submit():
        if profile:
            form.populate_obj(profile)
            db.session.commit()

            flash('Profile Information has been saved!')
            return redirect(url_for('account'))
        new_profile = UserProfile(user_id=current_user.id,
                                  first_name=form.first_name.data,
                                  last_name=form.last_name.data,
                                  birth_date=form.birth_date.data,
                                  address_1=form.address_1.data,
                                  address_2=form.address_2.data,
                                  city=form.city.data,
                                  state=form.state.data,
                                  zip=form.zip.data)

        db.session.add(new_profile)
        db.session.commit()

        flash('Profile Information has been saved!')
        return redirect(url_for('account'))
    return render_template('profile.html', form=form)
Example #35
0
def reg_new(request):
    exist = User.objects.filter(username=request.POST['username'])
    if (request.POST['password']==request.POST['confirm_password']) and not exist.exists():
        print request.POST
        username=request.POST['username']
        password=request.POST['password']
        mail =request.POST['mail']
        description=request.POST['description']
        u=User.objects.create_user(username,mail,password)
        fill=80-len(description)
        if fill==80:
            usr_desc=UserProfile(user=u)
        else:
            for x in range(0,fill):
                description+="="
            usr_desc=UserProfile(user=u,description=description)
        usr_desc.save()
        loginAuth(request)

    else:
        print "user already exists"
Example #36
0
def userRegister(request):  
    try:  
        if request.method=='POST':  
            username=request.POST['name']  
            password1=request.POST['password1'] 
            password2=request.POST['password2'] 
            email=request.POST['email'] 
            phone=request.POST['phone'] 
            errors=[]
            filterResult=User.objects.filter(username=username)
            if len(filterResult)>0:  
                errors.append("用户名已存在")  
                return render(request,'zhuce.html',{'errors':errors}) 
            if len(password1) < 6:
                errors.append("请输入大于6位数密码")
                return render(request,'zhuce.html',{'errors':errors})  
            if password1!=password2:  
                errors.append("两次输入的密码不一致!")  
                return render(request,'zhuce.html',{'errors':errors}) 
            if len(email) < 9:
                errors.append("请输入有效邮箱")
                return render(request,'zhuce.html',{'errors':errors})
            user=User()
            user.username=username  
            user.set_password(password1)  
            user.email=email  
            user.save()   
            profile=UserProfile() 
            profile.user_id=user.id  
            profile.phone=phone  
            profile.save()  
            newUser=authenticate(username=username,password=password1)
            if newUser is not None:  
                login(request, newUser)
                return redirect("http://127.0.0.1:8000/list/")  
    except Exception as e:  
        errors.append(str(e))  
        return render(request,'zhuce.html',{'errors':errors}) 
    return render(request,'zhuce.html') 
Example #37
0
def manage_register(request, sort_by_date=0, sort_by_status=0):
    if not request.user.is_superuser:
        return HttpResponseRedirect(reverse('school_index'))
    if request.method == 'POST':
        if request.is_ajax():
            request_type = request.POST['request_type']
            if request_type == 'del':
                ids = request.POST['data'].split('-')
                try:
                    for id in ids:
                        if id:
                            reg = Register.objects.get(id=int(id))
                            if reg.status == 'CHUA_CAP':
                                if reg.register_phone:
                                    sms_msg = 'Dang ki truong %s tai truongnha.com khong duoc chap nhan!' % (to_en1(unicode(reg.school_name)))
                                    try:
                                        sendSMS(reg.register_phone, sms_msg, request.user)
                                    except Exception:
                                        pass
                                send_email(u'Từ chối đăng kí tại Trường Nhà',
                                    u'Cảm ơn bạn đã đăng ký để sử dụng dịch ' +
                                    u'vụ Trường Nhà.\nSau khi xác minh lại thông tin mà bạn cung cấp, ' +
                                    u'chúng tôi từ chối cung cấp dịch vụ cho Trường ' +
                                    unicode(reg.school_name) +
                                    u'.\n Vui lòng liên hệ với Ban Quản Trị để biết thêm chi tiết.',
                                    to_addr=[reg.register_email])
                            reg.delete()
                    message = u'Xóa thành công'
                    success = True
                    data = simplejson.dumps({
                        'message': message,
                        'success': success
                    })
                    return HttpResponse(data, mimetype='json')
                except Exception as e:
                    print e
                    message = u'Không thể xóa đăng ký'
                    success = False
                    data = simplejson.dumps({
                        'message': message,
                        'success': success
                    })
                    return HttpResponse(data, mimetype='json')
            elif request_type == 'create_acc':
                ids = request.POST['data'].split('-')
                try:
                    account_info = ''
                    for id in ids:
                        if id:
                            reg = Register.objects.get(id=int(id))
                            if reg.status == 'CHUA_CAP':
                                org_name = reg.school_name
                                org_level = 'T'
                                org_school_level = reg.school_level
                                org_status = 0
                                org_manager_name = reg.register_name
                                org_address = reg.school_address
                                phone = reg.register_phone
                                email = reg.register_email
                                school = Organization.objects.create(
                                            name= org_name,
                                            level= org_level,
                                            school_level= org_school_level,
                                            status= org_status,
                                            manager_name= org_manager_name,
                                            address= org_address,
                                            phone= phone,
                                            email= email)
                                user = User()
                                user.username = make_username(
                                        full_name=org_manager_name)
                                user.password, raw_password = make_default_password()
                                if reg.register_name:
                                    temp = reg.register_name.split(' ')
                                    user.first_name = temp[-1]
                                    user.last_name = ' '.join(temp[:-1])
                                user.save()
                                userprofile = UserProfile()
                                userprofile.user = user
                                userprofile.organization = school
                                userprofile.position = 'HIEU_TRUONG'
                                userprofile.save()
                                reg.status = 'DA_CAP'
                                reg.default_user_name = user.username
                                reg.default_password = raw_password
                                reg.save()
                                #notify users about their account via email
                                if school.phone:
                                    sms_msg = 'Tai khoan truongnha.com:\n\
                                            Ten dang nhap:%s\nMat khau:%s\n\
                                            Cam on ban da su dung dich vu!'\
                                            % (unicode(user.username),
                                                    unicode(raw_password))
                                    try:
                                        sendSMS(school.phone, sms_msg, request.user)
                                    except Exception:
                                        pass
                                send_email(u'Tài khoản Trường Nhà',
                                        u'Cảm ơn bạn đã đăng ký để sử dụng dịch vụ Trường Nhà.\nTài khoản của bạn như sau:\n'+ u'Tên đăng nhập:' + unicode(user.username) + u'\n' + u'Mật khẩu:' + unicode(raw_password),
                                        to_addr=[reg.register_email])
                                account_info += str(id) + '-' + user.username + '-' + raw_password + ','
                            else:
                                if reg.register_phone:
                                    sms_msg = 'Tai khoan truongnha.com:\nTen dang nhap:%s\nMat khau:%s\nCam on ban da su dung dich vu!' % (unicode(reg.default_user_name),
                                                 unicode(reg.default_password))
                                    try:
                                        sendSMS(reg.register_phone, sms_msg, request.user)
                                    except Exception:
                                        pass
                                send_email(u'Tài khoản Trường Nhà',
                                        u'Cảm ơn bạn đã đăng ký để sử dụng dịch' +
                                        u'vụ Trường Nhà.\nTài khoản của bạn như' +
                                        u'sau:\n'+ u'Tên đăng nhập:' +
                                        unicode(reg.default_user_name) + u'\n'
                                        + u'Mật khẩu:' +
                                        unicode(reg.default_password),
                                        to_addr=[reg.register_email])
                                account_info += str(id) + '-' + reg.default_user_name + '-' + reg.default_password + ','

                    message = u'Tạo tài khoản thành công'
                    success = True
                    data = simplejson.dumps({
                        'message': message,
                        'account_info': account_info,
                        'success': success
                    })
                    return HttpResponse(data, mimetype='json')
                except Exception as e:
                    print e
                    message = u'Tạo tài khoản không thành công'
                    success = False
                    data = simplejson.dumps({
                        'message': message,
                        'success': success
                    })
                    return HttpResponse(data, mimetype='json')
            elif request.POST[u'request_type'] == u'send_email':
                try:
                    content = request.POST[u'content'].strip()
                    register_list = request.POST[u'register_list']
                    register_list = register_list.split("-")
                    sts = []
                    for register in register_list:
                        if register:
                            sts.append(int(register))
                    registers = Register.objects.filter(id__in=sts)
                    for reg in registers:
                        if reg.register_phone:
                            sms_msg = to_en1(unicode(content))
                            try:
                                sendSMS(reg.register_phone, sms_msg, request.user)
                            except Exception:
                                pass
                        send_email(u'Thông báo từ Trường Nhà',
                                unicode(content), to_addr=[reg.register_email])
                    data = simplejson.dumps({
                        'success': True,
                        'message': u'Gửi thông báo thành công.',
                        })
                    return HttpResponse(data, mimetype='json')
                except Exception as e:
                    print e
                    data = simplejson.dumps({
                        'success': False,
                        'message': u'Có lỗi khi gửi thông báo.',
                        })
                    return HttpResponse(data, mimetype='json')
            else:
                raise Exception("BadRequest")
    if sort_by_date: sort_by_date = '-'
    else: sort_by_date = ''
    if sort_by_status: sort_by_status = '-'
    else: sort_by_status = ''

    registers = Register.objects.order_by(sort_by_date+'register_date',
            sort_by_status+'status')
    if sort_by_date == '-': sort_by_date = 0
    else: sort_by_date = 1
    if sort_by_status == '-': sort_by_status = 0
    else: sort_by_status = 1
    context = RequestContext(request)
    return render_to_response(MANAGE_REGISTER, {
        'registers': registers,
        'short_by_date': sort_by_date,
        'short_by_status': sort_by_status },
        context_instance=context)
Example #38
0
def add_student(student=None, index=0, start_year=None, year=None,
                _class=None, term=None, school=None, school_join_date=None):
    if not ( student and start_year and term and school ):
        raise Exception("Phải có giá trị cho các trường: Student,Start_Year,Term,School.")
    if 'fullname' in student:
        first_name, last_name = extract_fullname(student['fullname'])
    else:
        last_name = normalize(student['last_name'])
        first_name = normalize(student['first_name'])
    if not school_join_date:
        school_join_date = root_dt.date.today()
    birthday = student['birthday']
    if 'uu_tien' in student:
        uu_tien = student['uu_tien']
    else: uu_tien = ''
    if 'ban_dk' in student:
        ban = student['ban_dk']
    else: ban = None
    find = start_year.pupil_set.filter(first_name__exact=first_name)\
    .filter(last_name__exact=last_name)\
    .filter(birthday__exact=birthday)
    # count primary subjects
    print find, 'find'
    number_subject = 0
    if _class:
        number_subject = _class.subject_set.filter(primary=True).count()
    if find: # the student exists:
        transaction.commit()
        return False, find[0]
    else:    # the student does not exist
        try:
            st = Pupil()
            st.first_name = first_name
            st.last_name = last_name
            st.birthday = birthday
            st.ban_dk = ban
            st.school_join_date = school_join_date
            st.start_year_id = start_year
            st.class_id = _class
            st.index = index
            st.school_id = school
            st.uu_tien = uu_tien
            if 'dan_toc' in student: st.dan_toc = student['dan_toc']
            if 'birth_place' in student: st.birth_place = student['birth_place']
            if 'current_address' in student: st.current_address = student['current_address']
            if 'father_name' in student: st.father_name = student['father_name']
            if 'father_phone' in student: st.father_phone = student['father_phone']
            if 'mother_name' in student: st.mother_name = student['mother_name']
            if 'mother_phone' in student: st.mother_phone = student['mother_phone']
            if 'phone' in student: st.phone = student['phone']
            if 'sms_phone' in student: st.sms_phone = student['sms_phone']

            if 'sex' in student:
                st.sex = student['sex']
            else:
                st.sex = 'Nam'
            user = User()
            user.username = make_username(first_name=first_name,
                last_name=last_name, start_year=start_year)
            user.password, raw_password = make_default_password()
            user.first_name = st.first_name
            user.last_name = st.last_name
            user.is_active = False
            user.save()
            userprofile = UserProfile()
            userprofile.user = user
            userprofile.organization = school
            userprofile.position = 'HOC_SINH'
            userprofile.save()
            st.user_id = user
            st.save()
            st.join_class(_class)

            _class.max += 1
            _class.save()

            for i in range(1, 3):
                term1 = year.term_set.get(number__exact=i)

                tb_hoc_ky = TBHocKy()
                tb_hoc_ky.student_id = st
                tb_hoc_ky.number_subject = number_subject
                tb_hoc_ky.term_id = term1
                tb_hoc_ky.save()

                tk_diem_danh = TKDiemDanh()
                tk_diem_danh.student_id = st
                tk_diem_danh.term_id = term1
                tk_diem_danh.save()

            tb_nam = TBNam()
            tb_nam.student_id = st
            tb_nam.number_subject = number_subject
            tb_nam.year_id = year
            tb_nam.save()

            if _class:
                subjects = _class.subject_set.all()
                for i in range(1, 3):
                    term1 = year.term_set.get(number__exact=i)
                    for subject in subjects:
                        the_mark = Mark()
                        the_mark.student_id = st
                        the_mark.subject_id = subject
                        the_mark.term_id = term1
                        the_mark.save()

                for subject in subjects:
                    tkmon = TKMon(student_id=st, subject_id=subject)
                    tkmon.save()
            transaction.commit()
            return True, st
        except Exception as e:
            print e
Example #39
0
def add_many_students( student_list=None,
                       start_year=None,
                       year=None,
                       _class=None,
                       term=None,
                       school=None,
                       school_join_date=None,
                       force_update=False):
    if not (start_year and term and school and _class ):
        raise Exception("Start_Year,Term,School CanNotBeNull")
    index = _class.max
    existing_student = []
    number_of_change = 0
    unc_st_found = False
    for student in student_list:
        print student
        index += 1
        if 'fullname' in student:
            first_name, last_name = extract_fullname(student['fullname'])
        else:
            last_name = normalize(student['last_name'])
            first_name = normalize(student['first_name'])

        if not school_join_date:
            school_join_date = root_dt.date.today()

        birthday = student['birthday']
        ban = student['ban_dk']
        print start_year
        find = start_year.pupil_set.filter(first_name__exact=first_name,
                last_name__exact=last_name, birthday__exact=birthday)

        cr_bl_found = False
        bl = _class.block_id
        unc_set = bl.uncategorizedclass_set.filter(year_id=year)
        for unc in unc_set:
            unc_st = unc.pupil_set.filter(first_name__exact=first_name)\
                    .filter(last_name__exact=last_name)\
                    .filter(birthday__exact=birthday)
            if unc_st:
                st = unc_st[0]
                unc_st_found = True
                cr_bl_found = True
                break
        if not cr_bl_found:
            try:
                bl = school.block_set.get(number=bl.number - 1)
                unc_set = bl.uncategorizedclass_set.filter(year_id=year)
                for unc in unc_set:
                    unc_st = unc.pupil_set.filter(first_name__exact=first_name)\
                            .filter(last_name__exact=last_name)\
                            .filter(birthday__exact=birthday)
                    if unc_st:
                        st = unc_st[0]
                        unc_st_found = True
                        break
            except ObjectDoesNotExist:
                pass

        # count primary subjects
        if find or unc_st_found: # the student exists:
            if force_update:
                st = find[0]
            elif not unc_st_found:
                st = find[0]
                student['class_id'] = st.current_class().id
                existing_student.append(student)
                continue
        else:    # the student does not exist
            st = Pupil(first_name=first_name,
                    last_name=last_name,
                    birthday=birthday,
                    ban_dk=ban,
                    school_join_date=school_join_date,
                    start_year_id=start_year,
                    class_id=_class,
                    index=index,
                    school_id=school)
        changed = False
        if 'sex' in student:
            if st.sex != student['sex']:
                st.sex = student['sex']
                changed = True
        else:
            if st.sex != 'Nam':
                st.sex = 'Nam'
                changed = True
        if 'ban_dk' in student and st.ban_dk != student['ban_dk']:
            st.ban_dk = student['ban_dk']
            changed = True
        if 'dan_toc' in student and st.dan_toc != student['dan_toc']:
            st.dan_toc = student['dan_toc']
            changed = True
        if 'birth_place' in student and st.birth_place != student['birth_place']:
            st.birth_place = student['birth_place']
            changed = True
        if 'current_address' in student and st.current_address != student['current_address']:
            st.current_address = student['current_address']
            changed = True
        if 'father_name' in student and st.father_name != student['father_name']:
            st.father_name = student['father_name']
            changed = True

        if 'father_phone' in student and st.father_phone != student['father_phone']:
            st.father_phone = student['father_phone']
            changed = True

        if 'mother_name' in student and st.mother_name != student['mother_name']:
            st.mother_name = student['mother_name']
            changed = True

        if 'mother_phone' in student and st.mother_phone != student['mother_phone']:
            st.mother_phone = student['mother_phone']
            changed = True
        if 'sms_phone' in student and st.sms_phone != student['sms_phone']:
            st.sms_phone = student['sms_phone']
            changed = True
        if force_update and st.current_class() != _class:
            move_student(school, st, _class)
            changed = True

        if not force_update and not unc_st_found:
            user = User()
            user.username = make_username(first_name=first_name,
                last_name=last_name,
                start_year=start_year)
            user.password, raw_password = make_default_password()
            user.first_name = st.first_name
            user.last_name = st.last_name
            user.is_active = False
            user.save()
            userprofile = UserProfile()
            userprofile.user = user
            userprofile.organization = school
            userprofile.position = 'HOC_SINH'
            userprofile.save()
            st.user_id = user
        if force_update and changed:
            st.save()
            number_of_change += 1
        elif not force_update:
            st.save()
            if st.unc_class_id:
                st.move_to_new_class(_class)
            else:
                st.join_class(_class)
        if not force_update:
            for i in range(1, 3):
                term1 = year.term_set.get(number__exact=i)
                number_subject = 0
                if _class:
                    number_subject += _class.subject_set.filter(primary=0).count()
                    number_subject += _class.subject_set.filter(primary=3).count()
                    if i == 1:
                        number_subject += _class.subject_set.filter(primary=1).count()
                    if i == 2:
                        number_subject += _class.subject_set.filter(primary=2).count()

                tbhk, created = TBHocKy.objects.get_or_create(student_id=st,
                        term_id=term1)
                tbhk.number_subject = number_subject
                tbhk.save()

                TKDiemDanh.objects.get_or_create(student_id=st,
                    term_id=term1)

            number_subject = 0
            if _class:
                number_subject += _class.subject_set.filter(primary=0).count()
            tbnam, created = TBNam.objects.get_or_create(student_id=st,
                    year_id=year)
            if created:
                tbnam.number_subject = number_subject
                tbnam.save()

            if _class:
                subjects = _class.subject_set.all()
                for i in range(1, 3):
                    term1 = year.term_set.get(number__exact=i)
                    for subject in subjects:
                        Mark.objects.get_or_create(student_id=st,
                            subject_id=subject,
                            term_id=term1)
                for subject in subjects:
                    TKMon.objects.get_or_create(student_id=st,
                        subject_id=subject)
    _class.max = index
    _class.save()
    #transaction.commit()
    if force_update: return number_of_change
    return existing_student
Example #40
0
def add_teacher(first_name=None, last_name=None, full_name=None,
                birthday=None, sms_phone='', sex='N', dan_toc='Kinh',
                major='', current_address='', home_town='', birthplace='',
                school=None, team_id=None, group_id=None, email='',
                force_update=False):
    if full_name:
        first_name, last_name = extract_fullname(full_name)
    else:
        first_name = normalize(first_name)
        last_name = normalize(last_name)
    if team_id:
        if (type(team_id) == str or type(team_id) == unicode) and team_id.strip():
            name = team_id.strip()
            try:
                team_id = school.team_set.get(name=name)
            except Exception as e:
                print e
                team_id = Team()
                team_id.name = name
                team_id.school_id = school
                team_id.save()
        elif not isinstance(team_id, Team):
            team_id = None
    else:
        team_id = None
    if team_id:
        if group_id:
            if (type(group_id) == str
                or type(group_id) == unicode) and group_id.strip():
                name = group_id
                try:
                    group_id = team_id.group_set.get(name=name)
                except Exception as e:
                    print e
                    group_id = Group()
                    group_id.name = name
                    group_id.team_id = team_id
                    group_id.save()
            elif isinstance(group_id, Group):
                if group_id.team_id != team_id:
                    raise Exception("GroupNotBelongToTeam")
            else:
                group_id = None
        else:
            group_id = None
    else:
        group_id = None

    if major.strip():
        if to_en(major) not in SUBJECT_LIST_ASCII:
            try:
                major = to_subject_name(major)
            except Exception:
                major = ''

    teacher = Teacher()
    teacher.first_name = first_name
    teacher.last_name = last_name
    teacher.school_id = school
    teacher.birthday = birthday
    find = school.teacher_set.filter(first_name__exact=first_name,
        last_name__exact=last_name, birthday__exact=birthday)
    if find:
        if force_update:
            teacher = find[0]
        else:
            return find
    teacher.sms_phone = sms_phone
    teacher.email = email
    teacher.home_town = home_town
    teacher.sex = sex
    teacher.dan_toc = dan_toc
    teacher.current_address = current_address
    teacher.birth_place = birthplace
    teacher.team_id = team_id
    teacher.group_id = group_id
    teacher.major = major

    if not force_update:
        user = User()
        user.username = make_username(first_name=first_name, last_name=last_name)
        user.password, raw_password = make_default_password()
        user.is_active = False
        user.first_name = teacher.first_name
        user.last_name = teacher.last_name
        user.save()
        userprofile = UserProfile()
        userprofile.user = user
        userprofile.organization = school
        userprofile.position = 'GIAO_VIEN'
        userprofile.save()
        teacher.user_id = user
    teacher.save()
    return teacher
Example #41
0
def manage_register(request, sort_by_date=0, sort_by_status=0):
    try:
        if not request.user.is_superuser:
            return HttpResponseRedirect( reverse('school_index'))
        if request.method == 'POST':
            if request.is_ajax():
                request_type = request.POST['request_type']
                if request_type == 'del':
                    ids = request.POST['data'].split('-')
                    print ids
                    try:
                        for id in ids:
                            if id:
                                register = Register.objects.get(id= int(id))
                                register.delete()
                        message = u'Xóa thành công'
                        success = True
                        data = simplejson.dumps({
                            'message': message,
                            'success': success
                        })
                        return HttpResponse(data, mimetype='json')
                    except Exception as e:
                        print e
                        message = u'Không thể xóa đăng ký'
                        success = False
                        data = simplejson.dumps({
                            'message': message,
                            'success': success
                        })
                        return HttpResponse(data, mimetype='json')
                elif request_type == 'create_acc':
                    ids = request.POST['data'].split('-')
                    print ids
                    try:
                        account_info = ''
                        for id in ids:
                            if id:
                                register = Register.objects.get(id= int(id))
                                org_name = register.school_name
                                org_level = 'T'
                                org_school_level = register.school_level
                                org_status = 0
                                org_manager_name = register.register_name
                                org_address = register.school_address
                                phone = register.register_phone
                                email = register.register_email
                                school = Organization.objects.create(
                                                            name= org_name,
                                                            level= org_level,
                                                            school_level= org_school_level,
                                                            status= org_status,
                                                            manager_name= org_manager_name,
                                                            address= org_address,
                                                            phone= phone,
                                                            email= email
                                                        )
                                user = User()
                                user.username = make_username( full_name=org_manager_name)
                                user.password = make_default_password( user.username )
                                user.save()
                                userprofile = UserProfile()
                                userprofile.user = user
                                userprofile.organization = school
                                userprofile.position = 'HIEU_TRUONG'
                                userprofile.save()
                                register.status = 'DA_CAP'
                                register.default_user_name = user.username
                                register.default_password = user.password
                                register.save()
                                #TODO send an email about account information to customers.
                                account_info += str(id) + '-' + user.username + ','
                        message = u'Tạo tài khoản thành công'
                        success = True
                        data = simplejson.dumps({
                            'message': message,
                            'account_info': account_info,
                            'success': success
                        })
                        print data
                        return HttpResponse(data, mimetype='json')
                    except Exception as e:
                        print e
                        message = u'Tạo tài khoản không thành công'
                        success = False
                        data = simplejson.dumps({
                            'message': message,
                            'success': success
                        })
                        return HttpResponse(data, mimetype='json')
                else:
                    raise Exception("BadRequest")
        if sort_by_date: sort_by_date = '-'
        else: sort_by_date = ''
        if sort_by_status: sort_by_status = '-'
        else: sort_by_status = ''

        registers = Register.objects.order_by(sort_by_date+'register_date', sort_by_status+'status')
        if sort_by_date == '-': sort_by_date = 0
        else: sort_by_date = 1
        if sort_by_status == '-': sort_by_status = 0
        else: sort_by_status = 1
        context = RequestContext(request)
        return render_to_response(MANAGE_REGISTER, {
            'registers': registers,
            'short_by_date': sort_by_date,
            'short_by_status': sort_by_status
        }, context_instance = context)

    except Exception as e:
        print e
        raise e
Example #42
0
def create_user_profile():
    user_profile = UserProfile(
        first_name=get_word(),
        last_name=get_word())
    user_profile.save()
    return user_profile