Beispiel #1
0
 def test_survey_expired(self):
     listing = Listing(expired=1, uuid="123")
     listing.save()
     request = HttpRequest()
     request.method = "GET"
     response = vars(views)["survey"](request, "123")
     self.assertTrue("Survey for this listing has expired" in vars(response)["_container"][0])
Beispiel #2
0
def register_listing(request):
    if request.method == 'POST':
        if request.user.is_authenticated and request.user.is_realtor:
            user_id=request.POST['user_id']
            realtor_email=request.POST['realtor_email']
            realtor_name=Realtor.objects.get(name=realtor_email)
     
            title=request.POST['title']
            address=request.POST['address']
            city=request.POST['city']
            state=request.POST['state']
            zipcode=request.POST['zipcode']
            description=request.POST['description']
            price=request.POST['price']
            bedrooms=request.POST['bedrooms']
            bathrooms=request.POST['bathrooms']
            garage=request.POST['garaze']
            sqft=request.POST['sqft']
            lot_size=request.POST['lot_size']
            photo_main=request.FILES['photo_main']
            photo_1=request.FILES['photo_1']
            
            fs=FileSystemStorage()
            fs.save(photo_main.name,photo_main)
            fs.save(photo_1.name,photo_1)
            
            register_listing=Listing(title=title,address=address,city=city,state=state,zipcode=zipcode,description=description,price=price,bedrooms=bedrooms
                                        ,bathrooms=bathrooms,garage=garage,sqft=sqft,lot_size=lot_size,photo_main=photo_main,photo_1=photo_1,user_id=request.user.id,realtor=realtor_name
            )
            register_listing.save()
            return redirect('register_listing')
    else:
        return render(request,'accounts/register_listing.html')
Beispiel #3
0
def neworder(request):
    if request.method== 'POST':
        username=request.POST['username']
        item=request.POST['item']
        quant=request.POST['quant']
        invoice=request.POST['invoice']
        pic=request.POST['pic']
        if Listing.objects.all().filter(invoice=invoice).exists():
            if Listing.objects.all().filter(invoice=invoice,username=username).exists():
             messages.error(request,'Invoice No. already exists, check in Previours orders')
             return redirect('neworder')
            else:
             messages.error(request,'Duplicate Invoice No.')
             return redirect('neworder')                
        else:
            a=Acc.objects.all().filter(username=username)
            a=a[0]
            l=Listing(accs=a,username=username,item=item,quantity=quant,invoice=invoice,pic=pic)
            l.save()
            return redirect('prevorders')
    else:
     u=request.user.username
     a=Acc.objects.all().filter(username=u)
     a=a[0]
     if a.isgov:
      return redirect('govlists')
     else:
      return render(request,'listings/newfarm.html')
Beispiel #4
0
def submitListing(request):
    if request.method == "POST":
        form = ListingForm(request.POST)
        if form.is_valid():
            building = form.cleaned_data["building"]
            room = form.cleaned_data["room"]
            start_lease = form.cleaned_data["start_lease"]
            end_lease = form.cleaned_data["end_lease"]
            posters_email = form.cleaned_data["posters_email"]
            price = form.cleaned_data["price"]
            negotiable = form.cleaned_data["negotiable"]
            description = form.cleaned_data["description"]
            l = Listing(
                building=building,
                room=room,
                start_lease=start_lease,
                end_lease=end_lease,
                posters_email=posters_email,
                price=price,
                negotiable=negotiable,
                description=description,
            )
            l.save()
            template = loader.get_template("submitAfter.html")
            dict = {"listingID": l.id, "listing": l}
            c = RequestContext(request, dict)
            return HttpResponse(template.render(c))
    else:
        form = ListingForm()

    return render(request, "submit.html", {"form": form})
Beispiel #5
0
def create_listing():
    """Creates an address object combining different elements from the list"""
    # logger.info("Creating address")
    street_number = ["221", "101", "550", "420", "13"]
    street_localities = [
        "Bakers Street",
        "Rajori Gardens",
        "Park Street",
        "MG Road",
        "Indiranagar",
    ]
    zipcodes = ["101234", "101232", "101231", "101236", "101239"]
    city = ["Chicago", "New York", "New Hampshire", "Boston"]
    state = ["WY", "AR", "NY", "CA"]
    description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    listing = Listing(
        realtor=random.choice(Realtor.objects.all()),
        title=random.choice(street_number) + " " +
        random.choice(street_localities),
        address=random.choice(street_number) + " " +
        random.choice(street_localities),
        city=random.choice(city),
        state=random.choice(state),
        zipcode=random.choice(zipcodes),
        description=description,
        price=random.randint(20, 60) * 10000,
        bedrooms=(random.randint(1, 4)),
        bathrooms=random.randint(1, 5),
        garage=random.randint(0, 3),
        sqft=random.randint(2000, 5000),
        lot_size=random.randint(2, 5),
    )
    listing.save()
    # logger.info("{} address created.".format(address))
    return listing
Beispiel #6
0
 	def test_survey_expired(self):
 		listing = Listing(expired=1, uuid='123')
 		listing.save()
 		request = HttpRequest()
 		request.method = 'GET'
 		response = vars(views)['survey'](request, '123')
 		self.assertTrue('Survey for this listing has expired' 
 				in vars(response)['_container'][0])
Beispiel #7
0
    def test_page_slugify_on_save(self):
        user = User()
        user.save()

        listing = Listing(title="A New Listing", description="A short description", price_per_month=120, total_area=234.34, author=user)
        listing.save()

        self.assertEqual(listing.slug, 'a-new-listing')
