Exemplo n.º 1
0
def new(request):
    company_form = CompanyForm()
    developer_form = formset_factory(DeveloperForm, min_num=1)
    
    if request.method == "POST":
        company_form = CompanyForm(request.POST, request.FILES)
        developer_form = developer_form(request.POST, request.FILES)
        
        if company_form.is_valid():
            company = company_form.save(commit=False)
            company.user = request.user
            company.save()
            
            if developer_form.is_valid():
                for dev in developer_form:
                    action = dev.save(commit=False)
                    action.company = company
                    action.save()
                messages.add_message(request, messages.SUCCESS, "New company with its team memebers have been saved successfully.")
                return redirect(reverse('companies_index'))
            else:
                company.delete()
                messages.add_message(request, messages.ERROR, "Team memebers saving failed. Check yout data.")
        else:
            messages.add_message(request, messages.ERROR, "Add new company failed. Check yout data.")
    data = {'company_form': company_form, 'developer_form': developer_form}
    return render(request, 'companies/new.html', data)
Exemplo n.º 2
0
 def test_localized_input(self):
     """
     Tests if form input is correctly localized
     """
     settings.USE_L10N = True
     activate("de-at")
     try:
         form6 = CompanyForm(
             {
                 "name": u"acme",
                 "date_added": datetime.datetime(2009, 12, 31, 6, 0, 0),
                 "cents_payed": decimal.Decimal("59.47"),
                 "products_delivered": 12000,
             }
         )
         self.assertEqual(True, form6.is_valid())
         self.assertEqual(
             form6.as_ul(),
             u'<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" value="acme" maxlength="50" /></li>\n<li><label for="id_date_added">Date added:</label> <input type="text" name="date_added" value="31.12.2009 06:00:00" id="id_date_added" /></li>\n<li><label for="id_cents_payed">Cents payed:</label> <input type="text" name="cents_payed" value="59,47" id="id_cents_payed" /></li>\n<li><label for="id_products_delivered">Products delivered:</label> <input type="text" name="products_delivered" value="12000" id="id_products_delivered" /></li>',
         )
         self.assertEqual(localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), "31.12.2009 06:00:00")
         self.assertEqual(datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data["date_added"])
         settings.USE_THOUSAND_SEPARATOR = True
         self.assert_(u"12.000" in form6.as_ul())
     finally:
         deactivate()
Exemplo n.º 3
0
 def test_localized_input(self):
     """
     Tests if form input is correctly localized
     """
     settings.USE_L10N = True
     activate('de-at')
     try:
         form6 = CompanyForm({
             'name':
             u'acme',
             'date_added':
             datetime.datetime(2009, 12, 31, 6, 0, 0),
             'cents_payed':
             decimal.Decimal('59.47'),
             'products_delivered':
             12000,
         })
         self.assertEqual(True, form6.is_valid())
         self.assertEqual(
             form6.as_ul(),
             u'<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" value="acme" maxlength="50" /></li>\n<li><label for="id_date_added">Date added:</label> <input type="text" name="date_added" value="31.12.2009 06:00:00" id="id_date_added" /></li>\n<li><label for="id_cents_payed">Cents payed:</label> <input type="text" name="cents_payed" value="59,47" id="id_cents_payed" /></li>\n<li><label for="id_products_delivered">Products delivered:</label> <input type="text" name="products_delivered" value="12000" id="id_products_delivered" /></li>'
         )
         self.assertEqual(
             localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)),
             '31.12.2009 06:00:00')
         self.assertEqual(datetime.datetime(2009, 12, 31, 6, 0, 0),
                          form6.cleaned_data['date_added'])
         settings.USE_THOUSAND_SEPARATOR = True
         # Checking for the localized "products_delivered" field
         self.assertTrue(
             u'<input type="text" name="products_delivered" value="12.000" id="id_products_delivered" />'
             in form6.as_ul())
     finally:
         deactivate()
