def Cart(request):
if request.user.is_authenticated:
customer=request.user.customer
order,created=Order.objects.get_or_create(customer=customer,complete=True)
items=order.orderitem_set.all()
print(items)
else:
items=[]
context={"items":items}
return render(request,'store/Cart.html',context)
i'm trying to show some orderitems in the Cart template but nothing appears so i tried to
print the items and i get a an despite in the admin pannel i assisgned in an order some orderitems
try this
def Cart(request):
if request.user.is_authenticated:
customer=request.user.customer
order=Order.objects.get_or_create(customer__user=customer,complete=True)
items=order.orderitem_set.all()
print(items)
else:
items=[]
context={"items":items}
return render(request,'store/Cart.html',context)
Related
I have a view and a model form as shown below. I initially could get a single item ID to use inn the view. Now I need multiple items selected from a Select2MultipleWidget. How would I do this? I already tried as shown in my code. I can understand that the data from the form to the view is not correct.
def new_issue(request,pk):
borrowed = request.session.get('teacher_borrowings')
if request.method == 'POST':
form = IssueForm(request.POST,pk=pk)
if form.is_valid():
try:
book = form.cleaned_data['book_id'].id
form.save(commit=True)
books = Books.objects.filter.get(id=book)
Books.Claimbook(books)
return redirect('all_borrowed_teacher', borrowed=borrowed)
except Exception as e:
return redirect('/')
else:
pass
return render(request, 'item.html)
def new_issue(request,pk):
borrowed = request.session.get('teacher_borrowings')
if request.method == 'POST':
form = IssueForm(request.POST,pk=pk)
if form.is_valid():
try:
book = form.cleaned_data['book_id'].id
form.save(commit=True)
books = Books.objects.filter.get(id=book)
Books.Claimbook(books)
return redirect('all_borrowed_teacher', borrowed=borrowed)
except Exception as e:
return redirect('/')
else:
pass
return render(request, 'item.html)
The error
Select a valid choice. That choice is not one of the available choices.
This is the view which was written for my django project.
if user is not None:
if user.is_active:
auth_login(request, user)
return HttpResponseRedirect('/home/')
else:
messages.error(self.request,
_("User is not Active"))
return HttpResponseRedirect('/')
else:
messages.error(self.request,_("User Does not Exist"))
return HttpResponseRedirect(settings.LOGIN_URL)
Suppose there is 3 groups of users customer,admin and super admin. How can I redirect the views to different html for each of the user groups? Thank You
if user.groups.all()[0].name == "groupname":
return redirect('some view')
you can do it like this
or if the user has many groups
l = request.user.groups.values_list('name',flat=True)
if "groupname" in l:
return redirect('some view')
i have a django website that runs a chatbot app to simulate a customer service by getting the question and retrieving the best match reply in the DB using queries.
view.py:
#csrf_exempt
def home(request):
context= locals()
template= 'home.html'
return render(request,template,context)
#csrf_exempt
def male_chatbot(request):
if not request.session.session_key:
request.session.create()
context= locals()
template= 'male_chatbot.html'
return render(request,template,context)
#csrf_exempt
def run_python_male(request):
if request.method == "POST":
session_key = request.session.session_key
param11 = request.POST.get('param1')
msg = chatbot.run_conversation_male(param11)
return JsonResponse({ 'msg': msg})
chatbot.py:
raw_chatting_log =[]
chatting_log =[]
def chatting_log_data(raw_Input,Input,check):
if check== "check":
if raw_Input in raw_chatting_log:
return True
else:
return False
else:
if check== "app":
raw_chatting_log.append(raw_Input)
chatting_log.append(Input)
def check_lastB():
new='جديد'
if len(raw_chatting_log) == 0:
return new
else:
return raw_chatting_log[-1]
def delandsave_chat_log():
name= str(uuid.uuid4())
thefile = open('/home/mansard/webapps/gadgetron/src/chatting_logs/'+name+'.txt', 'w')
for item in chatting_log:
thefile.write("%s\n" % item)
thefile.close()
raw_chatting_log.clear()
chatting_log.clear()
def run_conversation_male(user_in):
last_B = check_lastB()
H = user_in
NN1= "H:"+str(user_in)
New_H= ' '.join(PreProcess_text(H))
if last_B== 'تقييمك للمحادثة و الخدمة؟':
#do_somthing
else:
if chatting_log_data(H,NN1,"check") == True:
#do_somthing
else:
#find_replay
So, the idea is saving the input/output conversation in two list :
raw_chatting_log ==> hold the data with out the addition 'H:' or 'B:' just a the input and output.to help the chatbot remembering the asked questions and using it in chatting_log_data(H,NN1,"check").
chatting_log=> will hold the the conversation to the chat log in form of 'H:' and 'B:' to save the whole list when the user ends the conversation or close the page in def delandsave_chat_log()
and for last_B helps me know what is the chatbot's last responce
So far it is working for one user, now what i'm thinking is switching to make it handle or chat with many users at the same time where each user has it own chatbot.run_conversation_male and each chat/conversation is separate each with it own chatting log list so that i can use it for checking and saving the data.
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')
def addbook(request):
if request.method == 'POST':
book_name =request.POST['book_name']
Book = Book.objects.get()
Book.save()
return render_to_response('book_detail.html', {'books': books},context_instance=RequestContext(request))
else:
return render_to_response('addbook.html',context_instance=RequestContext(request))
def book_detail(request):
return render(request, 'book_detail.html')
the above is my view.py i am getting this error"MultiValueDictKeyError at /addbook/"
please help me
That error means that 'book_name' isn't in your POST data.
If you want to handle that case, you can use book_name = request.POST.get('book_name'), which will default book_name to None if it isn't in the POST data.
If not, you need to make sure the form has an input called 'book_name'.