Beispiel #8
0
    def test_one_specific_page(self):
        user = User.objects.create() # This line will both create the user and save it
        listing = Listing(title="A New Listing", description="A short description", price_per_month=120, total_area=234.34, author=user)
        listing.save()

        response = self.client.get(reverse_lazy('listing-details-page', args=(listing.slug,)))

        self.assertEqual(response.status_code, 200)
Beispiel #9
0
 def create_listing(self):
     listing = Listing(creator="*****@*****.**",
                       address="2205 lower mall",
                       title="test",
                       text_content="test description",
                       for_sale="sell")
     listing.save()
     return listing
Beispiel #10
0
def save_rent_listing(prop_list, is_search_listing):
    is_search_listing = is_search_listing
    listing_id = prop_list['listing_id']
    prop_type = prop_list['prop_type']
    prop_status = prop_list['prop_status']
    last_update = prop_list['last_update']
    title = prop_list['address_new']['line']
    address = prop_list['address']
    city = prop_list['address_new']['city']
    postal_code = prop_list['address_new']['postal_code']
    state_code = prop_list['address_new']['state_code']
    state = prop_list['address_new']['state']
    price = prop_list['price']
    lat = prop_list['lat']
    lon = prop_list['lon']
    beds = prop_list['beds']
    baths = prop_list['baths']
    sqft = prop_list['sqft']
    neighborhood = ""
    photo=""
    try:
        neighborhood = prop_list['name']
    except KeyError:
        neighborhood = "N/A"

    try:
        photo = prop_list['photo']
    except KeyError:
        photo = ""


    listing = Listing(
        is_search_listing = is_search_listing,
        listing_id = listing_id,
        prop_type = prop_type,
        prop_status = prop_status,
        last_update = last_update,
        list_date = '',
        office_name = "N/A",
        title = title,
        address = address,
        city = city,
        postal_code = postal_code,
        state_code = state_code,
        state = state,
        neighborhood = neighborhood,
        price = price,
        lat = lat,
        lon = lon,
        beds = beds,
        baths = baths,
        sqft = sqft,
        lot_size = "N/A",
        rdc_web_url = "N/A",
        photo = photo)

    listing.save()
Beispiel #11
0
 	def test_survey_post_invalid(self):
 		listing = Listing(expired=0, uuid='123', category='Bricks', 
 					id=1, city='Hope', address='747 Fort Street',
 					title='selling stuff')
 		listing.save()
 		request = HttpRequest()
 		request.method = 'POST'
 		response = vars(views)['survey'](request, '123')
 		html = vars(response)['_container'][0]
 		self.assertTrue('This field is required' in html)
Beispiel #12
0
 	def test_survey_get(self):
 		listing = Listing(expired=0, uuid='123', category='Bricks', 
 					id=1, city='Hope', address='747 Fort Street',
 					title='selling stuff')
 		listing.save()
 		request = HttpRequest()
 		request.method = 'GET'
 		response = vars(views)['survey'](request, '123')
 		html = vars(response)['_container'][0]
 		self.assertTrue('selected="selected">Bricks</option>' in html)
 		self.assertTrue('selected="selected">Hope</option>' in html)
 		self.assertTrue('value="747 Fort Street"' in html)
 		self.assertTrue('value="selling stuff"' in html)
Beispiel #13
0
 def test_listing_transaction_success_rate_perfect(self):
     buyer_surveys = [Survey()]
     seller_surveys = [Survey()]
     buyer_listings = [Listing()]
     seller_listings = [Listing()]
     expected_bsr = 100
     expected_ssr = 100
     expected_tsr = 100
     actual_bsr, actual_ssr, actual_tsr = \
         vars(statistics)['__listing_transaction_success_rate'] \
         (buyer_surveys, seller_surveys, buyer_listings, seller_listings)
     self.assertEqual(expected_bsr, actual_bsr)
     self.assertEqual(expected_ssr, actual_ssr)
     self.assertEqual(expected_tsr, actual_tsr)
Beispiel #14
0
    def test_single_Listing(self):
        # Create a test Listing
        user = User.objects.create()

        listing = Listing(name="Test Listing",
                          description="Test",
                          owner=user,
                          price=2.00)
        listing.save()

        response = self.client.get(
            reverse('listing-detail', args=[listing.slug]))

        self.assertEqual(response.status_code, 200)
 def create_listing(self):
     new_listing = Listing(title="Test",
                           address="address",
                           city="city",
                           state="state",
                           zipcode=self.zipcode,
                           main_img="/media/test.jpg",
                           price=100000000,
                           bedrooms=5,
                           bathrooms=2,
                           garage=1,
                           square_feet=450,
                           seller=self.user)
     new_listing.save()
     return new_listing
Beispiel #16
0
 def test_survey_post_invalid(self):
     listing = Listing(
         expired=0,
         uuid="123",
         category="Bricks",
         id=1,
         city="Hope",
         address="747 Fort Street",
         title="selling stuff",
     )
     listing.save()
     request = HttpRequest()
     request.method = "POST"
     response = vars(views)["survey"](request, "123")
     html = vars(response)["_container"][0]
     self.assertTrue("This field is required" in html)
Beispiel #17
0
	def test_listing_to_statistics_no_survey(self):
		listing = Listing(id=1, for_sale='sell', url='test', 
				creator='*****@*****.**', created=datetime.now(),
				last_modified=datetime.now(), title='test',
				text_content='test', verified=True,
				category='Bricks', price='test',
				address='test street', city='test city',
				flag_count=1, expires=(datetime.now() + timedelta(days=30)),
				expired=1, survey_time_sent=None, uuid='1')
		listing.save()

		# Expect that 0 surveys were sent because no listing are
		# ready to have a survey sent. i.e. this is 1 expired listing.
		expected = 0
		actual = survey_mailer.expire_and_mail_surveys()
		self.assertEqual(expected, actual)
