コード例 #1
0
    def test_add_excessive_price(self):
        """Test that prices over 10,000 cannot be submitted"""

        # Log in seller
        self.client.login(username="******", password="******")

        # Issue a GET request
        response = self.client.get(reverse("website:sell"))

        # Check that the response is 200
        self.assertEqual(response.status_code, 200)

        # Submit fake form with price greater than 10,000
        form_data = {
            "seller_id": 2,
            "title": "Test Product",
            "description": "Test description",
            "product_type_id": 1,
            "price": "1230000",
            "local_delivery": "on",
            "quantity": "12"
        }

        product_form = ProductForm(form_data)

        # Check that form validation throws an error
        self.assertFalse(product_form.is_valid())

        # Check that the form validation specifically throws an error on quantity and provides the correct error message
        self.assertEqual(product_form.errors['price'],
                         ['Ensure this value is less than or equal to 10000.'])
コード例 #2
0
def sell_product(request):
    """
    Purpose: to present the user with a form to upload information about a product to sell
    Author: Jordan Nelson
    Args: request -- the full HTTP request object
    Returns: a form that lets a user upload a product to sell
    """
    if request.method == 'GET':
        product_form = ProductForm()
        template_name = 'create.html'
        return render(request, template_name, {'product_form': product_form})

    elif request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        form_data = request.POST

        if form.is_valid():

            product = Product()

            product.seller = request.user
            product.title = form.cleaned_data['title']
            product.description = form.cleaned_data['description']
            product.price = form.cleaned_data['price']
            product.quantity = form.cleaned_data['quantity']
            product.product_type = ProductType.objects.get(
                pk=form_data['product_type'])
            product.product_photo = form.cleaned_data['product_photo']
            product.city = form.cleaned_data['city']

            product.save()

            return render(request, 'success.html', {})
        else:
            return HttpResponse('Failure Submitting Form')
コード例 #3
0
def sell_product(request):
    if request.method == 'GET':
        product_form = ProductForm()
        template_name = 'product/create.html'
        return render(request, template_name, {'product_form': product_form})

    elif request.method == 'POST':
        data = Product(
            seller=request.user,
            title=request.POST['title'],
            description=request.POST['description'],
            price=request.POST['price'],
            quantity=request.POST['quantity'],
            category=Category.objects.get(id=request.POST['category']))
        form = ProductForm(data=request.POST,
                           files=request.FILES,
                           instance=data)
        form.save()

        # request.POST['seller'] = request.user
        # all_data = request.POST.copy()
        # all_data['seller_id'] = request.user
        # form_data = ProductForm(request.POST, request.FILES)
        # form_data.data['seller'] = request.userz

        # form_data.save()

        # file_data = {'image': SimpleUploadedFile(request.FILES['image'], <file data>)}
        # p = ContactFormWithMugshot(data, file_data)

        # p.save()
        return HttpResponseRedirect(f'/products/{data.id}')
