This is a single-page website that is kinda ecommerce site. I just want to count a single user how many products are ordered. How can I count?
index view:
def index(request):
total_user = User.objects.count()-1
total_orders =Frontend_Order.objects.count()
context = {
"total_user":total_user,
"total_orders":total_orders
}
return render(request,'0_index.html',context)
frontend_view:
def frontend_orders(request):
if request.user.is_authenticated:
if request.method == "POST":
frontend_orders_request = request.FILES['frontend_file'] if 'frontend_file' in request.FILES else None
sections = request.POST.get('numField11')
functionality = request.POST.get('frontend')
if functionality == "Portfolio":
price = int(sections)*10
elif (functionality == "e-Commerce") or (functionality == "social-media"):
price = int(sections)*15
Frontend_Order.objects.create(
files = frontend_orders_request,
Number_of_Section = sections,
Website_Functionality = functionality,
Price = price, USer = request.user,
Email = request.user.email
)
messages.success(request,f"{request.user.first_name}, Your order is procecing. I'll cotact you before placing the order.")
return redirect("/", userz = request.user)
else:
messages.error(request,"Please login or create an account.")
return redirect("/")
Frontend Order Model:
class Frontend_Order(models.Model):
USer = models.CharField(max_length=50, null=True)
Price = models.CharField(max_length=250, null=True)
Number_of_Section = models.CharField(max_length=250, null=True)
Website_Functionality = models.CharField(max_length=1, null=True)
Email = models.EmailField(max_length=50, null=True)
files = models.FileField(upload_to="new_file/", null=True, blank=True)
def __str__(self):
return str(self.pk) str(".") str(self.USer)
CodePudding user response:
You should use Frontend_Order.objects.filter(USer=userid)
(or Frontend_Order.objects.filter(USer.id=userid)
if it didn't worked) to get user orders by it's user id and then, use a for loop and a counter variable to iterate on filtered orders and add their products count to the counter.
It is better to reconsider your chosen names.
CodePudding user response:
Yes, it's possible. You can get the current user from the request object and use the filter method, like so:
def index(request):
total_user = User.objects.count()-1
total_orders =Frontend_Order.objects.filter(user=request.user).count()
context = {
"total_user":total_user,
"total_orders":total_orders
}
return render(request,'0_index.html',context)
However, this will only work if you connect your users to your orders, with a foreign key, instead of a CharField:
class Frontend_Order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
# etc...