def createlisting(request):
    userEmail = request.POST['email'];
    listingTitle = request.POST['title'];

    l = Listing(firstname=request.POST['firstname'],lastname=request.POST['lastname'],
        title=listingTitle, description=request.POST['description'], 
        skillsNeeded=request.POST['skills'], dateAdded=timezone.now(),
        email=userEmail, image=request.FILES.get('image'), 
        video=request.POST.get('video'))
    l.save()

    email = EmailMessage(listingTitle+" Listing",
     "Use the following link to edit or delete your listing: http://127.0.0.1:8000/listings/edit/"+str(l.id),
     to=[userEmail])
    email.send()

    return redirect(reverse('detail', args=(l.id,)))
Beispiel #19
0
 def test_average_transaction_time_successful_transaction(self):
     now = timedelta(days=100)
     created = timedelta(days=0)
     survey_listings = [(Survey(time_submitted=now),
                         Listing(created=created))]
     expected = 100
     actual = vars(statistics)['__average_time_successful_transaction'](
         survey_listings)
     self.assertEqual(expected, actual)
Beispiel #20
0
 def test_survey_get(self):
     listing = Listing(
         expired=0,
         uuid="123",
         category="Bricks",
         id=1,
         city="Hope",
         address="747 Fort Street",
         title="selling stuff",
     )
     listing.save()
     request = HttpRequest()
     request.method = "GET"
     response = vars(views)["survey"](request, "123")
     html = vars(response)["_container"][0]
     self.assertTrue('selected="selected">Bricks</option>' in html)
     self.assertTrue('selected="selected">Hope</option>' in html)
     self.assertTrue('value="747 Fort Street"' in html)
     self.assertTrue('value="selling stuff"' in html)
Beispiel #21
0
def multiple_entries_for_testing(number):
    """
    Fill in test data in DB: writes 'number' of listing objects 
    """
    email = "*****@*****.**"
    title = " of " + str(number) + " test listings"
    content = """Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam cursus. Morbi ut mi. Nullam enim leo, egestas id, condimentum at, laoreet mattis, massa. Sed eleifend nonummy diam. Praesent mauris ante, elementum et, bibendum at, posuere sit amet, nibh. Duis tincidunt lectus quis dui viverra vestibulum. Suspendisse vulputate aliquam dui. Nulla elementum dui ut augue. Aliquam vehicula mi at mauris. Maecenas placerat, nisl at consequat rhoncus, sem nunc gravida justo, quis eleifend arcu velit quis lacus. Morbi magna magna, tincidunt a, mattis non, imperdiet vitae, tellus. Sed odio est, auctor ac, sollicitudin in, consequat vitae, orci. Fusce id felis. Vivamus sollicitudin metus eget eros.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In posuere felis nec tortor. Pellentesque faucibus. Ut accumsan ultricies elit. Maecenas at justo id velit placerat molestie. Donec dictum lectus non odio. Cras a ante vitae enim iaculis aliquam. Mauris nunc quam, venenatis nec, euismod sit amet, egestas placerat, est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras id elit. Integer quis urna. Ut ante enim, dapibus malesuada, fringilla eu, condimentum quis, tellus. Aenean porttitor eros vel dolor. Donec convallis pede venenatis nibh. Duis quam. Nam eget lacus. Aliquam erat volutpat. Quisque dignissim congue leo.
Mauris vel lacus vitae felis vestibulum volutpat. Etiam est nunc, venenatis in, tristique eu, imperdiet ac, nisl. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In iaculis facilisis massa. Etiam eu urna. Sed porta. Suspendisse quam leo, molestie sed, luctus quis, feugiat in, pede. Fusce tellus. Sed metus augue, convallis et, vehicula ut, pulvinar eu, ante. Integer orci tellus, tristique vitae, consequat nec, porta vel, lectus. Nulla sit amet diam. Duis non nunc. Nulla rhoncus dictum metus. Curabitur tristique mi condimentum orci. Phasellus pellentesque aliquam enim. Proin dui lectus, cursus eu, mattis laoreet, viverra sit amet, quam. Curabitur vel dolor ultrices ipsum dictum tristique. Praesent vitae lacus. Ut velit enim, vestibulum non, fermentum nec, hendrerit quis, leo. Pellentesque rutrum malesuada neque.
Nunc tempus felis vitae urna. Vivamus porttitor, neque at volutpat rutrum, purus nisi eleifend libero, a tempus libero lectus feugiat felis. Morbi diam mauris, viverra in, gravida eu, mattis in, ante. Morbi eget arcu. Morbi porta, libero id ullamcorper nonummy, nibh ligula pulvinar metus, eget consectetuer augue nisi quis lacus. Ut ac mi quis lacus mollis aliquam. Curabitur iaculis tempus eros. Curabitur vel mi sit amet magna malesuada ultrices. Ut nisi erat, fermentum vel, congue id, euismod in, elit. Fusce ultricies, orci ac feugiat suscipit, leo massa sodales velit, et scelerisque mi tortor at ipsum. Proin orci odio, commodo ac, gravida non, tristique vel, tellus. Pellentesque nibh libero, ultricies eu, sagittis non, mollis sed, justo. Praesent metus ipsum, pulvinar pulvinar, porta id, fringilla at, est.
Phasellus felis dolor, scelerisque a, tempus eget, lobortis id, libero. Donec scelerisque leo ac risus. Praesent sit amet est. In dictum, dolor eu dictum porttitor, enim felis viverra mi, eget luctus massa purus quis odio. Etiam nulla massa, pharetra facilisis, volutpat in, imperdiet sit amet, sem. Aliquam nec erat at purus cursus interdum. Vestibulum ligula augue, bibendum accumsan, vestibulum ut, commodo a, mi. Morbi ornare gravida elit. Integer congue, augue et malesuada iaculis, ipsum dui aliquet felis, at cursus magna nisl nec elit. Donec iaculis diam a nisi accumsan viverra. Duis sed tellus et tortor vestibulum gravida. Praesent elementum elit at tellus. Curabitur metus ipsum, luctus eu, malesuada ut, tincidunt sed, diam. Donec quis mi sed magna hendrerit accumsan. Suspendisse risus nibh, ultricies eu, volutpat non, condimentum hendrerit, augue. Etiam eleifend, metus vitae adipiscing semper, mauris ipsum iaculis elit, congue gravida elit mi egestas orci. Curabitur pede.
Maecenas aliquet velit vel turpis. Mauris neque metus, malesuada nec, ultricies sit amet, porttitor mattis, enim. In massa libero, interdum nec, interdum vel, blandit sed, nulla. In ullamcorper, est eget tempor cursus, neque mi consectetuer mi, a ultricies massa est sed nisl. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Proin nulla arcu, nonummy luctus, dictum eget, fermentum et, lorem. Nunc porta convallis pede."""
    for i in xrange(0, number):
        sale = "sell"
        ver = True
        exp = False
        city = "Vancouver"
        if i % 2 == 0:
            sale = "want"
        if i % 5 == 0:
            ver = False
        if i % 7 == 0:
            exp = True
        if i % 4 == 0:
            city = "Whistler"
        if i % 8 == 0:
            city = "Surrey"
        l = Listing(
            creator=email,
            title=str(i) + " - " + title,
            text_content=content,
            category="wood",
            for_sale=sale,
            city=city,
            verified=ver,
            expired=exp,
            price=str(i * i % 5),
        )
        l.set_url(tag_maker("_", l))
        l.save()
    return
