I'm trying to display data that I put on a session for my shopping cart project that I'm developing,
but here I can't recover the product whose code I passed as a parameter
def index(request):
mes_produits={'produits':[{'code':'2BG12','nom':'banane sucré','prix':1500},
{'code':'MLO23','nom':'pomme de terre','prix':1800}]}
parcou=mes_produits['produits']
contex={'produits':parcou}
return render(request,'shop/index.html',contex)
def cart_add(request, code):
dico={'produits':[{'code':'2BG12','nom':'banane sucré','prix':1500},
{'code':'MLO23','nom':'pomme de terre','prix':1800}]}
mes_produits=dico['produits']
selected_product = next((item for item in mes_produits if item["code"] == code), None)
if selected_product != None:
request.session['nom']=selected_product.get('nom')
request.session['prix']=selected_product.get('prix')
contex={'nom':request.session['nom'],'prix':request.session['prix']}
return render(request, 'cart/cart_detail.html',contex)
car_detail.html
{% for key,value in request.session.items %}
Nom : {{value.nom}}
Prix : {{value.prix}}
{% endfor %}
I get a blank page with the name of the keys only
Your session object is a dict, not a list of tuple. Try this code in template:
Nom : {{request.session.nom}}
Prix : {{request.session.prix}}
But, you have already set the vars in context, so you can do:
Nom : {{nom}}
Prix : {{prix}}
# And your views.py
def cart_add(request, code):
dico={'produits':[{'code':'2BG12','nom':'banane sucré','prix':1500},
{'code':'MLO23','nom':'pomme de terre','prix':1800}]}
mes_produits=dico['produits']
selected_product = next((item for item in mes_produits if item["code"] == code), None)
if selected_product != None:
context={
'nom':selected_product.get('nom'),
'prix':selected_product.get('prix')
}
else:
context = {}
return render(request, 'cart/cart_detail.html',context)
Maybe you do not understand session usage?
https://docs.djangoproject.com/en/4.1/topics/http/sessions/
Related
I am creating a E commerce site in Django Everything is working fine but I am unable to display my QuerySet result in Django View
My Cart Function looks like this
def cart(request):
if request.method == 'POST':
return redirect('index')
else:
if request.method == 'GET':
# Recieve local storage product in post_id varibale
post_id = request.GET.get('get_cart')
cat_product = Product.objects.filter(id=.11)
if post_id is not None:
# Fomrat and remove { } and " from post_id string
post_id = post_id.replace('{','')
post_id = post_id.replace('}','')
post_id = post_id.replace('"','')
print("The Id is", post_id )
# Find ':' in string and get the value of id in cart_prod_index
index =0
while index < len(post_id):
index = post_id.find(':', index)
if index == -1:
break
local_storage_prod_id = post_id[index-1]
# '|' operator is used to append the queryset result
cat_product = cat_product | Product.objects.filter(id=local_storage_prod_id)
index+=2
print("Below Index" ,cat_product)
else:
print("Below else" ,cat_product)
# return render(request, "cart.html" ,{"x":cat_product,})
print(cat_product)
return render(request, "cart.html" ,{"cat_product":cat_product})
I have following Product in cat_product varibale
<QuerySet [<Product: Men Black T shirt>, <Product: White T Shirt>, <Product: Black Lady T Shirt>, <Product: Tomato>, <Product: White Ladies T Shirt>]>
When I use postman using Get Url i got the desired result
But in my browser it shows nothing I use following code in my cart.html page
<h2>You have Added the following product in your cart </h2>
{% for search in cat_product %}
<h3> {{search.name}}</h3>
<h3> {{search.price}}</h3>
<h3> {{search.id}}</h3>
{% endfor %}
I want to display my product in my cart.html
I need to display a pdf file in a browser, but I cannot find the solution to take the PDF for the folder media, the PDF file was save in my database, but I cannot show.
my urls.py:
urlpatterns = [
path('uploadfile/', views.uploadFile, name="uploadFile"),
path('verPDF/<idtermsCondition>', views.verPDF, name='verPDF'),
]
my models.py:
class termsCondition(models.Model):
title = models.CharField(max_length=20, verbose_name="title")
uploadPDF = models.FileField(
upload_to="PDF/", null=True, blank=True)
dateTimeUploaded = models.DateTimeField(auto_now_add=True)
deleted_at = models.DateTimeField(
auto_now=False, verbose_name="Fecha eliminacion", blank=True, null=True)
class Meta:
verbose_name = "termsCondition"
verbose_name_plural = "termsConditions"
my views.py:
def uploadFile(request):
user = request.user
if user.is_authenticated:
if user.is_admin:
if request.method == "POST":
# Fetching the form data
fileTitle = request.POST["fileTitle"]
loadPDF = request.FILES["uploadPDF"]
# Saving the information in the database
termscondition = termsCondition.objects.create(
title=fileTitle,
uploadPDF=loadPDF
)
termscondition.save()
else:
listfiles = termsCondition.objects.all()[:1].get()
return render(request, 'subirTerminos.html', context={
"files": listfiles
})
else:
messages.add_message(request=request, level=messages.SUCCESS,
message="No tiene suficientes permisos para ingresar a esta página")
return redirect('customer')
else:
return redirect('login2')
def verPDF(request, idtermsCondition):
user = request.user
if user.is_authenticated():
if user.is_admin:
getPDF = termsCondition.objects.get(pk=idtermsCondition)
seePDF = {'PDF': getPDF.uploadPDF}
print(seePDF)
return render(request, 'subirTerminos.html', {'termsCondition': getPDF, 'uploadPDF': getPDF.uploadPDF})
else:
messages.error(request, 'Do not have permission')
else:
return redirect('login2')
my html:
<div>
<iframe id="verPDF" src="media/PDF/{{ uploadPDF.url }}"
style="width:800px; height:800px;"></iframe>
</div>
I want to see my pdf and I cannot do, I want to know how to do, I tried many solutions, I accept js, embed iframe whatever to can solve.
It should be user.is_authenticated not user.is_authenticated() in verPDF view and also I'd recommend you to change <idtermsCondition> to <int:idtermsCondition> as by default (if nothing is given) it is considered as string.
urls.py
urlpatterns = [
path('uploadfile/', views.uploadFile, name="uploadFile"),
path('verPDF/<int:idtermsCondition>/', views.verPDF, name='verPDF'),
]
And the {{uploadPDF.url}} already has the url (full path to the media directory) and try to use <embed> tag so:
<div>
<embed id="verPDF" src="{{uploadPDF.url}}" width="500" height="375" type="application/pdf">
</div>
Note: Always add / at the end of every route
Finally I can solve it, I had problems in my views.py and in the html, when I called uploadPDF my views called another name which was loadpdf and when I rendered it it was another name.
now, views.py:
``def uploadFile(request):
user = request.user
if user.is_authenticated:
if user.is_admin:
if request.method == "POST":
# Fetching the form data
fileTitle = request.POST["fileTitle"]
loadPDF = request.FILES["uploadPDF"]
if termsCondition.objects.all().exists():
listfiles = termsCondition.objects.all()[:1].get()
listfiles.uploadPDF = loadPDF
listfiles.save()
else:
# Saving the information in the database
termscondition = termsCondition.objects.create(
title=fileTitle,
uploadPDF=loadPDF
)
return redirect('uploadFile')
else:
if termsCondition.objects.all().exists():
listfiles = termsCondition.objects.all()[:1].get()
return render(request, 'subirTerminos.html', context={
"files": listfiles.uploadPDF
})
else:
listfiles = {}
return render(request, 'subirTerminos.html', context={"files": listfiles})
else:
messages.add_message(request=request, level=messages.SUCCESS,
message="No tiene suficientes permisos para ingresar a esta página")
return redirect('customer')
else:
return redirect('login2') ``
and html:
<h1 class="title">Visualizador de PDF</h1>
<embed id="verPDF" src="{{files.url}}" width="500" height="375" type="application/pdf">
I am trying to pass user data from one template inside of another template. For this I use an ajax request, as well explained here How do I integrate Ajax with Django applications?
although no error shows up, nothing gets pulled.
here is what my model formset view look like inside of template 1:
def New_Sales(request):
#context = {}
form = modelformset_factory(historical_recent_data, fields=('id','Id', 'Date','Quantity', 'NetAmount', 'customer_name'))
if request.method == 'GET':
formset = form(queryset= historical_recent_data.objects.none())
#blank_form = formset.empty_form
elif request.method == 'POST':
formset = form(request.POST)
#blank_form = formset.empty_form
if formset.is_valid():
request.session['sale'] = request.POST.get('sale')
for check_form in formset:
check_form.save()
quantity = check_form.cleaned_data.get('Quantity')
id = check_form.cleaned_data.get('Id')
update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity)
update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') - quantity)
return redirect('/invoice/pdf/assembly/')
#else:
#form = form(queryset= historical_recent_data.objects.none())
return render(request, 'new_sale.html', {'formset':formset})
and here is the view to access template 1 data into template 2:
def generate_pdf_assembly(request):
my_company = MyCompany.objects.get(id = 1)
request = request.session.get('sale')
context = {'request' : request, 'my_company' : my_company }
print(context)
and here is the ajax request to access the data from the template (in template 2):
<h3> {{ context }} </h3>
<script>
$.ajax({
method: "GET",
url: "/new_sale.html",
sucess: function(context){
alert(context);
},
failure: function(context){
alert('got an error');
}
});
</script>
I feel like there must be an issue with the request.session in the view since no evident error gets outputed neither in log nor chrome console but I am not competent to debug it further at this point.
UPDATE: after changing context for request in tag template, the value None shows up, definitely an issue with the requesting
def username_exists(request):
data = {'msg':''}
if request.method == 'GET':
username = request.GET.get('username').lower()
exists = Usernames.objects.filter(name=username).exists()
if exists:
data['msg'] = username + ' already exists.'
else:
data['msg'] = username + ' does not exists.'`enter code here`
return JsonResponse(data)
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]))
I created a tag like this:
#register.inclusion_tag('post/comment_block.html')
def limit_amount_in_a_page(page_nr=1, post_id=1, amount=5):
starting_index = page_nr*amount
for index in range(starting_index, starting_index + amount):
dosomething()
has_prev = (page_nr != 0)
has_next = ((page_nr + 1) * amount) < comments.count()
return {
something
}
The problem is : page_nr is always not an int.
and this is how I call the tag and assign the value to page_nr in the tag:
{% limit_amount_in_a_page page_nr=my_page_nr post_id=post.id amount=4 %}
this is where the value of my_page_nr comes from:
def to_post_page(request, post_id, page_nr):
post = get_object_or_404(Post, id=post_id)
form = CommentForm()
comments = Comment.objects.filter(pk=post_id)
return render(request, 'post/posts.html', {
'post': post,
'form': form,
'comments': comments,
'my_page_nr': page_nr,
})
this is the url calling the view:
url(r'^(?P<post_id>[0-9]+)/(?P<page_nr>[0-9]+)/$', views.to_post_page, name="post"),
{% for post in my_posts %}
<li>{{post.title}}</li>
{% endfor %}
The value passed to this url tag should be a int. As you can see, I passed a 0.
Really appreciate for any help!
The value for page_nr is extracted from the URL, and is therefore a string. If you need it to be an int, it's simple to convert it - you could do this in the view, for example:
return render(request, 'post/posts.html', {
'post': post,
'form': form,
'comments': comments,
'my_page_nr': int(page_nr),
})