Esempio n. 1
0
 def test_price_positive(self):
   f = ProductForm(self.product)
   self.assertTrue(f.is_valid())
   self.product['price'] = 0
   f = ProductForm(self.product)
   self.assertFalse(f.is_valid())
   self.product['price'] = -1
   f = ProductForm(self.product)
   self.assertFalse(f.is_valid())
   self.product['price'] = 1
Esempio n. 2
0
 def test_imgae_url_endwiths(self):
     url_base = 'http://google.com/'
     oks = ('fred.gif', 'fred.jpg', 'fred.png', 'FRED.JPG', 'FRED.Jpg')
     bads = ('fred.doc', 'fred.gif/more', 'fred.gif.more')
     for endwith in oks:
         self.product['image_url'] = url_base+endwith
         f = ProductForm(self.product)
         self.assertTrue(f.is_valid(),msg='error when image_url endwith '+endwith)
     for endwith in bads:
         self.product['image_url'] = url_base+endwith
         f = ProductForm(self.product)
         self.assertFalse(f.is_valid(),msg='error when image_url endwith '+endwith)
         self.product['image_url'] = 'http://google.com/logo.png'
Esempio n. 3
0
  def test_imgae_url_endwiths(self):
    url_base = 'http://google.com/'
    oks = ('fred.gif', 'fred.jpg', 'fred.png', 'FRED.JPG', 'FRED.Jpg')
    bads = ('fred.doc', 'fred.gif/more', 'fred.gif.more')
    for endwith in oks:
      self.product['image_url'] = url_base+endwith
      f = ProductForm(self.product)
      self.assertTrue(f.is_valid(), msg='error when image_url endwith '+ endwith)

    for endwith in bads:
      self.product['image_url'] = url_base+endwith
      f = ProductForm(self.product)
      self.assertFalse(f.is_valid(), msg='error when image_url endwith '+ endwith)
      self.product['image_url'] = 'http://google.com/logo.png'
Esempio n. 4
0
 def test_attrs_cannot_empty(self):
     f = ProductForm({})
     self.assertFalse(f.is_valid())
     self.assertTrue(f['title'].errors)
     self.assertTrue(f['description'].errors)
     self.assertTrue(f['price'].errors)
     self.assertTrue(f['image_url'].errors)
Esempio n. 5
0
def new_product(request, pk):
    form = ProductForm()

    business_profile = get_object_or_404(BusinessProfile, pk=pk)

    if request.method == 'POST' and request.user.is_authenticated():
        form = ProductForm(request.POST)
        if form.is_valid():
            # check for duplicates
            # check_duplicates(Product, 
            #                  form.cleaned_data['name'], 
            #                  form.cleaned_data['product_size'],
            #                  business_profile)

            product = form.save()
            # attribute "business profile" to product
            product.business_profile = business_profile
            product.save()

            messages.add_message(request, messages.INFO,
                "You've created a product successfully. Please add raw materials used.")

            return redirect('product_add_raw_material', pk=pk, id=product.id) #, id=product.id)

        else:
            # TODO -> handel errors here!
            pass

    return render_to_response('dashboard/new_product.html',
        {'form': form},
        RequestContext(request)
        )
Esempio n. 6
0
def editProduct(request, pk):
    edit = False

    if request.method == "POST":
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
            product = form.save(commit=False)

            photo = request.FILES['Photo']
            fs = FileSystemStorage()
            filename = fs.save(photo.name, photo)
            uploaded_file_url = fs.url(filename)

            product.Photo = uploaded_file_url
            product.id = pk
            product.save()
            edit = True
        else:
            product = Product.objects.get(id=pk)
            product.Title = form.data['Title']
            product.Description = form.data['Description']
            product.Price = form.data['Price']
            product.save()
            edit = True

    args = {}
    args['user'] = auth.get_user(request)
    args['form'] = ProductForm(instance=Product.objects.get(id=pk))
    args['whatEdit'] = 'Редагування продукції'

    if not edit:
        return render(request, 'edit.html', args)
    else:
        args['products'] = Product.objects.all()
        return render(request, 'products.html', args)