Exemplo n.º 4
0
 def test_localized_input(self):
     """
     Tests if form input is correctly localized
     """
     settings.USE_L10N = True
     activate('de-at')
     try:
         form6 = CompanyForm({
             'name': u'acme',
             'date_added': datetime.datetime(2009, 12, 31, 6, 0, 0),
             'cents_payed': decimal.Decimal('59.47'),
             'products_delivered': 12000,
         })
         self.assertEqual(True, form6.is_valid())
         self.assertEqual(
             form6.as_ul(),
             u'<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" value="acme" maxlength="50" /></li>\n<li><label for="id_date_added">Date added:</label> <input type="text" name="date_added" value="31.12.2009 06:00:00" id="id_date_added" /></li>\n<li><label for="id_cents_payed">Cents payed:</label> <input type="text" name="cents_payed" value="59,47" id="id_cents_payed" /></li>\n<li><label for="id_products_delivered">Products delivered:</label> <input type="text" name="products_delivered" value="12000" id="id_products_delivered" /></li>'
         )
         self.assertEqual(localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), '31.12.2009 06:00:00')
         self.assertEqual(datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data['date_added'])
         settings.USE_THOUSAND_SEPARATOR = True
         # Checking for the localized "products_delivered" field
         self.assert_(u'<input type="text" name="products_delivered" value="12.000" id="id_products_delivered" />' in form6.as_ul())
     finally:
         deactivate()
Exemplo n.º 5
0
def create_company(request):
    if request.method == 'GET':
        template = 'new_position/new_company.html'
        form = CompanyForm()
        return render(
            request,
            template,
            {
                'form': form
            }
        )
    elif request.method == 'POST':
        form = CompanyForm(request.POST)
        if form.is_valid():
            company = Company(
                name = form.cleaned_data.get('name'),
                tag_name = form.cleaned_data.get('tag_name'),
                product = form.cleaned_data.get('product'),
                why_us = form.cleaned_data.get('why_us'),
                traction = form.cleaned_data.get('traction'),
                funding = form.cleaned_data.get('funding'),
                size = form.cleaned_data.get('size'),
                last_active = datetime.now(),
                market = form.cleaned_data.get('market'),
                company_link = form.cleaned_data.get('company_link'),
            )
            company.save()

            return render(
                request,
                'landing_pages/index.html',
            )
Exemplo n.º 6
0
def create_company():
    form = CompanyForm()
    if request.method == 'POST' and form.validate_on_submit():
        name = form.name.data
        username = form.username.data
        email = form.email.data
        website = form.website.data
        password = form.password.data
        confirm_password = form.confirm_password.data
        if password != confirm_password:
            return render_template('error.html',
                                   message='Password does not confirmed!',
                                   user=None)
        secret_key = form.secret_key.data
        company = Company()
        company.company_name = name
        company.website = website if website else ''
        company.secret_key = secret_key
        db.session.add(company)
        db.session.commit()
        db.session.refresh(company)
        user = User()
        user.user_password = sha256(str(password).encode('utf-8')).hexdigest()
        user.user_email = email
        user.user_username = username
        user.company_id = company.id
        db.session.add(user)
        db.session.commit()
        return redirect('/create_project')
    return render_template('company.html', form=form, user=None)
Exemplo n.º 7
0
def company_registraion(request):
    if request.method == 'POST':
        form = CompanyForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/companies/')
    else:
        form = CompanyForm()
    return render_to_response('company_registraion.html',{'form': form})
Exemplo n.º 8
0
def modify_account(request):
    uid = request.session.get('user')
    if request.method == 'POST':
        form = CompanyForm(request.POST)
        if form.is_valid():
            CompanyProfile.objects.filter(user_name_id=uid).update(user_name_id=uid,Company_name=request.POST['Company_name'], Corporation_type=request.POST['Corporation_type'], Adress= request.POST['Adress'], Zip_code=int(request.POST['Zip_code']), Country=request.POST['Country'], Providing_cloud_since=int(request.POST['Providing_cloud_since']))            
            return HttpResponseRedirect(reverse('accounts', args=(),   kwargs={'user_id': uid}))  
    else :
        form = CompanyForm()
    return render_to_response('modify_account.html', {'form':form},
                              context_instance=RequestContext(request))
