コード例 #1
0
def preferences_general(request):
    shop = request.shop
    profile = shop.admin.get_profile()
    preferences = Preference.get_preference(shop)
    form = GeneralPreferenceForm(request.POST or None, instance=preferences)
    profile_form = ProfileForm(request.POST or None, instance=profile)
    if form.is_valid() and profile_form.is_valid():
        preferences = form.save(commit=False)
        preferences.shop = shop
        preferences.save()

        profile = profile_form.save(commit=True)
        shop.update_geolocation()

        request.flash['message'] = unicode(
            _("General preferences successfully saved."))
        request.flash['severity'] = "success"
        return HttpResponseRedirect(reverse('preferences_general'))

    return render_to_response('preferences/preferences_general.html', {
        'form': form,
        'profile_form': profile_form
    }, RequestContext(request))
コード例 #2
0
def newProfile():

    form = ProfileForm()

    if request.method == 'GET':
        return render_template('newProfile.html', form=form)
    elif request.method == 'POST':
        if form.validate_on_submit():
            firstname = form.firstname.data
            lastname = form.lastname.data
            gender = form.gender.data
            email = form.email.data
            location = form.location.data
            bio = form.bio.data
            dateCreated = datetime.date.today()

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

            userid = generateUserId(firstname, lastname)

            newUser = UserProfile(userid=userid,
                                  first_name=firstname,
                                  last_name=lastname,
                                  gender=gender,
                                  email=email,
                                  location=location,
                                  biography=bio,
                                  pic=filename,
                                  created_on=dateCreated)

            db.session.add(newUser)
            db.session.commit()

            flash("Profile Successfully Created", "success")
            return redirect(url_for("profiles"))
コード例 #3
0
def change_profile():
    form = ProfileForm()
    if form.validate_on_submit():
        if form.password.data != form.password_again.data:
            return render_template('change_profile.html', title='Изменение профиля',
                                   form=form,
                                   message="Пароли не совпадают")
        db_sess = db_session.create_session()
        if db_sess.query(User).filter(User.id == form.email.data).first():
            if form.email.data == flask_login.current_user.id:
                pass
            else:
                return render_template('change_profile.html', title='Изменение профиля',
                                       form=form,
                                       message="Такой пользователь уже есть")
        db_sess = db_session.create_session()
        user = db_sess.query(User).filter(User.id == flask_login.current_user.id).first()
        user.id = form.email.data
        user.set_password(form.password.data)
        user.Name = form.name.data
        db_sess.commit()
        login_user(user, remember=False)
        return redirect('/profile')
    return render_template('change_profile.html', title='Изменение профиля', form=form)
コード例 #4
0
ファイル: views.py プロジェクト: aizeek1/info3180-project1
def profile():
    form = ProfileForm()
    file_folder = app.config['UPLOAD_FOLDER']
    if request.method == "POST" and form.validate_on_submit():
        fname = request.form['firstname']
        lname = request.form['lastname']
        username = request.form['username']
        userid = randomnum()
        age = request.form['age']
        gender = request.form['gender']
        image = request.files['image']
        biography = request.form['biography']
        created = time.strftime("%-d,%b,%Y")
        filename = secure_filename(image.filename)
        image.save(os.path.join(file_folder, filename))

        user = UserProfile(fname, lname, username, userid, age, gender,
                           biography, filename, created)
        db.session.add(user)
        db.session.commit()
        flash('Profile Created')
        return redirect(url_for('profiles'))
    flash_errors(form)
    return render_template('profileform.html', form=form)
コード例 #5
0
ファイル: views.py プロジェクト: D-barnett/info3180-project1
def create_userprofile():
    form = ProfileForm()

    if request.method == 'POST':
        if form.validate_on_submit():
            username = form.username.data
            firstname = form.first_name.data
            lastname = form.last_name.data
            age = form.age.data
            biography = form.biography.data
            email = form.email.data
            image = form.image.data
            gender = form.gender.data

            # save user to database
            user = UserProfile(id, username, firstname, lastname, age,
                               biography, email, image, gender)
            db.session.add(user)
            db.session.commit()

            flash('User successfully added')
            return redirect(url_for('login'))
    flash_errors(form)
    return render_template('profile.html', form=form)