Esempio n. 7
0
def add_edit(request, id=None):
    obj = None
    if id:
        obj = get_object_or_404(Product, pk=id)

    if request.method == "POST":
        form = ProductForm(request.POST, instance=obj)
        if form.is_valid():
            form.save()
            messages.success(request, 'Record has been saved successfully.')
            if id:
                return HttpResponseRedirect(reverse("internal:products:index"))
            return HttpResponseRedirect(".")
        else:
            messages.error(request, 'Failed to save record. Please correct the errors below.', extra_tags='danger')
    else:
        form = ProductForm(instance=obj)

    context = {
        'page_header': ("Edit Product ID: %s" % id) if id else "Add New Product",
        'page_title': ("Edit Product ID: %s" % id) if id else "Add New Product",
        'form': form
    }

    return render(
        request,
        'products/add_edit.html',
        context
    )
Esempio n. 8
0
 def test_attrs_cannot_empty(self):
     f = ProductForm({})
     self.assertFalse(f.is_valid())
     self.assertTrue(f['title'].errors)
     self.assertTrue(f['description'].errors)
     self.assertTrue(f['price'].errors)
     self.assertTrue(f['imageUrl'].errors)
Esempio n. 9
0
    def test_title_unique(self):
        self.product['title'] = 'My Book Title'
        f = ProductForm(self.product)
        self.assertFalse(f.is_valid())
        self.product['title'] = 'My Another Book Title'

        
Esempio n. 10
0
def create(request):
    if ( request.user.username=='' ):
        Uform = AnonymousForm(prefix='ano')
        Pform = ProductForm(prefix='prd')
        if request.method == 'POST':
            Pform = ProductForm(request.POST, request.FILES, prefix='prd')
            Uform = AnonymousForm(request.POST, prefix='ano')
            if Uform.is_valid() and Pform.is_valid():
                FileUploadHandler(request.FILES['image'])

                u = Uform.save()
                p = Pform.save()

                u.product_id = p.id

                u.save()

                return HttpResponseRedirect('/show/all/')
        else:
            Pform = ProductForm()
            Uform = AnonymousForm()
        args = {}
        args.update(csrf(request))
        args['Pform'] = Pform
        args['Uform'] = Uform
        return render_to_response('create_product_ano.html', args)

    else:
        if request.method == 'POST':
            form = ProductForm(request.POST, request.FILES)
            if form.is_valid():
                FileUploadHandler(request.FILES['image'])

                # u=User.objects.get(username=request.user.username)

                obj = form.save(commit=False)
                obj.user = request.user
                obj.save()
                return HttpResponseRedirect('/show/all/')
        else:
            form = ProductForm()

        args = {}
        args.update(csrf(request))
        args['form'] = form
        return render_to_response('create_product.html', args)
Esempio n. 11
0
def create_product(request):
    form = ProductForm(request.POST or None)
    if form.is_valid():
        form.save()
        form = ProductForm()
    return render_to_response("create_product.html",
                              locals(),
                              context_instance=RequestContext(request))
Esempio n. 12
0
def edit_product(request, id):
    product_instance = Product.objects.get(id=id)
    form = ProductForm(request.POST or None, instance=product_instance)
    if form.is_valid():
        form.save()
    return render_to_response("edit_product.html",
                              locals(),
                              context_instance=RequestContext(request))
Esempio n. 13
0
def edit(request, pk):
    pd1 = get_object_or_404(Product,pk=id)
    form = ProductForm(request.POST or None, instance = pd1)

    if form.is_valid():
        form.save()
    t=get_template('ebook/forms.html')
    c=RequestContext(request,locals())
    return HttpResponse(t.render(c))
def new_listing(request):
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect(all_products)
    else:
        form = ProductForm()
    return render(request, 'Sell-Item.html', {'form': form})
Esempio n. 15
0
 def test_product_form(self):
     form = ProductForm({
         'category': 'sale',
         'sku': '111111',
         'name': 'test',
         'description': 'Test Description',
         'price': '10',
     })
     self.assertFalse(form.is_valid())
Esempio n. 16
0
def new(request):
    form = ProductForm(request.POST or None)

    if request.method == "POST":
        form = ProductForm(request.POST)
        if form.is_valid():
            pd1 = form.save(created_by=request.user)
            return redirect('product_last')
    t = get_template('ebook/form.html')
    c = RequestContext(request,locals())
    return HttpResponse(t.render(c))
Esempio n. 17
0
def my_product(request, slug=None):
    product = get_object_or_404(Product, slug=slug)
    if request.method == 'POST':
        form = ProductForm(request.POST)
        if form.is_valid():
            updated_product = form.save(commit=False)
            updated_product.id = product.id
            updated_product.created = product.created
            updated_product.save()
    else:
        form = ProductForm(instance=product)
    return render(request, 'my_product.html', {'form': form, 'product': product})