Beispiel #22
0
def addListingPageView(request):
    if request.method == 'POST':

        new_listing = Listing()

        new_listing.job_title = request.POST.get('job_title')
        new_listing.contracts = request.POST.get('contract_length')
        new_listing.city = request.POST.get('city')
        new_listing.compensation = request.POST.get('compensation')
        new_listing.company_website = request.POST.get('company_website')
        new_listing.listing_id = (random.randint(
            209, 10000))  # had to manually input an id FIX ME: AUTOFILL PK

        new_listing.save()

        listing_data = Listing.objects.all()

        context = {'all_listings': listing_data, 'new_listing': new_listing}
        return render(request, 'organization/viewlisting.html', context)
    else:
        return HttpResponse("NOT FOUND")
Beispiel #23
0
	def test_listing_to_statistics_survey(self):
		listing = Listing(id=1, for_sale='sell', url='test', 
				creator='*****@*****.**', created=datetime.now(),
				last_modified=datetime.now(), title='test',
				text_content='test', verified=True,
				category='Bricks', price='test',
				address='test street', city='test city',
				flag_count=1, expires=(datetime.now() + timedelta(days=30)),
				expired=0, survey_time_sent=None, uuid='1')
		listing.save()

		# Expect that 1 survey was sent because one listing is
		# ready to have a survey sent.
		expected = 1
		actual = survey_mailer.expire_and_mail_surveys()
		self.assertEqual(expected, actual)

		# Simulate that a survey was submitted
		survey = Survey(id=1, listing_id=1, item='test item', category='Bricks',
				price=3, address='test street', city='test city',
				comments='test comments', time_submitted=datetime.now())
		survey.save()
		listing.survey_time_sent = datetime.now()
		listing.save()

		statistics.generate_statistics()

		stats = Statistics.objects.get(id=1)
		self.assertEqual(1, stats.number_surveys)
		self.assertEqual(1, stats.number_listings)
		self.assertEqual(0, stats.number_buyer_surveys)
		self.assertEqual(1, stats.number_seller_surveys)
		self.assertEqual(0, stats.number_buyer_listings)
		self.assertEqual(1, stats.number_seller_listings)
		self.assertEqual(3, stats.average_transaction_amount)
		self.assertEqual(0, stats.buyer_transaction_amount)
		self.assertEqual(3, stats.seller_transaction_amount)
		self.assertEqual(3, stats.successful_transaction_amount)
		self.assertEqual(0, stats.average_transaction_time)
		self.assertEqual(100, stats.buyer_transaction_success_rate)
		self.assertEqual(100, stats.seller_transaction_success_rate)
		self.assertEqual(100, stats.total_transaction_success_rate)

		stats_categories = StatisticsCategory.objects.filter(statistics_id=1)
		for cat in stats_categories:
			if cat.category == 'Bricks':
				self.assertEqual(1, cat.survey_count)
				self.assertEqual(0, cat.buyer_count)
				self.assertEqual(1, cat.seller_count)
				self.assertEqual(3, cat.amount)
			else:
				self.assertEqual(0, cat.survey_count)
				self.assertEqual(0, cat.buyer_count)
				self.assertEqual(0, cat.seller_count)
				self.assertEqual(0, cat.amount)