コード例 #6
0
ファイル: views.py プロジェクト: jpablonc94/aulaslimpias
    def post(self, request):
        success_message = ''
        user = User.objects.create_user(request.POST.get('username', ''),
                                        request.POST.get('email', ''),
                                        request.POST.get('pass', ''))

        user_form = ProfileForm()

        #form = ProfileForm()
        #form.usuario = user_form
        #form.centro = request.POST.get('centro', '')
        #form.responsable = request.POST.get('resp', '')
        #form.fax = request.POST.get('fax', '')

        if user_form.is_valid():
            user.save()

            return redirect('reports/home')
        else:
            success_message = u'¡Guardado con éxito!'

            context = {'form': user_form, 'success_message': success_message}

            return render(request, 'users/new_user.html', context)
コード例 #7
0
def createprof():

    pform = ProfileForm()
    file_folder = app.config['UPLOAD_FOLDER']
    # date=date()
    if request.method == 'POST':
        firstname = pform.firstname.data
        lastname = pform.lastname.data
        username = pform.username.data
        age = pform.age.data
        gender = pform.gender.data
        bio = pform.bio.data
        profpic = request.files['profpic']
        if profpic and allowed_file(profpic.filename):
            picname = secure_filename(profpic.filename)
            path = "/static/uploads/" + picname
            profpic.save("./app" + path)
            profpic = path
            prof = UserProfiles(1, firstname, lastname, username, gender, age,
                                bio, profpic, date())
            db.session.add(prof)
            db.session.commit()
            return redirect(url_for('home'))
    return render_template('createProf.html', form=pform)
コード例 #8
0
def addProfile():
    pForm = ProfileForm()
コード例 #9
0
ファイル: app.py プロジェクト: fagcinsk/socilite
def profile():
    form = ProfileForm(data=current_user.to_dict())
    if form.validate_on_submit():
        form.populate_obj(current_user)
    return render_template('profile.html', form=form)
コード例 #10
0
ファイル: views.py プロジェクト: mb4828/marchingtbirdswebapp
def profile(request):
    message = ''
    saved = False
    option = request.GET.get('mode')

    # is the user logged in?
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/nest/login/')
    if request.user.is_staff:
        return HttpResponseRedirect('/admin/')

    # locate student object and load its form if it exists
    student = 0
    try:
        student = Student.objects.get(user__pk=request.user.pk)
        form = ProfileForm(instance=student)
    except:
        form = ProfileForm()

    # render depending on what the user asked us to do
    if option == 'view' or not option:
        saved = True
        context = {
            'title': 'View my profile' + SITE_SUF,
            'navlight': 3,
            'request': request,
            'user': request.user,
            'form': form,
            'view': 1,
            'message': message,
            'saved': saved
        }
        return render(request, 'nest/profile.html', context)

    elif option == 'edit':
        if request.method == 'POST':
            if student:
                prof_form = ProfileForm(data=request.POST, instance=student)
            else:
                prof_form = ProfileForm(data=request.POST)

            if prof_form.is_valid():
                if student:
                    # user has already been associated with a student
                    student = prof_form.save(commit=False)
                else:
                    # we must now associate the user with the student
                    student = prof_form.save(commit=False)
                    student.user = request.user  # ta da!

                # update our other data and save
                request.user.first_name = student.first_name
                request.user.last_name = student.last_name
                request.user.email = student.student_email
                student.save()
                request.user.save()

                # create a message and redirect to the dashboard
                messages.add_message(request, messages.SUCCESS,
                                     "Your profile has been updated")
                return HttpResponseRedirect('/nest/')

            else:
                form = prof_form
                message = '<span style="color:firebrick">Please correct the errors below</span>'
                saved = False

        context = {
            'title': 'Edit my profile' + SITE_SUF,
            'navlight': 3,
            'request': request,
            'user': request.user,
            'form': form,
            'view': 0,
            'message': message,
            'saved': saved,
        }
        return render(request, 'nest/profile.html', context)
    else:
        raise Http404
