Eclipse import error Django - python

I have a Django program that was developed in Notepad++ but now I have installed Pydev for Eclipse, so , I want to develop the program in Eclipse going forward.
I have cart.py and views.py module under the cart folder but when I import the cart module in views.py file, I get a error--Unresolved import:cart ---on the views.py file import statement..Any help would be appreciated.
cart.py
from cart.models import CartItem
from catalog.models import Product
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
import decimal
import random
CART_ID_SESSION_KEY = 'cart_id'
#get the current users cart id,set new one if blank
def _cart_id(request):
print 'Get Cart Id'
if request.session.get(CART_ID_SESSION_KEY,'') == '':
print 'Failing here start'
request.session[CART_ID_SESSION_KEY] = _generate_cart_id()
print 'Failing here End'
return request.session[CART_ID_SESSION_KEY]
#
def _generate_cart_id():
print 'Generate cart id'
cart_id = ''
characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!##$%^&*()'
cart_id_length = 50
for y in range(cart_id_length):
cart_id += characters[random.randint(0,len(characters)-1)]
return cart_id
#return all items form the current users cart
def get_cart_items(request):
return CartItem.objects.filter(cart_id =_cart_id(request))
#add an item to the cart
def add_to_cart(request):
postdata = request.POST.copy()
#get product slug from post.data, return blank if empty
product_slug = postdata.get('product_slug','')
#get quantity added,return 1 if empty
quantity = postdata.get('quantity',1)
#fetch the product or return a missing page error
p = get_object_or_404(Product, slug=product_slug)
#get producsts in cart
cart_products = get_cart_items(request)
#check to see if the item is already in cart
product_in_cart = False
for cart_item in cart_products:
if cart_item.product.id == p.id:
cart_item.augment_quantity(quantity)
product_in_cart = True
if not product_in_cart:
ci = CartItem()
ci.product = p
ci.quantity = quantity
ci.cart_id = _cart_id(request)
ci.save()
def cart_distinct_item_count(request):
return get_cart_items(request).count()
views.py
import decimal
from django.shortcuts import render_to_response
from django.template import RequestContext
from ..cart import cart
from django.shortcuts import get_object_or_404
def show_cart(request, template_name="cart/cart.html"):
if request.method == 'POST':
postdata = request.POST.copy()
if postdata['submit'] == 'Remove':
cart.remove_from_cart(request)
if postdata['submit'] == 'Update':
cart.update_cart(request)
cart_items = cart.get_cart_items(request)
page_title = 'Shopping Cart'
cart_subtotal = cart.cart_subtotal(request)
return render_to_response(template_name, locals(),
context_instance=RequestContext(request))
def get_single_item(request, item_id):
return get_object_or_404(CartItem, id=item_id, cart_id=_cart_id(request))
# update quantity for single item
def update_cart(request):
postdata = request.POST.copy()
item_id = postdata['item_id']
quantity = postdata['quantity']
cart_item = get_single_item(request, item_id)
if cart_item:
if int(quantity) > 0:
cart_item.quantity = int(quantity)
cart_item.save()
else:
remove_from_cart(request)
# remove a single item from cart
def remove_from_cart(request):
postdata = request.POST.copy()
item_id = postdata['item_id']
cart_item = get_single_item(request, item_id)
if cart_item:
cart_item.delete()
# gets the total cost for the current cart
def cart_subtotal(request):
cart_total = decimal.Decimal('0.00')
cart_products = get_cart_items(request)
for cart_item in cart_products:
cart_total += cart_item.product.price * cart_item.quantity
return cart_total

The .. in front of from ..cart import cart is probably messing with you.
This means cart.py should be one level up directory-wise than views.py, which from your question derived - is not the case.

Related

The view products.views.get_product didn't return an HttpResponse object. It returned None instead