Beispiel #24
0
def save_bid(request, listing_id):
    listing = get_object_or_404(Listing, pk=listing_id)
    field_name = 'price'
    #obj = Listing.objects.first()
    field_value = getattr(listing, field_name)
    print("price", field_value)
    if request.method == 'POST':
        am = int(request.POST['am'])
        if field_value > am:
            messages.error(request,
                           'Bid price must be more than munimun price')
            return render(request, 'bid/bid.html', {'listing': listing})
        else:
            bid = Bid()
            bid.amount = request.POST['am']
            bid.bid_time = timezone.datetime.now()
            bid.user_id = Buyer.objects.get(user=request.user)
            bid.product = listing
            bid.save()
            listing = Listing()
            listing.num_bids = int(listing.num_bids) + 1
        return redirect('listings')
    return render(request, 'bid/bid.html', {'listing': listing})
Beispiel #25
0
 def test_listing_transaction_success_rate_seller(self):
     buyer_surveys = []
     seller_surveys = [Survey(), Survey()]
     buyer_listings = [Listing(), Listing(), Listing()]
     seller_listings = [Listing(), Listing(), Listing(), Listing()]
     expected_bsr = 0
     expected_ssr = 50
     expected_tsr = 2.0 / 7.0 * 100
     actual_bsr, actual_ssr, actual_tsr = \
         vars(statistics)['__listing_transaction_success_rate'] \
         (buyer_surveys, seller_surveys, buyer_listings, seller_listings)
     self.assertEqual(expected_bsr, actual_bsr)
     self.assertEqual(expected_ssr, actual_ssr)
     self.assertAlmostEqual(expected_tsr, actual_tsr, delta=0.0001)
Beispiel #26
0
 def test_average_transaction_time_successful_transaction_many(self):
     survey_listings = [
         (Survey(time_submitted=timedelta(days=1)),
          Listing(created=timedelta(days=0))),
         (Survey(time_submitted=timedelta(days=2)),
          Listing(created=timedelta(days=0))),
         (Survey(time_submitted=timedelta(days=3)),
          Listing(created=timedelta(days=0))),
         (Survey(time_submitted=timedelta(days=4)),
          Listing(created=timedelta(days=0))),
         (Survey(time_submitted=timedelta(days=5)),
          Listing(created=timedelta(days=0))),
         (Survey(time_submitted=timedelta(days=6)),
          Listing(created=timedelta(days=0))),
         (Survey(time_submitted=timedelta(days=7)),
          Listing(created=timedelta(days=0))),
         (Survey(time_submitted=timedelta(days=8)),
          Listing(created=timedelta(days=0))),
     ]
     expected = sum([1, 2, 3, 4, 5, 6, 7, 8]) / 8
     actual = vars(statistics)['__average_time_successful_transaction'](
         survey_listings)
     self.assertEqual(expected, actual)