Exemplo n.º 9
0
def my_company(request, id=None):
    company = get_object_or_404(Company, pk=id)
    if request.method == 'POST':
        form = CompanyForm(request.POST)
        if form.is_valid():
            updated_company = form.save(commit=False)
            updated_company.id = company.id
            updated_company.owner = company.owner
            updated_company.save()
    else:
        form = CompanyForm(instance=company)
    return render(request, 'my_company.html', {'form': form, 'company': company})
Exemplo n.º 10
0
def add_position():
    """Provide HTML form to adda new student record."""
    form = CompanyForm(request.form)
    if request.method == 'POST' and form.validate():
        need = Company()
        db.session.add(need)
        db.session.commit()
        flash('Account created! Check www.Intern.ly/position to see it. Thank you! ')
        # Success. Send the user back to the full appointment list.
        return redirect(url_for('company_index'))
    # Either first load or validation error at this point.
    return render_template('company/add.html', form=form)
Exemplo n.º 11
0
def new_user_company():
    form = CompanyForm()
    if form.validate_on_submit():
        company = Company(name=form.name.data, commercial_business=form.commercial_business.data,
                        employees=form.employees.data, company_seniority=form.company_seniority.data,
                        annual_sales=form.annual_sales.data, address=form.address.data,
                        company_phone=form.company_phone.data, user=current_user)
        db.session.add(company)
        db.session.commit()
        flash('Ya casi esta listo tu solicitud', 'is-success')
        return redirect(url_for('credit_request'))
    return render_template('user_company.html', title="Datos Comerciales", form=form)
Exemplo n.º 12
0
def edit_company(id):
    """
    Edit a company
    """
    check_admin()

    add_company = False

    company = Company.query.get_or_404(id)
    companyHasproperty = CompanyHasProperty.query.with_entities(
        CompanyHasProperty.p_id).filter(
            CompanyHasProperty.c_id == company.id).all()
    companyHasproperty_pid = [value for value, in companyHasproperty]
    form = CompanyForm(obj=company)

    property = Property.query.with_entities(Property.name).all()
    property_list = [value for value, in property]
    company_pid_list = companyHasproperty_pid
    company_pname_list = []
    for id in company_pid_list:
        property = Property.query.filter(Property.id == id).first()
        company_pname_list.append(property.name)

    if form.validate_on_submit():
        company.name = form.name.data
        companyHasproperty = CompanyHasProperty.query.filter(
            CompanyHasProperty.c_id == company.id).all()
        for i in companyHasproperty:
            db.session.delete(i)
        db.session.commit()
        property_names = request.form.getlist('company_property')
        for name in property_names:
            property = Property.query.filter(Property.name == name).first()
            companyHasproperty = CompanyHasProperty(c_id=company.id,
                                                    p_id=property.id)
            db.session.add(companyHasproperty)
            db.session.commit()
        flash('You have successfully edited the company.')

        # redirect to the property page
        return redirect(url_for('admin.list_company'))

    form.name.data = company.name
    form.category.data = company.category
    return render_template('admin/company/company.html',
                           action="Edit",
                           add_company=add_company,
                           form=form,
                           company=company,
                           company_pname_list=company_pname_list,
                           property_list=property_list,
                           title="Edit Company")
Exemplo n.º 13
0
def RegisterView(request):
    if request.method == 'POST':
        form = CompanyForm(request.POST)
        if form.is_valid():
            create_service_area(form.cleaned_data['name'], form.cleaned_data['json_coordinates'])
            redirect('/')
            return

        # Show errors
        errors = form.errors
        return render(request, 'register.html', {"errors": errors})

    return render(request, 'register.html')
Exemplo n.º 14
0
def insert_company():
    form = CompanyForm()
    name = form.name.data
    location = form.location.data
    balance = form.balance.data
    type = form.type.data
    if form.validate():
        company = OrmCompany(company_name=name,
                             company_location=location,
                             company_balance=balance,
                             company_type=type)
        db.session.add(company)
        db.session.commit()
    return redirect('/company')