ValueError at /product/apple-ipad-air-5th-gen-64-gb-rom-109-inch-with-wi-fi5g-purple/
The view products.views.get_product didn't return an HttpResponse object. It returned None instead.
how can i solve this problem please help me
`
from django.shortcuts import render,redirect
from products.models import Product
from accounts.models import *
from django.http import HttpResponseRedirect
from products.models import *
from django.utils.timezone import datetime
# Create your views here.
def get_product(request, slug):
product = Product.objects.get(slug=slug)
# comment = Comment.objects.get(slug=slug)
if request.method == "POST":
star = request.POST.get('star')
name = request.user.first_name
body = request.POST.get('body')
review = Comment(star=star, name=name,body=body,date_added = datetime.today())
review.product = product
review.save()
return redirect(f'/product/{slug}', slug=product.slug)
try:
context = {'product': product, }
if request.GET.get('size'):
size = request.GET.get('size')
price = product.get_product_price_by_size(size)
context['selected_size'] = size
context['updated_price'] = price
return render(request, 'product\product.html' , context = context)
except Exception as e:
print(e)
`
i am making a ecommerce website and i add review option then i got this error
You got this error because return is inside if statement.
I have modified this:
try:
context = {'product': product, }
if request.GET.get('size'):
size = request.GET.get('size')
price = product.get_product_price_by_size(size)
context['selected_size'] = size
context['updated_price'] = price
except Exception as e:
print(e)
return render(request, 'product\product.html', context)

local variable 'intent' referenced before assignment