Beispiel #27
0
def multiple_entries_for_testing(number):
    '''
    Fill in test data in DB: writes 'number' of listing objects 
    '''
    email = '*****@*****.**'
    title = ' of ' + str(number) + ' test listings'
    content = """Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam cursus. Morbi ut mi. Nullam enim leo, egestas id, condimentum at, laoreet mattis, massa. Sed eleifend nonummy diam. Praesent mauris ante, elementum et, bibendum at, posuere sit amet, nibh. Duis tincidunt lectus quis dui viverra vestibulum. Suspendisse vulputate aliquam dui. Nulla elementum dui ut augue. Aliquam vehicula mi at mauris. Maecenas placerat, nisl at consequat rhoncus, sem nunc gravida justo, quis eleifend arcu velit quis lacus. Morbi magna magna, tincidunt a, mattis non, imperdiet vitae, tellus. Sed odio est, auctor ac, sollicitudin in, consequat vitae, orci. Fusce id felis. Vivamus sollicitudin metus eget eros.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In posuere felis nec tortor. Pellentesque faucibus. Ut accumsan ultricies elit. Maecenas at justo id velit placerat molestie. Donec dictum lectus non odio. Cras a ante vitae enim iaculis aliquam. Mauris nunc quam, venenatis nec, euismod sit amet, egestas placerat, est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Cras id elit. Integer quis urna. Ut ante enim, dapibus malesuada, fringilla eu, condimentum quis, tellus. Aenean porttitor eros vel dolor. Donec convallis pede venenatis nibh. Duis quam. Nam eget lacus. Aliquam erat volutpat. Quisque dignissim congue leo.
Mauris vel lacus vitae felis vestibulum volutpat. Etiam est nunc, venenatis in, tristique eu, imperdiet ac, nisl. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In iaculis facilisis massa. Etiam eu urna. Sed porta. Suspendisse quam leo, molestie sed, luctus quis, feugiat in, pede. Fusce tellus. Sed metus augue, convallis et, vehicula ut, pulvinar eu, ante. Integer orci tellus, tristique vitae, consequat nec, porta vel, lectus. Nulla sit amet diam. Duis non nunc. Nulla rhoncus dictum metus. Curabitur tristique mi condimentum orci. Phasellus pellentesque aliquam enim. Proin dui lectus, cursus eu, mattis laoreet, viverra sit amet, quam. Curabitur vel dolor ultrices ipsum dictum tristique. Praesent vitae lacus. Ut velit enim, vestibulum non, fermentum nec, hendrerit quis, leo. Pellentesque rutrum malesuada neque.
Nunc tempus felis vitae urna. Vivamus porttitor, neque at volutpat rutrum, purus nisi eleifend libero, a tempus libero lectus feugiat felis. Morbi diam mauris, viverra in, gravida eu, mattis in, ante. Morbi eget arcu. Morbi porta, libero id ullamcorper nonummy, nibh ligula pulvinar metus, eget consectetuer augue nisi quis lacus. Ut ac mi quis lacus mollis aliquam. Curabitur iaculis tempus eros. Curabitur vel mi sit amet magna malesuada ultrices. Ut nisi erat, fermentum vel, congue id, euismod in, elit. Fusce ultricies, orci ac feugiat suscipit, leo massa sodales velit, et scelerisque mi tortor at ipsum. Proin orci odio, commodo ac, gravida non, tristique vel, tellus. Pellentesque nibh libero, ultricies eu, sagittis non, mollis sed, justo. Praesent metus ipsum, pulvinar pulvinar, porta id, fringilla at, est.
Phasellus felis dolor, scelerisque a, tempus eget, lobortis id, libero. Donec scelerisque leo ac risus. Praesent sit amet est. In dictum, dolor eu dictum porttitor, enim felis viverra mi, eget luctus massa purus quis odio. Etiam nulla massa, pharetra facilisis, volutpat in, imperdiet sit amet, sem. Aliquam nec erat at purus cursus interdum. Vestibulum ligula augue, bibendum accumsan, vestibulum ut, commodo a, mi. Morbi ornare gravida elit. Integer congue, augue et malesuada iaculis, ipsum dui aliquet felis, at cursus magna nisl nec elit. Donec iaculis diam a nisi accumsan viverra. Duis sed tellus et tortor vestibulum gravida. Praesent elementum elit at tellus. Curabitur metus ipsum, luctus eu, malesuada ut, tincidunt sed, diam. Donec quis mi sed magna hendrerit accumsan. Suspendisse risus nibh, ultricies eu, volutpat non, condimentum hendrerit, augue. Etiam eleifend, metus vitae adipiscing semper, mauris ipsum iaculis elit, congue gravida elit mi egestas orci. Curabitur pede.
Maecenas aliquet velit vel turpis. Mauris neque metus, malesuada nec, ultricies sit amet, porttitor mattis, enim. In massa libero, interdum nec, interdum vel, blandit sed, nulla. In ullamcorper, est eget tempor cursus, neque mi consectetuer mi, a ultricies massa est sed nisl. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Proin nulla arcu, nonummy luctus, dictum eget, fermentum et, lorem. Nunc porta convallis pede."""
    for i in xrange(0, number):
        sale = "sell"
        ver = True
        exp = False
        city = "Vancouver"
        if i % 2 == 0:
            sale = "want"
        if i % 5 == 0:
            ver = False
        if i % 7 == 0:
            exp = True
        if i % 4 == 0:
            city = 'Whistler'
        if i % 8 == 0:
            city = 'Surrey'
        l = Listing(creator=email,
                    title=str(i) + " - " + title,
                    text_content=content,
                    category='wood',
                    for_sale=sale,
                    city=city,
                    verified=ver,
                    expired=exp,
                    price=str(i * i % 5))
        l.set_url(tag_maker('_', l))
        l.save()
    return
Beispiel #28
0
    def post(self, request, filename, format=None):
        """
        accepts a CSV file and translates each row into a Listing and saves it

        """
        file_obj = request.data['file']
        text = TextIOWrapper(request.FILES['file'].file,
                             encoding='utf-8 ',
                             errors='replace')
        csv_reader = csv.reader(text, delimiter=',')
        line_count = 0
        for row in csv_reader:
            if line_count == 0:
                headers = row
                line_count += 1
            else:
                listing = Listing()
                listing.from_csv_row(headers, row)

                listing.save()
                line_count += 1
        return Response(status=200)
Beispiel #29
0
 def create_listing(self):
     listing = Listing(creator = "*****@*****.**", address = "2205 lower mall", title = "test", text_content = "test description", for_sale = "sell")
     listing.save()
     return listing
Beispiel #30
0
 	def test_is_survey_ready_false_not_passed_resend(self):
 		listing = Listing(expired=False, survey_time_sent=datetime.now(),
 					created=datetime.now())
 		actual = vars(survey_mailer)['__is_survey_ready'](listing)
 		self.assertFalse(actual)
Beispiel #31
0
 def test_get_valid_listing_found(self):
     listing = Listing(uuid="123")
     listing.save()
     # This should not raise an exception
     vars(views)["__get_valid_listing"]("123")
Beispiel #32
0
 	def test_get_valid_listing_found(self):
 		listing = Listing(uuid='123')
 		listing.save()
 		# This should not raise an exception
 		vars(views)['__get_valid_listing']('123')
    def fake_data(self):
        """
        Generate User / Profile and listing depends on user 

        Generate random listing base on the schema and add the user to listing

        """

        listings = 1
        how_many = int(input("How many ?"))
        while listings < how_many:
            title = self.fake.street_name()
            city = self.fake.city()
            state = self.fake.state()
            zipcode = self.fake.postalcode()

            # description = self.fake.text(max_nb_chars=200, ext_word_list=None)
            description = ""
            price = random.randint(100000, 500000)

            bedrooms = random.randint(1, 4)
            bathrooms = random.randint(1, 2)
            garage = random.randint(0, 1)
            square_feet = random.randint(500, 1000)
            imgs = self.gen_secondary_imgs()
            main_img = f"fake_data/main/1 ({listings}).jpeg"
            img_1 = f"fake_data/others/1 ({imgs[0]}).jpeg"
            img_2 = f"fake_data/others/1 ({imgs[1]}).jpeg"
            img_3 = f"fake_data/others/1 ({imgs[2]}).jpeg"
            img_4 = f"fake_data/others/1 ({imgs[3]}).jpeg"
            img_5 = f"fake_data/others/1 ({imgs[4]}).jpeg"

            is_published = bool(random.getrandbits(1))
            paid_fee = True
            list_date = self.fake.past_date(start_date="-2y", tzinfo=None)
            seller = self.gen_user_and_profile()

            listing = Listing(
                title=title,
                address=title,
                city=city,
                state=state,
                zipcode=zipcode,
                description=description,
                price=price,
                bedrooms=bedrooms,
                bathrooms=bathrooms,
                garage=garage,
                square_feet=square_feet,
                main_img=main_img,
                img_1=img_1,
                img_2=img_2,
                img_3=img_3,
                img_4=img_4,
                img_5=img_5,
                is_published=is_published,
                paid_fee=paid_fee,
                list_date=list_date,
                seller=seller,
            )
            listing.save()
            listings += 1