コード例 #11
0
ファイル: views.py プロジェクト: al-layth/denigma
def add_profile(request):
    form = ProfileForm(request.POST or None, request.FILES or None)

    if request.POST:
        if not "file" in request.POST:
            file = request.FILES['file']
            data = file.read().split('\n')
        elif request.POST["data_text"]:
            data = request.POST["data_text"].replace('\r', '').split('\n')
        else:
            redirect('/expressions/profile/add/')

        # Create profiles:
        profiles = []
        replicates = []  # Container for bulk creation.

        # Header:
        columns = data[0].split('\t')
        for index, dataset in enumerate(columns[1:]):
            tissue, diet, name = columns[index + 1].split('_')
            #print tissue, diet, name
            profile = Profile(
                name=name,
                species=Species.objects.get(pk=request.POST['species']),
                diet=Regimen.objects.get(shortcut__exact=diet))
            profile.save()
            tissues = Tissue.objects.filter(notes__icontains=tissue)
            profile.tissue = tissues
            profiles.append(profile)
            #print index, tissue, diet, name

        # Actually Data Parsing:
        limit = 10
        counter = 0
        overall_count = 0
        lines = data[1:]
        line_number = len(lines)
        c = Counter(lines)
        print(line_number)
        for line in lines:
            #print(line)
            counter += 1
            c.count()
            #if counter % 2: print counter
            #            if (100. * overall_count / line_number) < 40:
            #                overall_count += counter
            #                continue
            columns = line.split('\t')
            if not line: continue
            #print("Iterate over columns and save the replicates:")
            probe_id = columns[0]
            for index, column in enumerate(columns[1:]):
                #print index, column
                intensity = columns[index + 1]
                replicate = Replicate(probe_id=probe_id,
                                      intensity=intensity,
                                      profile=profiles[index])
                #replicate.save()
                replicates.append(replicate)

            if counter >= limit:
                current = 100. * overall_count / line_number
                #print(current)
                #if current > 47 and not current > 48:
                #print " ".join(replicate.intensity for replicate in replicates)
                #
                #else:
                try:
                    Replicate.objects.bulk_create(replicates)
                except Exception as e:
                    print(e)
                    messages.add_message(request, messages.ERROR,
                                         ugettext("1. Try: " + str(e)))
                    try:
                        [replicate.save() for replicate in replicates]
                    except Exception as es:
                        print(e)
                        messages.add_message(request, messages.ERROR,
                                             ugettext("2. Try: " + str(e)))
                replicates = []
                overall_count += counter
                counter = 0
                #print(current)
        if replicates:
            #Replicate.objects.bulk_create(replicates)
            replicates = []
            overall_count += counter

        # Adding replicates:
#        for profile in profiles:
#            replicates = Replicate.objects.filter(profile_id=profile.pk)
#            for replicate in replicates:
#                profile.replicates.add(replicate)
#profiles[index].replicates.add(replicate)

        msg = "Successfully integrated profiles."
        print(msg)
        messages.add_message(request, messages.SUCCESS, ugettext(msg))

        # Cleaning up:
        request.POST['file'] = ''
        data = ''
        import gc
        gc.collect()
        redirect('/expressions/profiles/')

    ctx = {'form': form, 'action': 'Add'}
    return render_to_response('expressions/profile_form.html',
                              ctx,
                              context_instance=RequestContext(request))
