コード例 #1
0
    def post(self, request, *args, **kwargs):

        self.request_data = json.loads(self.request.body)

        name = self.request_data['name']
        products = self.request_data[
            'products'] if 'products' in self.request_data else None
        owner = self.request.user

        try:
            Store.objects.get(name=name)
            return JsonResponse({'msg': 'Name taken.'})

        except:
            pass

        try:
            json.loads(product)
            return JsonResponse({'msg': 'json malformed.'})

        except:
            pass

        store = Store(name=name, products=products, owner=owner)
        store.save()
        return JsonResponse({'id': store.pk.__str__()}, safe=False)
コード例 #2
0
    def test_can_be_set_for_a_store(self):
        store = Store(name='Test Store')
        store.location = Point(30.3333, 123.323)
        store.save()

        store = Store.objects.get(id=store.id)
        self.assertEquals(store.location.x, 30.3333)
        self.assertEquals(store.location.y, 123.323)
コード例 #3
0
def register():
    form = OwnerRegister()
    error = None
    if form.validate_on_submit():
        stimage_ts = None
        image_ts = None
        hash_pwd = generate_password_hash(form.password.data)
        if form.code.data == '10726629':
            ####save store_image#####
            if request.files.get('store_image'):
                #securing file's name
                filename = secure_filename(form.store_image.data.filename)
                #pathing
                file_path = os.path.join(UPLOAD_FOLDER_IMG, 'store', filename)
                #save image to path
                form.store_image.data.save(file_path)
                #image_ts=image name for img_src function to find images
                stimage_ts = str(
                    thumbnail_process(file_path, 'store',
                                      str(form.storecode.data)))
            if request.files.get('owner_image'):
                #securing file's name
                filename = secure_filename(form.owner_image.data.filename)
                #pathing
                file_path = os.path.join(UPLOAD_FOLDER_IMG, 'owner', filename)
                #save image to path
                form.owner_image.data.save(file_path)
                #image_ts=image name for img_src function to find images
                image_ts = str(
                    thumbnail_process(file_path, 'owner',
                                      str(form.storecode.data)))

            store = Store(username=form.username.data,
                          password=hash_pwd,
                          email=form.email.data,
                          storename=form.storename.data,
                          storecode=form.storecode.data)

            if stimage_ts:
                store.store_image = stimage_ts

            if image_ts:
                store.qr_image = image_ts
            store.save()

            return redirect(url_for('store_app.login'))
        else:
            error = 'Wrong code'

    return render_template('store/o_register.html', form=form, error=error)
コード例 #4
0
ファイル: import_stores.py プロジェクト: nikdoof/vapemap
    def handle(self, *args, **options):
        fn = args[0]
        if fn.startswith('http'):
            self.stdout.write("Downloading %s\n" % fn)
            f = StringIO(requests.get(fn).text)
        else:
            self.stdout.write("Opening file %s\n" % fn)
            f = open(fn, 'r')

        self.stdout.write('Formatting data...')
        # Generate the dataset
        reader = csv.reader(f)
        headers = [h.lower().strip() for h in reader.next()]
        data = []
        for row in reader:
            values = []
            for h, v in zip(headers, row):
                if v == '':
                    value = None
                else:
                    value = v.strip()
                values.append((h, value))
            data.append(dict(values))

        self.stdout.write('%d entries found.' % len(data))
        for row in data:
            self.stdout.write("Importing %s... " % row['name'])
            try:
                obj = Store.objects.get(name=row['name'])
            except Store.DoesNotExist:
                pass
            else:
                if obj.address.postcode == row['postcode']:
                    self.stdout.write("Store by that name already exists, skipping.\n")
                    continue
            with transaction.commit_on_success():
                if not row['country']:
                    row['country'] = 'United Kingdom'
                country, created = Country.objects.get_or_create(name=row['country'])
                county, created = County.objects.get_or_create(name=row['county'], country=country)
                addr = Address(name=row['name'], address1=row['address1'], address2=row['address2'],
                               address3=row['address3'], city=row['city'], county=county, country=country,
                               postcode=row['postcode'], geo_latitude=row['y'], geo_longitude=row['x'])
                addr.save(no_lookup=True)
                store = Store(name=row['name'], address=addr, website=row['website'], email=row['email'],
                              phone=row['phone'])
                if row['type']:
                    if row['type'] == 'Online':
                        store.store_type = Store.STORE_TYPE_ONLINE
                    if row['type'] == 'Retail':
                        store.store_type = Store.STORE_TYPE_RETAIL
                    if row['type'] == 'Both':
                        store.store_type = Store.STORE_TYPE_BOTH
                elif row['website']:
                    store.store_type = Store.STORE_TYPE_BOTH
                store.save()
                if row['twitter']:
                    Link(object_id=store.pk, object_type=ContentType.objects.get_for_model(store.__class__),
                         account_type=LinkType.objects.get(name='Twitter'),
                         account_name=row['twitter'].split('/')[-1]).save()
            self.stdout.write("Done\n")

        f.close()
        self.stdout.write("Done\n")
コード例 #5
0
ファイル: tests.py プロジェクト: nikdoof/vapemap
 def test_absolute_url(self):
     obj = Store(name='Test Store 2', address=self.addr)
     obj.save()
     self.assertEqual(str(obj.get_absolute_url()), '/stores/test-store-2/')
コード例 #6
0
ファイル: tests.py プロジェクト: nikdoof/vapemap
 def test_slug_creation(self):
     obj = Store(name='Test Store 1', address=self.addr)
     obj.save()
     self.assertEqual(obj.slug, 'test-store-1')