Can anyone please help me to fix this problem local variable 'intent' referenced before assignment i could not find out why client_secret in the context is triggered. to my knowledge if the code in if statement fails then else block will be executed but i have set a print statement and it does not appear in the teminal either. if someone can please help me in solving this issue.
from django.shortcuts import render, redirect, reverse
from django.contrib import messages
from django.conf import settings
from .forms import OrderForm
from .models import Order, OrderLineItem, ProductLineItem, ExerciseLineItem, NutritionLineItem
from merchandise.models import Product
from exercise.models import ExercisePlans
from nutrition.models import NutritionPlans
from cart.contexts import cart_contents
import stripe
def checkout(request):
stripe_public_key = settings.STRIPE_PUBLIC_KEY
stripe_secret_key = settings.STRIPE_SECRET_KEY
if request.method == 'POST':
cart = request.session.get('cart', {
'merchandise_dic': {},
'excercise_plans_dic': {},
'nutrition_plans_dic': {},
})
form_data = {
'full_name': request.POST['full_name'],
'email': request.POST['email'],
'phone_number': request.POST['phone_number'],
'country': request.POST['country'],
'postcode': request.POST['postcode'],
'town_or_city': request.POST['town_or_city'],
'street_address1': request.POST['street_address1'],
'street_address2': request.POST['street_address2'],
'county': request.POST['county'],
}
order_form = OrderForm(form_data)
if order_form.is_valid():
print("Order form is valid")
order = order_form.save()
for product_type, dic in cart.items():
if product_type == 'merchandise_dic':
for item_id, quantity in dic.items():
print(f"This is item id of merchandise: {item_id}")
print(f"This is quantity of merchandise: {quantity}")
product = Product.objects.get(id=item_id)
print(product)
order_line_item = ProductLineItem(
order=order,
product=product,
quantity=quantity,
)
order_line_item.save()
elif product_type == 'excercise_plans_dic':
for item_id, quantity in dic.items():
print(f"This is item id of exercise plan: {item_id}")
print(f"This is quantity of exercise plan: {quantity}")
product = ExercisePlans.objects.get(id=item_id)
print(product)
order_line_item = ExerciseLineItem(
order=order,
product=product,
quantity=quantity,
)
order_line_item.save()
elif product_type == 'nutrition_plans_dic':
for item_id, quantity in dic.items():
print(f"This is item id of nutrition plan: {item_id}")
print(f"This is quantity of nutrition plan: {quantity}")
product = NutritionPlans.objects.get(id=item_id)
print(product)
order_line_item = NutritionLineItem(
order=order,
product=product,
quantity=quantity,
)
order_line_item.save()
else:
print("Order form is invalid")
messages.error(request, ('There was an error with your form. '
'Please double check your information.'))
return redirect(reverse('checkout'))
else:
print("Order form is invalid")
cart = request.session.get('cart', {
'merchandise_dic': {},
'excercise_plans_dic': {},
'nutrition_plans_dic': {},
})
if not cart:
messages.error(request,
"There is nothing in your \
shopping cart at the moment")
return redirect(reverse('products'))
""" Got total from cart_contents """
current_cart = cart_contents(request)
current_total = current_cart['total']
stripe_total = round(current_total * 100)
""" Set secret key on stripe """
stripe.api_key = stripe_secret_key
""" Created payment intent """
intent = stripe.PaymentIntent.create(
amount=stripe_total,
currency=settings.STRIPE_CURRENCY,
)
print(intent)
order_form = OrderForm()
if not stripe_public_key:
messages.warning(request, 'Stripe public key is missing. \
Did you forget to set it in your environment?')
template = 'checkout/checkout.html'
context = {
'order_form': order_form,
'stripe_public_key': stripe_public_key,
'client_secret': intent.client_secret,
}
return render(request, template, context)
If your method == "POST": is true then the intent variable is not assigned any parameter.
context = {
'order_form': order_form,
'stripe_public_key': stripe_public_key,
'client_secret': intent.client_secret,
}
Hence, the intent in last section is not assigned anything.
else:
print("Order form is invalid")
cart = request.session.get('cart', {
'merchandise_dic': {},
'excercise_plans_dic': {},
'nutrition_plans_dic': {},
})
if not cart:
messages.error(request,
"There is nothing in your \
shopping cart at the moment")
return redirect(reverse('products'))
""" Got total from cart_contents """
current_cart = cart_contents(request)
current_total = current_cart['total']
stripe_total = round(current_total * 100)
""" Set secret key on stripe """
stripe.api_key = stripe_secret_key
""" Created payment intent """
---> intent = stripe.PaymentIntent.create(
amount=stripe_total,
currency=settings.STRIPE_CURRENCY,
)
print(intent)
order_form = OrderForm()
intent is assigned inside the else block, but it is referenced outside the else block
context = {
'order_form': order_form,
'stripe_public_key': stripe_public_key,
---> 'client_secret': intent.client_secret,
So if the else block is not executed there is no intent variable.
Thanks every one for your valuable input I found the problem and fixed it. Actually I was not returning anything if the form is valid! Thus I was missing the redirect to checkout_success page at the first for loop level before 1st else.
That is why even if the form is valid it's still trying to return the render() statement at the bottom which was causing this error. Thus I created a checkout_success view and and also checkout_success.html and redirected to it. like this and fixed this error.
return redirect(reverse('checkout_success',
args=[order.order_number]))

Django 1.10 redirect view not working

My redirect to another view is not working in django 1.10
Views.py
from django.shortcuts import render, redirect
# Create your views here.
from forms import DocumentForm
from models import Document
from django.apps import apps
myapp = apps.get_app_config('django_celery_results')
myapp.models.TASK_MODEL = myapp.models['taskresult']
def tasks_view(request):
tasks = TASK_MODEL.objects.all()
return render(request, 'saved.html', {'tasks': tasks})
def SaveDocument(request):
saved = False
if request.method == "POST":
#Get the posted form
MyDocumentForm = DocumentForm(request.POST, request.FILES)
if MyDocumentForm.is_valid():
print 'It enters here'
document = Document()
document.name = MyDocumentForm.cleaned_data["name"]
document.doc = request.FILES["document"]
print document.doc
print document.name
print 'request type', request.method
document.save()
saved = True
return redirect('tasks_view')
else:
print 'Fails'
else:
MyDocumentForm = DocumentForm()
return render(request, 'saved.html', locals())
urls.py
from django.conf.urls import url
from django.views.generic import TemplateView
from core.views import *
urlpatterns = [
url(r'profile/',TemplateView.as_view(
template_name = 'profile.html')),
url(r'saved/', SaveDocument, name = 'SaveDocument'),
url(r'check/', tasks_view, name = 'tasks_view,')
]
I do not understand why do i always get this exception in Reverse for 'tasks_view' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
The url redirects to NoReverseMatch at /my_app/saved/. Why doesnt it redirect to the tasks view and goes to /my_app/check/ instead?
from django.conf.urls import url
from django.views.generic import TemplateView
from core.views import *
urlpatterns = [
url(r'profile/',TemplateView.as_view(
template_name = 'profile.html')),
url(r'saved/', SaveDocument, name = 'SaveDocument'),
url(r'check/', tasks_view, name = 'tasks_view')
]
Here you have small mistake in your code, you added coma at url(r'check/', tasks_view, name = 'tasks_view')
now this will definitely work.
At first reverse("view_name") after redirect
from django.core.urlresolvers import reverse
def SaveDocument(request):
saved = False
if request.method == "POST":
#Get the posted form
MyDocumentForm = DocumentForm(request.POST, request.FILES)
if MyDocumentForm.is_valid():
print 'It enters here'
document = Document()
document.name = MyDocumentForm.cleaned_data["name"]
document.doc = request.FILES["document"]
print document.doc
print document.name
print 'request type', request.method
document.save()
saved = True
return redirect(reverse('tasks_view'))
else:
print 'Fails'
else:
MyDocumentForm = DocumentForm()
return render(request, 'saved.html', locals())

Updating Items In A Shopping Cart With Django

I am tracking the total cost of items in a shopping cart with Django. My problem is the first item is tracked. When you deduct quantity or reduce quantity the price adjust. But anything that is below it does NOT adjust the total cost. I think the problem is I am not looping through it incorrectly so after many hours of failure I figured I would ask.
In
def cart()
I am looping through the member variables add updating
their values. The problem I am facing is that only the book_id is being passed to the cart() function when you click remove_from_cart
But if it was a problem of only one book_id being passed in then how come only the first item in the cart list is being changed regardless of the book_id that is being passed in?
views.py
#login_required
def add_to_cart(request,book_id):
book = get_object_or_404(Book, pk=book_id)
cart,created = Cart.objects.get_or_create(user=request.user, active=True)
order,created = BookOrder.objects.get_or_create(book=book,cart=cart)
order.quantity += 1
order.save()
messages.success(request, "Cart updated!")
return redirect('cart')
def remove_from_cart(request, book_id):
if request.user.is_authenticated():
try:
book = Book.objects.get(pk = book_id)
except ObjectDoesNotExist:
pass
else:
cart = Cart.objects.get(user = request.user, active = True)
cart.remove_from_cart(book_id)
return redirect('cart')
else:
return redirect('index')
def cart(request):
if request.user.is_authenticated():
cart = Cart.objects.filter(user=request.user.id, active = True)
orders = BookOrder.objects.filter(cart=cart)
total = 0
count = 0
for order in orders:
total += order.book.price * order.quantity
count += order.quantity
context = {
'cart': orders,
'total': total,
'count': count,
}
return render(request, 'store/cart.html', context)
else:
return redirect('index')
Your indentation is slightly off
def cart(request):
if request.user.is_authenticated():
cart = Cart.objects.filter(user=request.user.id, active = True)
orders = BookOrder.objects.filter(cart=cart)
total = 0
count = 0
for order in orders:
total += order.book.price * order.quantity
count += order.quantity
#Indentation needs to be offset by one level from here on
context = {
'cart': orders,
'total': total,
'count': count,
}
return render(request, 'store/cart.html', context)
else:
return redirect('index')

Django Object Log error: name 'register' is not defined

Im have a Django application and Im adding Django log Object to it, Im following this documentation https://code.osuosl.org/projects/django-object-log/wiki/Usage#Registering-Action-Types
I'm in the part of (Caching Data Automatically) in the documentation which is an example of how to add build cashe and register:
def build_cache(user, obj1, obj2, obj3, data):
return {'foo':obj.foo}
register('MY_EVENT', 'template.html', build_cache)
def my_view(request, pk):
""" example view that retrieves an object by its pk """
obj = SomeModel.objects.get(pk=pk)
log('MY_EVENT', request.user, obj)
Now my code looks like this when adding the above part:
from models import *
from django.template import Context, loader, RequestContext
from django.shortcuts import render_to_response , get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_protect
from django.core.mail import EmailMessage
#from django.contrib.formtools.tests.wizard.forms import request
from object_log.models import LogAction
from object_log.models import LogItem
register('MY_EVENT', 'template.html', build_cache)
def build_cache(user, obj1, obj2, obj3, data):
return {'foo':obj.foo}
LogAction.objects.register('MY_EVENT','path/to/my/template.html')
LogAction.objects.register('MY_EVENT','path/to/my/template.html')
# store log_action for faster access
log = LogItem.objects.log_action
def create_task(request):
#Employer.objects.filter(pk=request.session[user_id])
employer_id = request.user.id #Take the employer in the current session
getcategory = request.POST['cat_dd']
getsubcategory = request.POST['subcat_dd']
getname = request.POST['task_name']
getdesc = request.POST['task_desc']
getcountry = request.POST['country_dd']
getcity = request.POST['task_city']
getaddress = request.POST['task_address']
getstatus = request.POST['status_dd']
if (employer_id == NULL or getcategory == "Please select a category" or getsubcategory == "Please select a subcategory" or getname == "" or getdesc == "Write a short description about your task.." or getcountry == "(please select a country)" or getcity == "" or getaddress == "" or getstatus == ""):
return render_to_response('createTask.html',RequestContext(request))
else:
t = Task.objects.create(employer = employer_id, category = getcategory, subcategory = getsubcategory, name = getname, description = getdesc, country = getcountry, city = getcity, address = getaddress, status = getstatus, contractor = NULL)
t.save()
return render_to_response('task.html',RequestContext(request))
def edit_task(request, task_id):
t = get_object_or_404(Task, pk=task_id)
t.category = request.POST['cat_dd']
t.subcategory = request.POST['subcat_dd']
t.name = request.POST['task_name']
t.description = request.POST['task_desc']
t.country = request.POST['country_dd']
t.city = request.POST['task_city']
t.address = request.POST['task_address']
t.status = request.POST['status_dd']
log('MY_EVENT', request.user, t,data={'foo':obj.foo})
if (employer_id == NULL or getcategory == "Please select a category" or getsubcategory == "Please select a subcategory" or getname == "" or getdesc == "Write a short description about your task.." or getcountry == "(please select a country)" or getcity == "" or getaddress == "" or getstatus == ""):
return render_to_response('editTask.html',RequestContext(request))
else:
t = Task.objects.create(employer = employer_id, category = getcategory, subcategory = getsubcategory, name = getname, description = getdesc, country = getcountry, city = getcity, address = getaddress, status = getstatus, contractor = NULL)
t.save()
#log('MY_EVENT', request.user, obj, data={'foo':obj.foo})
return render_to_response('task.html',RequestContext(request))
But I got an error name 'register' is not defined
Is there any solution for the error??
Try:
LogAction.objects.register('MY_EVENT', 'template.html', build_cache)
instead of:
register('MY_EVENT', 'template.html', build_cache)
if we use
LogAction.objects.register('MY_EVENT', 'template.html', build_cache)
the error will become
NameError: name 'LogAction' is not defined

Categories

Resources