コード例 #12
0
def edit_profile(request):
    """
    Show and edit user profile.
    """
    username = request.user.username

    if request.method == 'POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            nickname = form.cleaned_data['nickname']
            intro = form.cleaned_data['intro']
            try:
                profile = Profile.objects.get(user=request.user.username)
            except Profile.DoesNotExist:
                profile = Profile()
                
            profile.user = username
            profile.nickname = nickname
            profile.intro = intro
            profile.save()
            messages.success(request, _(u'Successfully edited profile.'))
            # refresh nickname cache
            refresh_cache(request.user.username)
            
            return HttpResponseRedirect(reverse('edit_profile'))
        else:
            messages.error(request, _(u'Failed to edit profile'))
    else:
        try:
            profile = Profile.objects.get(user=request.user.username)
            form = ProfileForm({
                    'nickname': profile.nickname,
                    'intro': profile.intro,
                    })
        except Profile.DoesNotExist:
            form = ProfileForm()

    # common logic
    try:
        server_crypto = UserOptions.objects.is_server_crypto(username)
    except CryptoOptionNotSetError:
        # Assume server_crypto is ``False`` if this option is not set.
        server_crypto = False   

    sub_lib_enabled = UserOptions.objects.is_sub_lib_enabled(username)

    default_repo_id = UserOptions.objects.get_default_repo(username)
    if default_repo_id:
        default_repo = seafile_api.get_repo(default_repo_id)
    else:
        default_repo = None
    owned_repos = seafile_api.get_owned_repo_list(username)

    return render_to_response('profile/set_profile.html', {
            'form': form,
            'server_crypto': server_crypto,
            "sub_lib_enabled": sub_lib_enabled,
            'force_server_crypto': settings.FORCE_SERVER_CRYPTO,
            'default_repo': default_repo,
            'owned_repos': owned_repos,
            }, context_instance=RequestContext(request))
コード例 #13
0
ファイル: views.py プロジェクト: mdek/flightloggin2
def profile(request):

    profile = Profile.objects.get_or_create(user=request.display_user)[0]
    column = Columns.objects.get_or_create(user=request.display_user)[0]
    auto = AutoButton.objects.get_or_create(user=request.display_user)[0]

    if request.POST:
        profile_form = ProfileForm(request.POST, instance=profile)
        user_form = UserForm(request.POST, instance=request.display_user)
        column_form = ColumnsForm(request.POST,
                                  prefix="column",
                                  instance=column)
        auto_form = AutoForm(request.POST, prefix="auto", instance=auto)
        password_form = ChangePasswordForm(request.POST,
                                           prefix='pass',
                                           user=request.user)

        if request.POST.get("submit") == "Delete All Flights":
            Flight.objects.filter(user=request.display_user).delete()
            edit_logbook.send(sender=request.display_user)

        elif request.POST.get("submit") == "Delete All Events":
            NonFlight.objects.filter(user=request.display_user).delete()

        elif request.POST.get("submit") == "Delete Unused Planes":
            Plane.objects.filter(flight__isnull=True,
                                 user=request.display_user).delete()
            edit_logbook.send(sender=request.display_user)

        elif request.POST.get("submit") == "Completely Reset All Data":
            NonFlight.objects.filter(user=request.display_user).delete()
            Flight.objects.filter(user=request.display_user).delete()
            Records.objects.filter(user=request.display_user).delete()
            Location.objects.filter(loc_class=3,
                                    user=request.display_user).delete()
            Plane.objects.filter(user=request.display_user).delete()
            edit_logbook.send(sender=request.display_user)

        else:

            if auto_form.is_valid():
                auto_form.save()

            if profile_form.is_valid():
                profile_form.save()

            if column_form.is_valid():
                column_form.save()

            if user_form.is_valid():
                ## remove illegal characters and spaces
                user = user_form.save(commit=False)
                user.username = \
                    re.sub(r'\W', '', user.username)\
                    .replace(" ",'')

                if request.display_user.id == settings.DEMO_USER_ID:
                    ## don't let anyone change the demo's username or email
                    ## it will break stuff
                    user_form.cleaned_data['username'] = '******'
                    user_form.cleaned_data['email'] = '*****@*****.**'

                user.save()

            if password_form.is_valid():
                password_form.save()
    else:
        profile_form = ProfileForm(instance=profile)
        user_form = UserForm(instance=request.display_user)
        column_form = ColumnsForm(prefix="column", instance=column)
        auto_form = AutoForm(prefix="auto", instance=auto)
        password_form = ChangePasswordForm(prefix='pass')

    f1 = '<td class="{cls}">{checkbox}</td>'
    f2 = '<td class="title">{title}</td><td class="description">{desc}</td>\n'

    bool_fields = []
    ## mix the auto button and the columns fields into the same html table
    ## FIXME: this should all be in a template tag
    for field in OPTION_FIELDS:
        row = []

        row.append("<tr>\n")

        if auto_form.fields.get(field):
            checkbox = str(auto_form[field])
        else:
            checkbox = "<input type='checkbox' style='visibility: hidden'>"

        row.append(f1.format(checkbox=checkbox, cls="aauto"))

        if column_form.fields.get(field):
            formatted = f1.format(checkbox=str(column_form[field]),
                                  cls="column")
            row.append(formatted)
        else:
            row.append('<td class="column"></td>')

        formatted = f2.format(title=FIELD_TITLES[field],
                              desc=column_form[field].help_text)

        row.append(formatted)

        row.append("</tr>\n")
        bool_fields.append("".join(row))

    return locals()