Esempio n. 18
0
def my_products(request):
    user = request.user
    if request.method == 'POST':
        form = ProductForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = ProductForm()
    companies = Company.objects.filter(owner=user)
    products = Product.objects.filter(company__in=companies)
    exchange_rate = get_rate_of_exchange()
    return render(request, 'my_products.html', {'products': products, 'form': form, 'exchange_rate': exchange_rate})
Esempio n. 19
0
def admin_products(request):
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
            create_product(request)
        else:
            print form.errors
    if not request.user or not request.user.is_staff:
        return redirect('login')
    categories = ['Камеры', 'Антирадары']
    brands = ['Nikon', 'Canon', 'Fujitsu']
    return render(request, "core/admin/index.html", {"categories": categories, "brands": brands})
Esempio n. 20
0
def product_add(request):
  if request.method == 'POST':
    form = ProductForm(request.POST)
    if form.is_valid():
      p = form.save(commit=False)
      p.sn = generate_sn(prefix = 'PROD')
      p.save()
      serializer = JSONSimpleSerializer()
      return HttpResponse(serializer.serialize([p,], use_natural_foreign_keys=True))
  else:
    form = ProductForm()
    return render_to_response('modal/main_form.html',{'action':'Add', 'module':module, 'form': form},context_instance=RequestContext(request))
Esempio n. 21
0
def product_info(request, product_slug, template_name="pdcts/poduct_edit.html"):
#    request.breadcrumbs( ( ("My Account", '/accounts/my_account/'), ("Edit Profile", request.path_info) ) )
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
            product_profile.set(request, product_slug)
            url = urlresolvers.reverse('my_account')
            return HttpResponseRedirect(url)
    else:
        pdct_profile = product_profile.retrieve(request, product_slug)
        form = ProductForm(instance=pdct_profile)
    page_title = 'Edit Product Information'
    return render_to_response(template_name, locals(), context_instance=RequestContext(request))
Esempio n. 22
0
def edit_product(request, product_id=0):
    # Sets the form of product creation. If product_id is present, will use the product as form instance
    if product_id:
        try:
            product = Product.objects.get(pk=product_id)
            form = ProductForm(request.POST or None, instance=product)
        except Product.DoesNotExist:
            form = ProductForm(request.POST or None)
    else:
        form = ProductForm(request.POST or None)
    if form.is_valid():
        product = form.save()
        return HttpResponseRedirect(reverse("products.views.products_list"))
    return locals()
Esempio n. 23
0
def product_update(request):
  if request.method == 'POST':
    postdata = request.POST.copy()
    try:
      c = Product.objects.get(sn=postdata.pop('sn')[0])
    except Product.DoesNotExist:
      raise Http404
    form = ProductForm(postdata, instance=c)
    if form.is_valid():
      p = form.save()
      serializer = JSONSimpleSerializer()
      return HttpResponse(serializer.serialize([p,], use_natural_foreign_keys=True))
  else:
      return HttpResponse('Invalid request.')
Esempio n. 24
0
def product_add(request):
    temp_name = "appconf/appconf-header.html"
    if request.method == 'POST':
        form = ProductForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('product_list'))
    else:
        form = ProductForm()

    results = {
        'form': form,
        'request': request,
        'temp_name': temp_name,
    }
    return render(request, 'appconf/product_base.html', results)
Esempio n. 25
0
def product_info(request,
                 product_slug,
                 template_name="pdcts/poduct_edit.html"):
    #    request.breadcrumbs( ( ("My Account", '/accounts/my_account/'), ("Edit Profile", request.path_info) ) )
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
            product_profile.set(request, product_slug)
            url = urlresolvers.reverse('my_account')
            return HttpResponseRedirect(url)
    else:
        pdct_profile = product_profile.retrieve(request, product_slug)
        form = ProductForm(instance=pdct_profile)
    page_title = 'Edit Product Information'
    return render_to_response(template_name,
                              locals(),
                              context_instance=RequestContext(request))