Beispiel #34
0
def index(request):
    listings = Listing.order_by('-list_date').filter(is_published=True)[:3]
    context = {'listings': listings}
    return render(request, 'pages/index.html')
Beispiel #35
0

def get_random_event():
    if randint(0, 1) == 0:
        return None
    events = Event.objects.all()
    return random.choice(events)


def get_random_user():
    users = User.objects.all()
    return random.choice(users)


chicago = Region.objects.first()

for i in range(5000):
    listing = Listing()
    listing.ticket_total = randint(1, 10)
    listing.price = randint(1, 500)
    listing.description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    listing.event = get_random_event()
    if listing.event is None:
        listing.bands = random_bands()
        listing.venue = 'Random Venue'
    listing.title = '%s tickets to %s' % (listing.ticket_total,
                                          listing.get_band_display())
    listing.region = chicago
    listing.seller = get_random_user()
    listing.save()
def scrapeListing(url, soup=None):
	logging.debug('Scraping %s', url)
	
	extension = url.split('/')[3]
	listingID = int(url.split('/')[4].split('.')[0])

	logging.info('Scraping listing %s', listingID)
	
	newListing = Listing(listingID=listingID)
	
	# Retrieve page and extract contents 
	try:
		if not soup:
			page = urllib.request.urlopen(url)
			soup = BeautifulSoup(page)    
		postingtitle = soup.find('h2','postingtitle').get_text()
		postingbody = soup.find('section',id='postingbody').get_text()
	except AttributeError:
		logging.error('Failed to parse listing %s', url)
		self = None
		return
		
	newListing.listingBody = postingbody
	newListing.title = postingtitle

	# Price 
	try:
		price = postingtitle.split()[0]
		price = price.split('$')[1]
		price = price.split('/m')[0]
		newListing.price = int(price)
	except (IndexError, ValueError):
		logging.warning('Non-$ price %s,', newListing.price)
		#newListing.price='' 

	# Type of listing
	newListing.listingType = extension
	if newListing.listingType == 'roo':
		newListing.shared = True;
	elif newListing.listingType == 'sub':
		newListing.sublet = True;
	

	# Address 
	try:
		address = soup.find('div','mapaddress').get_text()
		newListing.address = address.replace(',', ' ')
	except AttributeError:
		pass


	# Posting date
	postinginfos = soup.find('div','postinginfos')
	logging.debug('postinginfos: %s', postinginfos)
	for p in postinginfos.find_all('p','postinginfo'):
		postinginfo = p.get_text()
		if 'posted' in postinginfo:
			newListing.dateListingPosted = p.find('time')['datetime']
		elif 'updated' in postinginfo:
			newListing.dateListingUpdated = p.find('time')['datetime']
	if not newListing.dateListingUpdated:
		newListing.dateListingUpdated = newListing.dateListingPosted
			
	# Go through block of discrete attributes        
	attrgroup = soup.find('p','attrgroup')
	for span in attrgroup.find_all('span'):
		attribute = span.get_text()    
		if 'ft2' in attribute: 
			newListing.area = int(attribute.split('ft2')[0])
		elif 'laundry' in attribute or 'w/d' in attribute:
			newListing.laundry = attribute
		elif 'parking' in attribute or 'garage' in attribute or 'carport' in attribute:
			newListing.parking = attribute
		elif 'purrr' in attribute:
			newListing.catsAllowed = True
		elif 'wooof' in attribute:
			newListing.dogsAllowed = True
		elif 'no smoking' in attribute:
			newListing.noSmoking = True
		elif 'BR' in attribute:
			newListing.bedrooms = int(attribute.split('BR')[0])
		else:
			logging.debug('Mystery attribute: %s', attribute)
	logging.debug('attrgroup: ' + str(attrgroup))
	newListing.attributeGroup = str(attrgroup)

	# URLs
	newListing.listingUrl = url
	try:
		mapaddress = soup.find('p','mapaddress')
		newListing.mapUrl = mapaddress.find('a')['href']
	except AttributeError:
		pass
	
	# Geocode based on the Maps URL
	try:
		mapQueryString = newListing.mapUrl.split('?q=')[1]
		geocode = Geocoder.geocode(mapQueryString)
		newListing.city = geocode.locality
		county = geocode.administrative_area_level_2
		newListing.county = county.split(' ')[0]
		newListing.neighborhood = geocode.neighborhood
		newListing.zip = geocode.postal_code
	except:
		logging.debug('Geocoding error')
		pass
	
	# Region
	newListing.region = regionByZip(newListing)
		
	newListing.dateListingScraped = timezone.now()
	
	# Contact phone number
	try:
		newListing.phone = findPhone(postingbody)
	except AttributeError:
		logging.debug('No phone in posting, trying reply page')
	
	if not newListing.phone:
		try:
			replylink = soup.find('span','replylink').find('a')['href']
			if replylink:
				baseurl = url.split(extension)[0]
				replypage = str(urllib.request.urlopen(baseurl + replylink).read())
				newListing.phone = findPhone(replypage, True)
			else:
				logging.debug('No reply link on page')
		except:
			logging.debug('No phone from reply page')

	if not newListing.phone:
		newListing.phone = ''
			
		
	logging.debug('newListing (at the end) %s', newListing)
	return newListing