Exemplo n.º 15
0
def RegisterView(request):
    if request.method == 'POST':
        form = CompanyForm(request.POST)
        if form.is_valid():
            create_service_area(form.cleaned_data['name'],
                                form.cleaned_data['json_coordinates'])
            redirect('/')
            return

        # Show errors
        errors = form.errors
        return render(request, 'register.html', {"errors": errors})

    return render(request, 'register.html')
Exemplo n.º 16
0
def completeCompanyInfoView(request):
    user = request.user.userprofile
  
    if request.method=='POST':
        form = CompanyForm(request.POST)
        if form.is_valid():
            company_factory = CompanyFactory()
            company_factory.save_instance_form(form=form, user=user)
            
            return HttpResponseRedirect('/positions/list')
    else:
        form = CompanyForm()
    ctx = {'form':form}
    return render_to_response('company_form.html', ctx, context_instance=RequestContext(request))
Exemplo n.º 17
0
def test():
    form = CompanyForm(request.form)
    if form.plus_button.data:
        form.locations.append_entry()
    elif form.minus_button.data:
        form.locations.pop_entry()
    elif form.validate_on_submit():
        print request.form['company_name']
        print len(form.locations.entries)
        for entry in form.locations.entries:
            print entry.data['location_id']
            print entry.data['city']
        return 'test form submitted!'
    print(form.errors)
    return render_template('test_field_list.html', companyForm=form)
Exemplo n.º 18
0
def createcompany(request):
    
    if request.method == 'POST': # If the form has been submitted...
        form = CompanyForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            form.save()
            return HttpResponseRedirect('/createpage/') # Redirect after POST
    else:
        form = CompanyForm() # An unbound form

    return render(request, "createpage/createcompany.html", {
        'form': form,
    })
Exemplo n.º 19
0
def companyDetailView(request):
    user = request.user.userprofile
    company = user.company
    if request.method=='POST':
        form = CompanyForm(request.POST)
        if form.is_valid():
            company_factory = CompanyFactory()
            company_factory.update_instance_form(form=form, company=company)
            
            return HttpResponseRedirect('/positions/list')
    else:
        form_loader = CompanyFormLoader()
        form = form_loader.load_initial_data(company)

    ctx={'form':form, 'company':company}
    return render_to_response('company_edit.html', ctx, context_instance=RequestContext(request))
Exemplo n.º 20
0
def create_company():
    form = CompanyForm(request.form)
    stored_user = DB.get_user(current_user.get_id())
    if DB.get_company(stored_user[0]['id']):
        data = DB.get_company(stored_user[0]['id'])
        return render_template('create-company.html',
                               data=data,
                               companyform=form)
    elif form.validate():
        DB.create_company(stored_user[0]['id'], form.company_name.data,
                          form.address1.data, form.address2.data,
                          form.phone.data, form.fax.data, form.email.data)
        return render_template(
            'launch.html',
            onloadmessage='Company Information Successfully Updated.')
    return render_template('create-company.html', companyform=form)
Exemplo n.º 21
0
def add_company():
    """
    Add a Company to the database
    """
    check_admin()

    add_company = True
    property = Property.query.with_entities(Property.name).all()

    form = CompanyForm()

    property_list = [value for value, in property]

    if form.validate_on_submit():
        company = Company(name=form.name.data, category=form.category.data)
        try:
            # add company to the database
            db.session.add(company)
            db.session.commit()

            company_property_list = request.form.getlist('company_property')
            company = Company.query.filter(
                Company.name == form.name.data).first()

            for name in company_property_list:
                property = Property.query.filter(Property.name == name).first()
                companyHasproperty = CompanyHasProperty(c_id=company.id,
                                                        p_id=property.id)
                db.session.add(companyHasproperty)
                db.session.commit()
            flash('You have successfully added a new Company.')
        except:
            # in case Company name already exists
            flash('Error: company name already exists.')

        # redirect to company page
        return redirect(url_for('admin.list_company'))
    else:
        # print (form.errors)
        # load company template
        return render_template('admin/company/company.html',
                               action="Add",
                               add_company=add_company,
                               form=form,
                               property_list=property_list,
                               title="Add Company")