Esempio n. 26
0
def add_product(request, template_name="pdcts/add.html"):
    request.breadcrumbs(("Submit a Product"), request.path_info)
    page_title = 'Submission'
    '''try:
        	profile = request.user.get_profile()
    	except UserProfile.DoesNotExist:
       		profile = UserProfile(user=request.user)
        	profile.save() '''

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

        email_subject = 'Approve a Product'
        email_body = "Hello Administrator, \n\nThis is a My Campuser alert for products that have been submitted and are awaiting your approval.\n\nLogin to the admin panel to activate/approve these products\n\nRegards,\nMy Campuser Team"

        if form.is_valid():
            add = form.save(commit=False)
            add.user = request.user
            product_name = request.POST.get('product_name')
            add.product_name = product_name.title()
            add.save()
            form.save_m2m()
            send_mail(email_subject, email_body, '*****@*****.**',
                      ['*****@*****.**'])

            reputation = User_Reputation.objects.filter(user=request.user)

            if reputation:
                r = User_Reputation.objects.get(user=request.user)
                nR = r.reputation
            else:
                r = User_Reputation()
                r.user = request.user
                r.reputation = 0.5
                r.entity_alpha = 0.5
                r.entity_beta = 0.5
                r.votes = 0
                r.save()

            return HttpResponseRedirect('/success/')
    else:
        form = ProductForm()
    return render_to_response(template_name,
                              locals(),
                              context_instance=RequestContext(request))
Esempio n. 27
0
def product_edit(request, product_id):
    product = Product.objects.get(id=product_id)
    temp_name = "appconf/appconf-header.html"
    if request.method == 'POST':
        form = ProductForm(request.POST, instance=product)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('product_list'))
    else:
        form = ProductForm(instance=product)

    results = {
        'form': form,
        'product_id': product_id,
        'request': request,
        'temp_name': temp_name,
    }
    return render(request, 'appconf/product_base.html', results)
Esempio n. 28
0
def new_product(request):
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)

        if form.is_valid():
            product = form.save(commit=False)
            product.seller = request.user
            product.save()

            request.session['message'] = 'Product successfully added'
            return HttpResponseRedirect('/')
    else:
        context = retrieve_basic_info(request)
        form = ProductForm()
        context['form'] = form
        return render(request, 'new_product.html', context)

    return render(request, 'new_product.html', {'form': form})
Esempio n. 29
0
def add_product (request, template_name="pdcts/add.html"):
        request.breadcrumbs(("Submit a Product"),request.path_info)
	page_title = 'Submission'

    	'''try:
        	profile = request.user.get_profile()
    	except UserProfile.DoesNotExist:
       		profile = UserProfile(user=request.user)
        	profile.save() '''

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

		email_subject = 'Approve a Product'
		email_body = "Hello Administrator, \n\nThis is a My Campuser alert for products that have been submitted and are awaiting your approval.\n\nLogin to the admin panel to activate/approve these products\n\nRegards,\nMy Campuser Team"

		if form.is_valid():
			add = form.save(commit=False)
			add.user = request.user
			product_name = request.POST.get('product_name')
			add.product_name = product_name.title()
			add.save()
			form.save_m2m()
			send_mail(email_subject, email_body, '*****@*****.**' , ['*****@*****.**'])

	             	reputation = User_Reputation.objects.filter(user = request.user)

	             	if reputation:
				r = User_Reputation.objects.get(user = request.user)
				nR = r.reputation
	              	else:
		   		r = User_Reputation()
		              	r.user = request.user
		             	r.reputation = 0.5
		                r.entity_alpha = 0.5
		               	r.entity_beta = 0.5
		               	r.votes = 0
		               	r.save()                        

			return HttpResponseRedirect('/success/')
	else:
		form = ProductForm()
	return render_to_response(template_name, locals(), context_instance = RequestContext(request))
Esempio n. 30
0
def products(request):

    if request.method == "POST" and request.FILES['Photo']:
        form = ProductForm(request.POST, request.FILES)
        if form.is_valid():
            product = form.save(commit=False)

            photo = request.FILES['Photo']
            fs = FileSystemStorage()
            filename = fs.save(photo.name, photo)
            uploaded_file_url = fs.url(filename)

            product.Photo = uploaded_file_url
            product.save()

    args = {}
    args['user'] = auth.get_user(request)
    args['form'] = ProductForm()
    args['products'] = Product.objects.all()

    return render(request, 'products.html', args)