コード例 #14
0
ファイル: views.py プロジェクト: Gabkings/usence
 def get_template_values(self):
     template_values = super(UserProfileView, self).get_template_values()
     form = ProfileForm()
     template_values['form'] = form
     return template_values
コード例 #15
0
def edit(request):
    key = ApiKey.objects.get(user=request.user)
    if request.method == 'POST':

        form = ProfileForm(request.POST, request=request)
        if form.is_valid():
            # update basic data
            email = form.cleaned_data.get("email")
            first_name = form.cleaned_data.get("first_name")
            last_name = form.cleaned_data.get("last_name")
            #OWC Additional fields are added
            phoneno = form.cleaned_data.get("phoneno")
            current_working_city = form.cleaned_data.get(
                "current_working_city")
            currently_working_facility = form.cleaned_data.get(
                "currently_working_facility")
            staff_type = form.cleaned_data.get("staff_type")
            nurhi_sponsor_training = form.cleaned_data.get(
                "nurhi_sponsor_training")
            current_place_employment = form.cleaned_data.get(
                "current_place_employment")
            highest_education_level = form.cleaned_data.get(
                "highest_education_level")
            religion = form.cleaned_data.get("religion")
            sex = form.cleaned_data.get("sex")
            age = form.cleaned_data.get("age")

            request.user.email = email
            request.user.first_name = first_name
            request.user.last_name = last_name
            #OWC Additional fields are added
            request.user.phoneno = phoneno
            request.user.current_working_city = current_working_city
            request.user.currently_working_facility = currently_working_facility
            request.user.staff_type = staff_type
            request.user.nurhi_sponsor_training = nurhi_sponsor_training
            request.user.current_place_employment = current_place_employment
            request.user.highest_education_level = highest_education_level
            request.user.religion = religion
            request.user.sex = sex
            request.user.age = age

            request.user.save()
            messages.success(request, _(u"Profile updated"))

            # if password should be changed
            password = form.cleaned_data.get("password")
            if password:
                request.user.set_password(password)
                request.user.save()
                messages.success(request, _(u"Password updated"))
    else:
        request.user = CustomUser.objects.get(pk=request.user.id)

        form = ProfileForm(initial={
            'username': request.user.username,
            'email': request.user.email,
            'first_name': request.user.first_name,
            'last_name': request.user.last_name,
            'phoneno': request.user.phoneno,
            'current_working_city': request.user.current_working_city,
            'currently_working_facility':
            request.user.currently_working_facility,
            'staff_type': request.user.staff_type,
            'nurhi_sponsor_training': request.user.nurhi_sponsor_training,
            'current_place_employment': request.user.current_place_employment,
            'highest_education_level': request.user.highest_education_level,
            'religion': request.user.religion,
            'sex': request.user.sex,
            'age': request.user.age,
            'api_key': key.key
        },
                           request=request)

    return render(request, 'oppia/profile/profile.html', {
        'form': form,
    })