Exemplo n.º 22
0
 def put(self, request):
     """
     Handling put method.
     :param request: Request to View.
     :return: HttpResponse with code 201 if company is updated or
     HttpResponseBadRequest if request contain incorrect data.
     """
     data = json.loads(request.body)
     data["administrator"] = AdviserUser.objects.get(
         id=data["administrator"])
     company = Company.get_company(data["id"])
     company_form = CompanyForm(data, company)
     if not company_form.is_valid():
         return HttpResponseBadRequest(
             "Invalid input data. Please edit and try again.")
     company.set_company(data)
     return HttpResponse(status=201)
Exemplo n.º 23
0
def company():
    result = []
    form = CompanyForm()
    companies = OrmCompany.query.all()
    for company in companies:
        result.append([
            company.company_name, company.company_location,
            company.company_balance, company.company_type
        ])
    return render_template('company.html', rows=result, form=form)
Exemplo n.º 24
0
 def test_localized_input(self):
     """
     Tests if form input is correctly localized
     """
     settings.USE_L10N = True
     activate('de-at')
     try:
         form6 = CompanyForm({
             'name': u'acme',
             'date_added': datetime.datetime(2009, 12, 31, 6, 0, 0),
         })
         form6.save()
         self.assertEqual(True, form6.is_valid())
         self.assertEqual(
             form6.as_ul(),
             u'<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" value="acme" maxlength="50" /></li>\n<li><label for="id_date_added">Date added:</label> <input type="text" name="date_added" value="31.12.2009 06:00:00" id="id_date_added" /></li>'
         )
         self.assertEqual(localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), '31.12.2009 06:00:00')
         self.assertEqual(datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data['date_added'])
     finally:
         deactivate()
Exemplo n.º 25
0
def create_company_view(corporation_slug_to_id, **kwargs):
    form = CompanyForm(corporation_slug_to_id)

    next_page = request.args.get('next')

    if request.method == 'POST':
        if form.submit_company.data and form.validate_on_submit():

            CompanyAccess(corporation_id=corporation_slug_to_id,
                          name=form.name_company.data.strip()). \
                create_company()
            flash('Your company is now live!')
            if next_page:
                return redirect(next_page)
            form.name_company.data = ''

        elif form.cancel_company.data:
            if next_page:
                return redirect(next_page)
            form.name_company.data = ''

    return render_template('create_company.html', form=form)
Exemplo n.º 26
0
def company_profile(request):
    from forms import CompanyForm
    engineer = Engineer.objects.get(user__username=request.user.username)
    mailserver_list = get_mx_list(engineer.company)
    company = engineer.company
    engineer_list = Engineer.objects.filter(company=company)
    form = CompanyForm(instance=company)
    message = None
    if request.method == 'POST':
        form = CompanyForm(data=request.POST, instance=company)
        if form.is_valid():
            form.save()
            message = "Company details updated successfully"


    return render_to_response("profiles/upd_company.html", {
                                'company_form': form,
                                'mailserver_list': mailserver_list,
                                'message': message,
                                'company': company,
                                'engineer_list': engineer_list,
                                },
                                context_instance=RequestContext(request))
Exemplo n.º 27
0
def create_interest_ranking_view(industry_name):
    """Interest growth ranking page in each industry sector."""

    form = CompanyForm(request.args)
    company_name = form.company.data

    industry = Industry.query.filter_by(name=industry_name).first()
    industries = Industry.query.all()
    companies = Company.query.filter(
        Company.industry_id == industry.industry_id,
        Company.ranking != None).order_by(Company.ranking).all()

    return render_template("interest_ranking.html",
                           companies=companies,
                           industries=industries,
                           industry_name=industry.name,
                           form=form)