コード例 #4
0
    def test_add_product(self):
        """Test that products are successfully added to the database."""

        form_data = {
            "seller_id": 2,
            "title": "Test Product",
            "description": "Test description",
            "product_type_id": 1,
            "price": "123",
            "local_delivery": "on",
            "quantity": "123"
        }

        product_form = ProductForm(form_data)

        if product_form.is_valid():

            seller = form_data["seller_id"]
            title = form_data["title"]
            description = form_data["description"]
            product_type = form_data["product_type_id"]
            price = form_data["price"]
            quantity = form_data["quantity"]
            local_delivery = form_data["local_delivery"]

            data = [
                seller, title, description, product_type, price, quantity,
                local_delivery
            ]

            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    INSERT INTO website_product
                    (
                        seller_id,
                        title,
                        description,
                        product_type_id,
                        price,
                        quantity,
                        local_delivery
                    )
                    VALUES(
                        %s, %s, %s, %s, %s, %s, %s
                    )
                """, data)
                new_product = cursor.lastrowid

                self.assertEqual(new_product, 1)
コード例 #5
0
def sell_product(request):
    if request.method == 'GET':
        product_form = ProductForm()
        template_name = 'product/create.html'
        return render(request, template_name, {'product_form': product_form})

    if request.method == "POST":
        seller = request.user.id
        title = request.POST["title"]
        productType = request.POST["productType"]
        description = request.POST["description"]
        price = request.POST["price"]
        quantity = request.POST["quantity"]

        with connection.cursor() as cursor:
            cursor.execute(
                "INSERT into website_product VALUES(%s, %s, %s, %s, %s, %s, %s, %s)",
                [
                    None, title, description, price, quantity, None, seller,
                    productType
                ])
            product_details = cursor.lastrowid

    return HttpResponseRedirect(
        reverse("website:product_detail", args=(product_details, )))
コード例 #6
0
def sell_product(request):
    """
    purpose: allows user to list an item for sale by after submitting a form
    author: Dean Smith, Helana Nosrat, Bri Wyatt
    args: request allows Django to see user session data
    """

    if request.method == 'GET':
        product_form = ProductForm()
        template_name = 'product/create.html'
        return render(request, template_name, {'product_form': product_form})

    elif request.method == 'POST':
        form_data = request.POST

        def post_product(boolean):
            myfile = request.FILES['photo']
            fs = FileSystemStorage()
            filename = fs.save(myfile.name, myfile)
            uploaded_file_url = fs.url(filename)

            print("photo url", uploaded_file_url)

            c = Category.objects.get(pk=form_data['category'])
            p = Product(
                seller=request.user,
                title=form_data['title'],
                description=form_data['description'],
                price=form_data['price'],
                quantity=form_data['quantity'],
                is_local=boolean,
                city=form_data['city'],
                date='date',
                photo=uploaded_file_url,
                category=c,
            )

            p.save()
            return p

        try:
            if form_data['is_local']:
                print("is local")
                product = post_product(True)
                template_name = 'product/product_detail.html'
                return render(request, template_name, {'product': product})

        except KeyError:
            product = post_product(False)
            template_name = 'product/product_detail.html'
            return render(request, template_name, {'product': product})
コード例 #7
0
def sell_product(request):
    if request.method == 'GET':
        product_form = ProductForm()
        template_name = 'product/create.html'
        return render(request, template_name, {'product_form': product_form})

    elif request.method == 'POST':
        form_data = request.POST

        p = Product(
            seller=request.user,
            title=form_data['title'],
            description=form_data['description'],
            price=form_data['price'],
            quantity=form_data['quantity'],
        )
        p.save()
        template_name = 'product/success.html'
        return render(request, template_name, {})
コード例 #8
0
ファイル: views.py プロジェクト: binauralbeat/sprint-3
def sell_product(request):
    if request.method == 'GET':
        product_form = ProductForm()
        template_name = 'product/create.html'
        return render(request, template_name, {'product_form': product_form})

    elif request.method == 'POST':
        product_form = ProductForm(data=request.POST)
        if product_form.is_valid():
            product = product_form.save(commit=False)
            product.seller = request.user
            product.save()
        template_name = 'product/success.html'
        return render(request, template_name, {'sell': product})
コード例 #9
0
def sell_product(request):
    """ View manages GETs the product form view and product detail view from POST request """
    if request.method == 'GET':

        product_form = ProductForm()
        template_name = 'product/create.html'
        return render(request, template_name, {'product_form': product_form})

    elif request.method == 'POST':

        form_data = request.POST

        p = Product(  # p is a built in DOM manipulator - makes the form show up in paragraph form
            seller=request.user,
            title=form_data['title'],
            description=form_data['description'],
            price=form_data['price'],
            quantity=form_data['quantity'],
        )
        p.save()
        template_name = 'product/success.html'
        context = {'product': p}
        return render(request, template_name, context)
コード例 #10
0
def sell_product(request):
    """
    This method is invoked to post a product to sell

    ---Arguments---
    None

    ---GET---
    Renders create.html
        ---Context---
        'product_form': the form from product_form.py

    ---POST---
    Renders success/product_added_to_sell_links.html

        ---Context---
        'posted_object': 'Your Product added to Sell'
        'posted_object_identifier': The product's title

    Author: Jessica Younker
    """

    if request.method == 'GET':
        product_form = ProductForm()
        template_name = 'create.html'
        return render(request, template_name, {
            'product_form': product_form,
        })

    elif request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        form_data = request.POST
        try:
            form_data['local_delivery'] == 'on'
            local_delivery_boolean = True
            location_data = form_data['location']
        except KeyError:
            local_delivery_boolean = False
            location_data = None
        if form.is_valid():
            # b64_image = base64.b64encode(request.FILES['image'].read())
            p = Product(seller=request.user,
                        title=form_data['title'],
                        description=form_data['description'],
                        price=form_data['price'],
                        current_inventory=form_data['current_inventory'],
                        product_category_id=form_data['product_category'],
                        date_added=timezone.now(),
                        local_delivery=local_delivery_boolean,
                        image=form.cleaned_data['image'],
                        is_active=1,
                        location=location_data)
            p.save()
            # template_name = 'success/product_added_to_sell_links.html'
            # return render(request, template_name, {
            #     'posted_object': 'Your Product added to Sell',
            #     'posted_object_identifier': p.title})
            return HttpResponseRedirect(
                reverse('website:product_detail', args=[p.id]))
        else:
            return HttpResponseRedirect(reverse('website:sell'))
コード例 #11
0
def sell_product(request):
    """
    purpose: produce a form for the user to create a product to sell

    author: casey dailey, justin short

    args: request

    returns: redirect to detail view for product created
    """
    # if attempting to view, render the form.
    if request.method == 'GET':
        product_form = ProductForm()
        template_name = 'product/create.html'
        return render(request, template_name, {'product_form': product_form})

    # if POST, gather form data and save, then redirect to details for that product
    elif request.method == 'POST':
        form_data = request.POST
        file_data = request.FILES
        print(file_data)

        def create_product(product_delivery, product_image):
            p = Product(
                seller=request.user,
                title=form_data['title'],
                description=form_data['description'],
                price=form_data['price'],
                quantity=form_data['quantity'],
                local_delivery=product_delivery,
                city=form_data['city'],
                image_path=product_image,

                # create an instance of category of where category_name = the user's choice
                product_category=Category.objects.get(
                    category_name=form_data['product_category']))
            p.save()
            return p

        product_delivery = None
        product_image = None

        # if trying to upload an image:
        if 'image_path' in request.FILES:
            product_image = request.FILES['image_path']
        else:
            product_image = None

        try:

            # handle local delivery T/F
            if 'local_delivery' in request.POST:
                product_delivery = True
                product = create_product(product_delivery, product_image)
                return HttpResponseRedirect('product_details/{}'.format(
                    product.id))
        except MultiValueDictKeyError:
            product_delivery = False
            product = create_product(product_delivery, product_image)
            return HttpResponseRedirect('product_details/{}'.format(
                product.id))
コード例 #12
0
def sell_product(request):
    """Loads the view for creating a product to sell and saves it to the database.

        Author: Sebastian Civarolo, Jase Hackman

    """
    if request.method == "GET":
        product_form = ProductForm()
        template_name = "product/create.html"
        context = {"product_form": product_form, "file_Error": False}
        return render(request, template_name, context)

    elif request.method == "POST":
        form_data = request.POST
        product_form = ProductForm(form_data)
        uploaded_file_url = ""
        if "photo" in request.FILES:
            photo = request.FILES["photo"]
            if photo.size > 5000000:
                template_name = "product/create.html"
                context = {"product_form": product_form, "file_Error": True}
                return render(request, template_name, context)
                # raise ValidationError("The maximum file size that can be uploaded is 5MB")
            fs = FileSystemStorage()
            photo_name = fs.save(photo.name, photo)
            uploaded_file_url = fs.url(photo_name)

        if product_form.is_valid():

            seller = request.user.customer.id
            title = form_data["title"]
            description = form_data["description"]
            product_type = form_data["product_type"]
            price = form_data["price"]
            quantity = form_data["quantity"]
            photo = uploaded_file_url
            if "local_delivery" in form_data:
                local_delivery = 1
                delivery_city = form_data["delivery_city"]
                delivery_state = form_data["delivery_state"]
            else:
                local_delivery = 0
                delivery_city = ""
                delivery_state = ""

            data = [
                seller, title, description, product_type, price, quantity,
                local_delivery, delivery_city, delivery_state, photo
            ]

            with connection.cursor() as cursor:
                cursor.execute(
                    """
                    INSERT INTO website_product
                    (
                        seller_id,
                        title,
                        description,
                        product_type_id,
                        price,
                        quantity,
                        local_delivery,
                        delivery_city,
                        delivery_state,
                        photo_url
                    )
                    VALUES(
                        %s, %s, %s, %s, %s, %s, %s, %s, %s, %s
                    )
                """, data)
                new_product = cursor.lastrowid

            context = {"title": title, "product_id": new_product}

            return HttpResponseRedirect(
                reverse("website:product_details", args=(new_product, )))
コード例 #13
0
def sell_product(request):
    """Handles displaying, validating, and posting the new product form

    Author(s): Nolan Little

    Arguments:
        request {request object}

    Returns:
        render -- if the request is a get, returns a render of the form
               -- if the request is a post, checks the validity of the form data
               -- if the data is valid, performs the db insert of new item and returns a render
                    of the details view of the new items
    """

    if request.method == 'GET':
        product_form = ProductForm()
        template_name = 'product/create.html'
        return render(request, template_name, {'product_form': product_form})

    elif request.method == 'POST':
        form_data = request.POST

        try:
            myfile = request.FILES['myfile']
            fs = FileSystemStorage()
            filename = fs.save(myfile.name, myfile)
            uploaded_file_url = fs.url(filename)

        except MultiValueDictKeyError:
            myfile = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQEbVj-dY-HFt1DhTc2JXe0LtqQ-HSDyMy1qvDNWJoFMtB7gfR9'
            uploaded_file_url = myfile

        p_form_data = {
            'title': form_data['title'],
            'description': form_data['description'],
            'price': form_data['price'],
            'quantity': form_data['quantity'],
            'category': form_data['category']
        }

        product_form = ProductForm(p_form_data)

        if product_form.is_valid():
            customer_id = request.user.id

            sql = "INSERT INTO website_product VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s)"
            product_params = [
                None,
                p_form_data['title'],
                p_form_data['description'],
                p_form_data['price'],
                p_form_data['quantity'],
                uploaded_file_url,
                0,  #default boolean not deleted
                customer_id,
                p_form_data['category']
            ]

            with connection.cursor() as cursor:
                cursor.execute(sql, product_params)
                product_id = cursor.lastrowid
        else:
            template_name = 'product/create.html'
            return render(request, template_name,
                          {'product_form': product_form})

        product = Product.objects.raw(
            'SELECT * FROM website_product WHERE id = %s', [product_id])
        template_name = 'product_details.html'
        return HttpResponseRedirect(
            reverse('website:product_details', args=(product_id, )))