コード例 #16
0
def review():
    review_form = ReviewForm(request.form)
    profile_form = ProfileForm()
    if request.method == 'POST' and review_form.validate():
        reviewerid = review_form['reviewerid']
        partnerid = review_form['partnerid']
        reviewerid = int(reviewerid.raw_data[0])
        partnerid = int(partnerid.raw_data[0])
        classID = review_form['classID']
        classID = int(classID.raw_data[0])
        percentage = review_form['percentage']
        percentage = int(percentage.raw_data[0])
        repartner = review_form['repartner']
        repartner = int(repartner.raw_data[0])
        prof = review_form['professorid']
        prof = str(prof.raw_data[0])
        grade = review_form['grade']
        grade = int(grade.raw_data[0]) / 25

        #make sure that the reviewer has a profile - if they don't make them make one
        if len(student_exists(reviewerid)) == 0:
            return render_template(
                'create_profile.html',
                form=profile_form,
                error=
                'No fair reviewing a friend if you don\'t have your own profile! Make one before you proceed.'
            )
        if len(student_exists(partnerid)) == 0:
            return render_template(
                'create_profile.html',
                form=profile_form,
                error=
                'That person\'s not registered yet. Make a profile for them before you review!'
            )

        #make sure that both are listed as having taken the class
        if taken_class(reviewerid, classID) == 0:
            session.execute(
                "insert into taken(classID, studentID) values (:classID, :reviewerid)",
                {
                    'reviewerid': reviewerid,
                    'classID': classID
                })
        if taken_class(partnerid, classID) == 0:
            session.execute(
                "insert into taken(classID, studentID) values (:classID, :partnerid)",
                {
                    'partnerid': partnerid,
                    'classID': classID
                })
        try:
            session.execute(
                "insert into reviews (classID, reviewerid, partnerid, grade, percentage, repartner, prof) values (:classID, :reviewerid, :partnerid, :grade, :percentage, :repartner, :prof)",
                {
                    'classID': classID,
                    'reviewerid': reviewerid,
                    'partnerid': partnerid,
                    'grade': grade,
                    'percentage': percentage,
                    'repartner': repartner,
                    'prof': prof
                })
            session.commit()
            return redirect(url_for('get_student_profile', id=partnerid))
        except exc.SQLAlchemyError:
            return render_template(
                'error.html',
                error=
                'Hey now - you can\'t take a class more than once. You or your partner is already registered.',
                link="/review",
                destination='back')
    return render_template('create_review.html', form=review_form)
コード例 #17
0
ファイル: views.py プロジェクト: jeevan-naidu/ansrportal
    def post(self, request):
        context = {"form": ""}
        form = ProfileForm(request.POST)
        if form.is_valid():
            try:
                requisition_number = Count.objects.get(
                    requisition_number=form.cleaned_data['requisition_number'].
                    requisition_number.id,
                    recruiter=request.user.id)
                candidate_name = form.cleaned_data['candidate_name']
                mobile_number = form.cleaned_data['mobile_number']
                email_id = form.cleaned_data['email_id']
                gender = form.cleaned_data['gender']
                date_of_birth = form.cleaned_data['date_of_birth']
                source = form.cleaned_data['source']
                referred_by = form.cleaned_data['refered_by']
                interview_by = form.cleaned_data['interview_by']
                interview_on = form.cleaned_data['interview_on']
                interview_status = form.cleaned_data['interview_status']
                remark = form.cleaned_data['remark']
                mobilenocheck = uniquevalidation(mobile_number)
                if interview_status == 'rejected':
                    candidate_status = 'rejected'
                else:
                    candidate_status = 'in_progress'
                if mobilenocheck:
                    context[
                        'error'] = "Candidate with same phone number is already avaliable"
                    context["form"] = form
                    return render(request, "candidateform.html", context)
                if referred_by:
                    profile = Profile(candidate_name=candidate_name,
                                      date_of_birth=date_of_birth,
                                      gender=gender,
                                      mobile_number=mobile_number,
                                      email_id=email_id,
                                      requisition_number=requisition_number,
                                      source=source,
                                      candidate_status=candidate_status,
                                      referred_by=referred_by)
                else:
                    profile = Profile(candidate_name=candidate_name,
                                      date_of_birth=date_of_birth,
                                      gender=gender,
                                      mobile_number=mobile_number,
                                      email_id=email_id,
                                      requisition_number=requisition_number,
                                      source=source,
                                      candidate_status=candidate_status)

                profile.save()
                process = Process.objects.create(
                    interview_step="test",
                    interview_status=interview_status,
                    interview_on=interview_on,
                    profile=profile,
                    feedback=remark)
                process.save()
                process.interview_by.add(interview_by)
            except Exception as programmingerror:
                context['error'] = programmingerror
                context["form"] = form
                return render(request, "candidateform.html", context)

        else:
            context["form"] = form
            return render(request, "candidateform.html", context)

        return HttpResponseRedirect('/hire/candidatesearch/')