Beispiel #37
0
 def get(self):
     listings = Listing.get_featured_listings()
     return render_template('home.html', listings=listings)
Beispiel #38
0
 	def test_is_survey_ready_true_resend_ready(self):
 		listing = Listing(expired=False, 
 						survey_time_sent=datetime.now() - timedelta(days=1),
 						created=datetime.now() - timedelta(days=7))
 		actual = vars(survey_mailer)['__is_survey_ready'](listing)
 		self.assertTrue(actual)
Beispiel #39
0
def create_listing(request):
    '''
    Loads the page for the users to post a new listing (either sale items or wanted items)
    and when a new listing is submitted, it is saved in the database
    '''
    if request.user.is_authenticated():
        logtext = "Logout"
        accounttext = "My Account"
        welcometext = request.user.username
        logparams = [logtext, accounttext, welcometext]
    else:
        logtext = "Login"
        accounttext = "Sign Up"
        logparams = [logtext, accounttext]
    submit_action = URL_PATHS.get('listing_new')
    #create a new upload form that will be rendered to page
    pictureform = UploadForm()
    if request.method == 'GET':
        if request.user.is_authenticated():
            city = UserProfile.objects.get(username=request.user.email)
            form = ListingForm(instance=Listing(),
                               initial={
                                   'creator': request.user.email,
                                   'email_verification': request.user.email,
                                   'city': city
                               })
            form.fields['creator'].widget = forms.HiddenInput()
            form.fields['email_verification'].widget = forms.HiddenInput()
        else:
            form = ListingForm(instance=Listing())
        form_args = {
            'form': form,
            'submit_action': submit_action,
            'pictureform': pictureform,
            'logparams': logparams
        }
        return render_to_response(TEMPLATE_PATHS.get('listings_new'),
                                  form_args,
                                  context_instance=RequestContext(request))

    if request.method == 'POST':
        pictureform = UploadForm(request.POST, request.FILES)
        listing_form = ListingForm(request.POST)
        form_args = {}
        if request.user.is_authenticated():
            listing_form.fields['creator'].widget = forms.HiddenInput()
            listing_form.fields[
                'email_verification'].widget = forms.HiddenInput()
        #if the listing form is valid and the listing has not yet been created
        if listing_form.is_valid() and request.POST.get(
                "notnewlisting") == None:
            listing = listing_form.save(commit=False)

            #if user is logged in, then verify post
            if request.user.is_authenticated():
                listing.verified = True

            listing.set_url(tag_maker("_", listing))
            listing_url = listing.url
            listing_url = HttpRequest.build_absolute_uri(request, listing_url)

            listing.save()
            listingid = listing.id
            logger.debug('format', "createListing: debug")

        if request.POST.get("notnewlisting") != None:
            listingid = request.POST.get("listingid")
            listing = Listing.objects.get(id=listingid)
            listing_url = listing.get_url()
            form_args = {
                'form': listing_form,
                'submit_action': submit_action,
                'listing_url': listing_url,
                'listing': listing,
                'logparams': logparams
            }
        # if the picture form is valid, save the picture
        if pictureform.is_valid():
            form_args = {
                'listing': listing,
                'listing_url': listing_url,
                'logparams': logparams
            }
            photo = Photo(photo=request.FILES['picture'], listing=listing)
            photo.save()
            #if user wants to add another picture
            if request.POST.get('pictureform'
                                ) == "1" and request.POST.get("issubmit") != 1:
                photolist = Photo.objects.filter(listing_id=listing.id)
                addanotherprevious = list()
                #get all the names of the previously added pictures
                for o in Photo.objects.filter(listing_id=listing.id):
                    addanotherprevious.append(o.photo.name)

                form_args = {
                    'form': listing_form,
                    'submit_action': submit_action,
                    'pictureform': pictureform,
                    'listingid': listingid,
                    'addanotherprevious': addanotherprevious,
                    'logparams': logparams
                }
                return render_to_response(
                    "listings/listings_new.html",
                    form_args,
                    context_instance=RequestContext(request))

        #====================================================================
        # Testing purposes only - this just creates x # of listings
        # whenever a single one is created from the web, just used to
        # populate db for testing purposes
        #====================================================================
        #multiple_entries_for_testing(10000)

        if listing.verified:
            # if post is already verified, redirect user to their newly created post)
            return redirect("/listings/" + listing.url,
                            context_instance=RequestContext(request))

        # create a verification/edit link and send with mailer then direct to success message page
        user_email = listing.get_creator()
        verify_url = '%s%s?listing_id=%s&uuid=%s' % (
            Site.objects.get_current(), URL_PATHS.get('listings_edit-verify'),
            listing.id, listing.get_uuid())
        send_post_verification_email(verify_url, user_email, 'list')

        return render_to_response(TEMPLATE_PATHS.get('listings_success'),
                                  form_args,
                                  context_instance=RequestContext(request))
    raise Http404