Exemplo n.º 28
0
def my_companies(request):
    user = request.user
    if request.method == 'POST':
        form = CompanyForm(request.POST)
        if form.is_valid():
            company = form.save(commit=False)
            company.owner = user
            form.save()
    else:
        form = CompanyForm()
    companies = Company.objects.filter(owner=user)
    return render(request, 'my_companies.html', {'companies': companies, 'form': form})
Exemplo n.º 29
0
def company_profile(request):
    from forms import CompanyForm
    engineer = Engineer.objects.get(user__username=request.user.username)
    mailserver_list = get_mx_list(engineer.company)
    company = engineer.company
    engineer_list = Engineer.objects.filter(company=company)
    form = CompanyForm(instance=company)
    message = None
    if request.method == 'POST':
        form = CompanyForm(data=request.POST, instance=company)
        if form.is_valid():
            form.save()
            message = "Company details updated successfully"

    return render_to_response("profiles/upd_company.html", {
        'company_form': form,
        'mailserver_list': mailserver_list,
        'message': message,
        'company': company,
        'engineer_list': engineer_list,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 30
0
def company():
    return render_template('create-company.html', companyform=CompanyForm())
Exemplo n.º 31
0
def select_company():
    """Select Company for search."""

    form = CompanyForm()

    return render_template("home.html", form=form)
Exemplo n.º 32
0
def dashboard():
    form = CompanyForm()
    if request.method == 'POST':
        if form.validate():
            cmp_id = int(form.cmp.data)
            xAxis1 = {
                "categories": [datetime.datetime.now().year],
                "crosshair": 'true'
            }
            series1 = [{
                "name": 'LY YTD',
                "data": [cnx.calculate_ly_ytd(cmp_id)]
            }, {
                "name": 'CY YTD',
                "data": [cnx.calculate_cy_ytd(cmp_id)]
            }]
            top_companies = cnx.get_top_customers(cmp_id)

            xAxis2 = {"categories": [], "crosshair": 'true'}
            series2 = [{
                "name":
                'LY YTD',
                "data": [
                    cnx.calculate_ly_quaterly_ytd(cmp_id, 1),
                    cnx.calculate_ly_quaterly_ytd(cmp_id, 2),
                    cnx.calculate_ly_quaterly_ytd(cmp_id, 3),
                    cnx.calculate_ly_quaterly_ytd(cmp_id, 4)
                ]
            }, {
                "name":
                'CY YTD',
                "data": [
                    cnx.calculate_cy_quaterly_ytd(cmp_id, 1),
                    cnx.calculate_cy_quaterly_ytd(cmp_id, 2),
                    cnx.calculate_cy_quaterly_ytd(cmp_id, 3),
                    cnx.calculate_cy_quaterly_ytd(cmp_id, 4)
                ]
            }]

            xAxis3 = {
                "categories": [datetime.datetime.now().year],
                "crosshair": 'true'
            }
            series3 = [{
                "name": 'LY YTD',
                "data": cnx.calculate_category_ly_ytd(cmp_id)
            }, {
                "name": 'CY YTD',
                "data": cnx.calculate_category_ly_ytd(cmp_id)
            }]
            top_categories = cnx.get_top_categories(cmp_id)
            pie_chart_data = cnx.calculate_category_cy_ytd_pie(cmp_id)
            return render_template('form.html', form=form, list_companies=cnx.get_companies(), form_name='edit',\
                                   xAxis1=xAxis1, series1=series1, xAxis2=xAxis2, series2=series2, xAxis3=xAxis3, series3=series3,\
                                   top_companies=top_companies, top_categories=top_categories, pie_chart_data=pie_chart_data)
        else:
            return render_template('form.html',
                                   form=form,
                                   form_name='add',
                                   list_companies=cnx.get_companies())
    return render_template('form.html',
                           form=form,
                           form_name='add',
                           list_companies=cnx.get_companies())
Exemplo n.º 33
0
def create_main_view():
    """Create the company's search result view."""

    try:

        start = datetime.now()  # for checking runtime
        form = CompanyForm(request.args)
        company_name = form.company.data
        company_name = company_name.upper()
        company = Company.query.options(
            db.joinedload("industry")).filter_by(name=company_name).first()
        print('#' * 20, 'query',
              datetime.now() - start)  # for checking runtime

        company_infos = get_company_infos(company_name)
        print('#' * 20, 'infos',
              datetime.now() - start)  # for checking runtime

        location = get_maps(company_name)
        print('#' * 20, 'map', datetime.now() - start)  # for checking runtime
        print(location)

        job_listings = get_job_listings(company_name)
        print('#' * 20, 'job_listings',
              datetime.now() - start)  # for checking runtime

        if company.interest_growth:
            # interest growth data exists only for a company which has interest data.
            interest_chart = create_interest_chart(company)
            print('#' * 20, 'chart',
                  datetime.now() - start)  # for checking runtime
            interest_growth = company.interest_growth
            print('#' * 20, 'interest_growth',
                  datetime.now() - start)  # for checking runtime

            if company.ranking:
                ranking = company.ranking
                industry_name = company.industry.name
                industry_num = get_industry_num(company.industry.industry_id)
                print('#' * 20, 'industry_num & ranking',
                      datetime.now() - start)  # for checking runtime

            else:
                industry_name, industry_num, ranking = None, None, None

        else:
            interest_chart, interest_growth, ranking, industry_name, industry_num = None, None, None, None, None

        return render_template("main.html",
                               map_key=os.environ['MAP_KEY'],
                               form=form,
                               location=location,
                               salary_query=company.salaries,
                               company_name=company_name,
                               job_listings=job_listings,
                               interest_growth=interest_growth,
                               ranking=ranking,
                               industry_name=industry_name,
                               industry_num=industry_num,
                               company_infos=company_infos,
                               interest_chart=interest_chart)

    except AttributeError:

        flash("Please check the company name.")
        return redirect("/")
Exemplo n.º 34
0
    def post(self, request, *args, **kwargs):
        register_form = RegistrationForm(request.POST, instance=User())
        broker_profile_form = BrokerProfileForm(request.POST,
                                                instance=BrokerProfile())
        user_type_form = UserTypeForm(request.POST)
        contact_form = ContactNumberForm(request.POST, instance=ContactNumber())
        company_form = CompanyForm(request.POST, instance=Company())

        forms = {
            'user_type_form': user_type_form,
            'register_form': register_form,
            'broker_profile_form': broker_profile_form,
            'company_form': company_form,
            'contact_form': contact_form,
        }

        if user_type_form.is_valid():
            if register_form.is_valid():
                user = get_user_model().objects.create_user(
                    register_form.cleaned_data['email'],
                    register_form.cleaned_data['password'],
                    first_name=register_form.cleaned_data['first_name'],
                    last_name=register_form.cleaned_data['last_name'],
                )

                if user_type_form.cleaned_data['type'] == 'normal-user':
                    user = authenticate(username=user.email,
                                        password=register_form.cleaned_data[
                                            'password'])
                    login(self.request, user)
                    return reverse_lazy('index')

                if company_form.is_valid():
                    company, created = Company.objects.get_or_create(
                        name=company_form.cleaned_data['name'],
                        address=company_form.cleaned_data['address']
                    )
                    if broker_profile_form.is_valid():
                        BrokerProfile(
                            license_no=broker_profile_form.cleaned_data[
                                'license_no'],
                            user=user,
                            company=company,
                        ).save()
                    else:
                        user.delete()
                        return render(request, self.template_name, forms)

                else:
                    user.delete()
                    return render(request, self.template_name, forms)

                if contact_form.is_valid():
                    ContactNumber.objects.create(
                        contact_no=contact_form.cleaned_data['contact_no'],
                        user=user)
                else:
                    user.delete()
                    return render(request, self.template_name, forms)

            else:
                return render(request, self.template_name, forms)

        else:
            return render(request, self.template_name, forms)
        user = authenticate(username=register_form.cleaned_data['email'],
                            password=register_form.cleaned_data['password'])
        login(self.request, user)
        return HttpResponseRedirect(reverse_lazy('index'))