コード例 #18
0
ファイル: views.py プロジェクト: jeevan-naidu/ansrportal
 def get(self, request):
     context = {"form": ""}
     form = ProfileForm()
     context["form"] = form
     return render(request, "candidateform.html", context)
コード例 #19
0
def index():
    user = current_user
    form = ProfileForm(email=current_user.email,
                       role_code=current_user.role_code,
                       next=request.args.get('next'))
    return render_template('manage/index.html', form=form)
コード例 #20
0
def profile():

    my_form = ProfileForm()

    my_data = Profile()
    my_data.remove_none_values()

    # print("my_form.validate_on_submit()", my_form.validate_on_submit())
    # print(my_form.errors)
    if my_form.validate_on_submit():

        # print("************ FORM SUBMITTED****")
        my_data.first_name = request.form.get('first_name')
        my_data.last_name = request.form.get('last_name')
        my_data.email = request.form.get('email')
        my_data.dob = request.form.get('dob')
        # print("first_name", my_data.first_name)
        # print("last_name", my_data.last_name)

        # process file
        file = request.files.get('file_photo')
        if file:
            orig_filename = secure_filename(file.filename)
            file_extension = os.path.splitext(orig_filename)
            file_extension = str(file_extension[1]).lower()

            new_filename = str(uuid.uuid1()) + file_extension

            # save to upload folder
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], new_filename))
            # print("file saved")

            my_data.file_photo_filename = orig_filename
            my_data.file_photo_code = new_filename

        # ---------------EXCEL/CSV - Load into table
        data_file = request.files.get('excel_file')
        print("data_file", data_file)
        if data_file:
            orig_filename = secure_filename(data_file.filename)
            file_extension = os.path.splitext(orig_filename)
            file_extension = str(file_extension[1]).lower()

            new_filename = str(uuid.uuid1()) + file_extension

            file_full_path = os.path.join(app.config['UPLOAD_FOLDER'],
                                          new_filename)

            # save to upload folder
            data_file.save(file_full_path)
            # print("file_full_path", file_full_path)
            my_data.file_data_filename = orig_filename
            my_data.file_data_code = new_filename

            # load the data in the table using pandas
            df = pd.read_csv(file_full_path)
            rest_list_raw = df.to_dict('records')
            rest_list = []
            for rest in rest_list_raw:
                my_rest = Restaurant()
                my_rest.bill = rest['bill']
                my_rest.tip = rest['tip']
                rest_list.append(my_rest)
            db.session.bulk_save_objects(rest_list)
            db.session.commit()

        # save to database
        db.session.add(my_data)
        db.session.commit()
        # print("my_data", my_data.id)

        # redirect to display page
        return redirect('/profile/' + str(my_data.id))  # profile/5

    return render_template('profile.html', my_form=my_form, my_data=my_data)
コード例 #21
0
ファイル: views.py プロジェクト: prryplatypus/aulavirtual
def profile():
    form = ProfileForm(email=current_user.email,
                       username=current_user.username,
                       profile=current_user.profile)
    return render_template("profile.html", module="profile", form=form)
コード例 #22
0
def profile():
    form = ProfileForm()
    return render_template("profile.html", form=form)