コード例 #7
0
    def handle(self, *args, **options):
        file_path = options.get('file')

        if not file_path:
            raise CommandError('File not provided!')

        if not file_path.endswith('.json'):
            raise CommandError('Import supports .json files only!')

        file_path = os.path.join('data', file_path)
        try:
            with open(file_path) as import_file:
                stores = json.load(import_file)
        except FileNotFoundError as e:
            raise CommandError('File at %s was not found!' % file_path)

        pizza_list = get_pizza_list()

        try:
            with transaction.atomic():
                for store in stores:
                    # Create owner in DB
                    owner_data = store['owner']
                    db_user = AuthUserModel.objects.create_user(
                        first_name=owner_data['first_name'],
                        last_name=owner_data['last_name'],
                        username=owner_data['email'],
                        email=owner_data['email'],
                        is_staff=1,
                        password='******')

                    db_store = Store(
                        owner=db_user,
                        name=store['name'],
                        logo=store['logo'],
                        delivery_fee=store['delivery_fee'],
                        profit_fee=store['profit_fee'],
                    )
                    db_store.save()

                    for pizza in pizza_list:
                        db_pizza = Pizza(
                            store=db_store,
                            name=pizza['name'],
                            image=pizza['image'],
                        )
                        db_pizza.save()

                        for ingredient in pizza['ingredients']:
                            db_ingredient = Ingredient.objects.filter(
                                name=ingredient['name']).first()

                            if not db_ingredient:
                                db_ingredient = Ingredient(
                                    name=ingredient['name'],
                                    image=ingredient['image'],
                                )
                                db_ingredient.save()

                            db_store_ingredient = StoreIngredients.objects.filter(
                                store=db_store,
                                ingredient=db_ingredient).first()

                            if db_store_ingredient:
                                db_store_ingredient.stock = ingredient['stock']
                                db_store_ingredient.price = ingredient['price']
                            else:
                                db_store_ingredient = StoreIngredients(
                                    store=db_store,
                                    ingredient=db_ingredient,
                                    stock=ingredient['stock'],
                                    price=ingredient['price'],
                                )
                            db_store_ingredient.save()

                            db_pizza_ingredient = PizzaIngredients.objects.filter(
                                store_ingredient=db_store_ingredient,
                                pizza=db_pizza).first()

                            if db_pizza_ingredient:
                                db_pizza_ingredient.quantity = ingredient[
                                    'quantity']
                            else:
                                db_pizza_ingredient = PizzaIngredients(
                                    pizza=db_pizza,
                                    store_ingredient=db_store_ingredient,
                                    quantity=ingredient['quantity'],
                                )
                            db_pizza_ingredient.save()
        except Exception as e:
            raise CommandError('Something wrong happened: [%s] %s' %
                               (type(e).__name__, e))
コード例 #8
0
 def create(self, validated_data):
     store = Store(name=validated_data.get('name', None))
     store.owner = self.context['request'].user
     store.save()
     return store
コード例 #9
0
ファイル: sample_data.py プロジェクト: Manalu/furnidashboard
def create_sample_data():

    now = datetime.now()
    this_m_first = datetime(now.year, now.month, 1)
    this_m_first = timezone.make_aware(this_m_first,
                                       timezone.get_current_timezone())

    last_m_mid = this_m_first - timedelta(days=16)

    last_m_first = datetime(last_m_mid.year, last_m_mid.month, 1)

    create_test_users()

    cust = Customer(first_name="TestCust1", last_name="L")
    cust.save()
    cust2 = Customer(first_name="TestCust2", last_name="L")
    cust2.save()
    cust3 = Customer(first_name="TestCust3", last_name="L")
    cust3.save()

    store1 = Store(name="Sacramento")
    store2 = Store(name="Roseville")
    store1.save()
    store2.save()

    users = User.objects.all()
    user1 = users.get(username="******")
    user2 = users.get(username="******")
    user3 = users.get(username="******")
    user4 = users.get(username="******")

    o = Order()
    o.number = 'SO-01-0001'
    o.order_date = this_m_first
    o.customer = cust
    o.status = 'N'
    o.deposit_balance = 100.00
    o.subtotal_after_discount = 3500.00
    o.store = store1
    o.save()

    commission = Commission(associate=user1, order=o)
    commission.save()

    item1 = OrderItem(status='S', description="Item1", order=o)
    item1.save()

    o = Order()
    o.number = 'SO-01-0003'
    o.order_date = last_m_mid
    o.customer = cust2
    o.status = 'Q'
    o.deposit_balance = 500
    o.subtotal_after_discount = 7000.00
    o.store = store1
    o.save()

    commission = Commission(associate=user3, order=o)
    commission.save()
    commission = Commission(associate=user4, order=o)
    commission.save()

    item1 = OrderItem(status='P', description="Item2", order=o)
    item1.save()
    item2 = OrderItem(status='S', description="Item3", order=o)
    item2.save()

    o = Order()
    o.number = 'SO-03-0001'
    o.order_date = last_m_first
    o.customer = cust
    o.status = 'C'
    o.deposit_balance = 5000
    o.subtotal_after_discount = 5000.00
    o.store = store2
    o.save()

    commission = Commission(associate=user3, order=o)
    commission.save()
    commission = Commission(associate=user4, order=o)
    commission.save()

    item1 = OrderItem(status='P', description="Item4", order=o)
    item1.save()
    item2 = OrderItem(status='S', description="Item6", order=o)
    item2.save()
    item2 = OrderItem(status='O', description="Item7", order=o)
    item2.save()