Esempio n. 31
0
def product_view(request):
    user = check_validation(request)
    if user:
        if request.method == 'POST':
            form = ProductForm(request.POST, request.FILES)
            if form.is_valid():
                image = form.cleaned_data.get('image')
                caption = form.cleaned_data.get('caption')
                review = ProductModel(user=user, image=image, caption=caption)
                review.save()

                path = str(BASE_DIR + '/' + product.image.url)

                client = ImgurClient(CLIENT_ID, CLIENT_SECRET)
                product.image_url = client.upload_from_path(path, anon=True)['link']
                product.save()

                return redirect('/products/')

            else:
                return render(request, 'feed.html', {'form': form})
        else:
            return redirect('/post/')
Esempio n. 32
0
def add_product(request):
    posted_data = {}
    user = UserDetail(request).getLoginUser()
    if not user:
        #messages.add_message(request, messages.INFO, 'Please login firstly !!')
        return redirect("/")

    user_id = user['id']
    login_user = "******"
    page = "add_product"

    if UserDetail(request).is_vendor():
        login_user = "******"
    else:
        login_user = "******"

    if request.method == "POST":
        posted_data = request.POST
        title = request.POST['title']
        description = request.POST['description']
        category = request.POST['category']
        selling_price = float(request.POST['selling_price'])
        compare_price = float(request.POST['compare_price'])

        token = request.POST['token']

        if 'is_tax' in request.POST:
            is_tax = request.POST['is_tax']
        else:
            is_tax = 0
        if 'sku' in request.POST:
            sku = request.POST['sku']
        else:
            sku = 0
        barcode = request.POST['barcode']
        user_id = user_id

        form = ProductForm(request.POST, request=request)
        if form.is_valid():
            product_detail = Products(user_id=user_id,
                                      title=title,
                                      description=description,
                                      selling_price=selling_price,
                                      compare_price=compare_price,
                                      sku=sku,
                                      barcode=barcode,
                                      category_id=category)
            product_detail.save()
            product_id = product_detail.id

            # images
            Images.objects.filter(token=token).update(product_id=product_id)

            #messages.add_message(request, messages.SUCCESS, 'Products saved successfully')
            if login_user == "vendor":
                return redirect("/dashboard")
            else:
                return redirect('/mvpadmin/products')
    else:
        form = ProductForm(request=request)

    vendor = ''

    categories_list = []

    categories = Categories.objects.filter(user_id=1)
    for category in categories:
        category_id = category.id
        category_name = category.title
        categories_list.append({
            'category_id': category_id,
            'category_name': category_name
        })
    user_detail = Account.objects.filter(id=user_id)
    # if user_detail:
    # 	vendor = user_detail[0].account_id
    return render(
        request, "add_product.html", {
            'categories_list': categories_list,
            'login_user': login_user,
            'form': form,
            'page': page,
            'posted_data': posted_data
        })
Esempio n. 33
0
 def test_product_description_is_required(self):
     form = ProductForm({'description': ''})
     self.assertFalse(form.is_valid())
     self.assertIn('description', form.errors.keys())
     self.assertEqual(form.errors['description'][0],
                      'This field is required.')
Esempio n. 34
0
 def test_product_price_is_required(self):
     form = ProductForm({'price': ''})
     self.assertFalse(form.is_valid())
     self.assertIn('price', form.errors.keys())
     self.assertEqual(form.errors['price'][0], 'This field is required.')
Esempio n. 35
0
    def test_title_unique(self):
        self.product['title'] = 'My Book Title'
        f = ProductForm(self.product)
        self.assertFalse(f.is_valid())

        self.product['title'] = 'My Another Book Title'
Esempio n. 36
0
def create_product(request):
    form=ProductForm(request.POST or None)
    if form.is_valid():
        form.save()
        form=ProductForm()
    return render_to_response("create_product.html",locals(),context_instance=RequestContext(request))
Esempio n. 37
0
def edit_product(request,id):
    product_instance=Product.objects.get(id=id)
    form=ProductForm(request.POST or None,instance=product_instance)
    if form.is_valid():
        form.save()
    return render_to_response("edit_product.html",locals(),context_instance=RequestContext(request))
Esempio n. 38
0
def create_product(request):
    form = ProductForm(request.POST or None)
    if form.is_valid():
        form.save()
        form = ProductForm()
    return render(request, 'marketapp/create_product.html', locals())
Esempio n. 39
0
def edit_product(request, id):
    product_instance = Product.objects.get(id = id)
    form = ProductForm(request.POST or None, instance = product_instance)
    if form.is_valid():
        form.save()
    return render(request, 'marketapp/edit_product.html', locals())