hie i want to display the order for each customer within a loop this is my view
def clientes(request):
all_clientes = Utilizadores.objects.filter(user_type='cliente')
all_orders = Checkout.objects.all()
context={'all_clientes':all_clientes,'all_orders':all_orders}
return render(request,'todos-clientes.html',context)
my template:
{% for all_clientes in all_clientes %}
<div class="item_wrapp">
<div class="contxt _7000">
<div class="img-def-doc-2 _9090903">
{% if all_clientes.imagem%}
<div class="img_cliente"style="background-image: url({{ all_clientes.imagem.url }}");>
</div>
{% else %}
<div class="img_cliente"></div>
{% endif%}
</div>
<div class="main_name_do_wrapp">
<div class="nome_produto">{{all_clientes.nome}}</div>
</div>
</div>
<div class="extra_item_1_wrapp produto">
{% for all_orders in all_orders %}
{% if all_orders.user_id == all_clientes.id %}
<div class="data num_encomendas_cliente">{{
all_orders.user_id|length }} encomendas(here should be displayed the number of orders for this particular customer) </div>
{% endif %}
{% endfor %}
class Checkout(models.Model):
user_id = models.IntegerField(null=True)
order_number = models.CharField(max_length=200, null=True)
def __str__(self):
return self
class Utilizadores(models.Model): nome= models.CharField(max_length=100, null=True) def str(self): return self
`
any help i would appreciate thank you.
Related
There is some problem, I'm trying to update the product on the client by making changes and clicking on the update button - my page is refreshing w/o updating info, so the product has the same data as before. But in the logs, the status code of the GET request is 200 and shows the updated object in the database. When I try to update through the admin Django dashboard, everything works successfully, the problem is only on the client side of the web application. What issues can there be?
Thank you in advance!
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
CATEGORY = (
('Stationary', 'Stationary'),
('Electronics', 'Electronics'),
('Food', 'Food'),
)
class Product(models.Model):
name = models.CharField(max_length=100, null=True)
quantity = models.PositiveIntegerField(null=True)
category = models.CharField(max_length=50, choices=CATEGORY, null=True)
def __str__(self):
return f'{self.name}'
class Order(models.Model):
name = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)
customer = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
order_quantity = models.PositiveIntegerField(null=True)
def __str__(self):
return f'{self.customer}-{self.name}'
views.py
#login_required(login_url='user-login')
#allowed_users(allowed_roles=['Admin'])
def product_edit(request, pk):
item = Product.objects.get(id=pk)
if request.method == 'POST':
form = ProductForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('dashboard-products')
else:
form = ProductForm(instance=item)
context = {
'form': form,
}
return render(request, 'dashboard/products_edit.html', context)
forms.py
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = '__all__'
html template:
{% extends 'partials/base.html' %}
{% block title %}Products Edit Page{% endblock %}
{% load crispy_forms_tags %}
{% block content %}
<div class="row my-4">
<div class="col-md-6 offset-md-3 p-3 bg-white">
<h3>Edit Item</h3>
<hr>
<form>
{% csrf_token %}
{{ form|crispy }}
<input class="btn btn-info" type="submit" value="Confirm">
</form>
</div>
</div>
{% endblock %}
You have forgotten to pass POST method you are using GET.
{% extends 'partials/base.html' %}
{% block title %}Products Edit Page{% endblock %}
{% load crispy_forms_tags %}
{% block content %}
<div class="row my-4">
<div class="col-md-6 offset-md-3 p-3 bg-white">
<h3>Edit Item</h3>
<hr>
<form method="post">
{% csrf_token %}
{{ form|crispy }}
<input class="btn btn-info" type="submit" value="Confirm">
</form>
</div>
</div>
{% endblock %}
I think I have a pretty basic UpdateView but the object is not saved when I submit the form. The success_url is never called. When I click the Update button, the form refreshes and I stay on the same page. I am able to update the object via admin, so I believe the model is working fine. I am not getting any errors.
urls
path('classroomdetail/<uuid:classroom_id>/',
views.classroomdetail, name='classroomdetail'),
path('classedit/<uuid:pk>/', views.ClassroomUpdateView.as_view(), name='classupdate'),
Model
class Classroom(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
classroom_name = models.CharField(max_length=20)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
students = models.ManyToManyField(Student)
class Meta:
constraints = [models.UniqueConstraint(
fields=['user', 'classroom_name'], name="unique-user-classroom")]
def __str__(self):
return self.classroom_name
views
class ClassroomUpdateView(UpdateView):
model = Classroom
fields = ['classroom_name']
template_name_suffix = '_update'
success_url = reverse_lazy('gradebook:classroom')
template
{% extends 'base.html' %} {% load static %} {% block content %}
{% load crispy_forms_tags %}
<div class="container">
<div class="row">
<div class="col">
<h3>This Classroom belongs to {{ classroom.course }}</h3>
</div>
</div>
<div class="row">
<div class="col-md-3">
<form class="form-group">
{% csrf_token %}{{ form|crispy }}
<input type="submit" class="btn btn-primary mt-2 mb-2" value="Update">
</form>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="ps-2">Cancel
</div>
</div>
</div>
{% endblock content %}
I was missing method="post" in my template. Correct line:
<form method="post" class="form-group">
I am trying to create a search function based on the title of my posts. Right now I am trying to implement this search using a filter but the list view is not rendering. I am unsure if I should implement a URL for my search function.
This is my model:
class Post(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(default = 'default0.jpg', upload_to='course_image/')
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=6)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
feedback = models.ManyToManyField(Feedback)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk' : self.pk})
This is my class-based list view:
class PostListView(ListView):
model = Post
template_name = 'store/sub_home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
ordering = ['date_posted']
paginate_by = 12
def get_queryset(self):
object_list = super(PostListView, self).get_queryset()
search = self.request.GET.get('q', None)
if search:
object_list = object_list.filter(title__icontains = title)
return object_list
This is my search bar:
<div id="search">
<form method='GET' action=''>
<input type="text" name='q' placeholder="">
<button id='search_holder'>
<img src="/static/store/search_icon.gif" id="search_icon">
</button>
</form>
</div>
This is my html that is rendering the posts:
{% extends "store/base.html" %}
{% block content %}
{% include "store/home_ext.html" %}
<div style="padding-top: 20px;" id="main" >
<section class="text-center mb-4">
<div class="row" id="random">
{% for post in posts %}
{% include "store/card.html" %}
{% endfor %}
</div>
<div class="row" id="subscription" style="display: none;">
{% if not subs %}
<h2>You have not subscribed to any course :/</h2>
{% endif %}
{% for post in subs %}
{% include "store/card.html" %}
{% endfor %}
</div>
<div class="row" id="content" style="display: none;">
{% if not mine %}
<h2>You have not published anything :/</h2>
{% endif %}
{% for post in mine %}
{% include "store/card.html" %}
{% endfor %}
</div>
</section>
{% include "store/pagination.html" %}
</div>
{% endblock content %}
This is my card.html:
{% load extra_filter %}
<div class="col-lg-3 col-md-6 mb-4">
<div id="course_card">
<div class="view overlay">
<img style="margin-left: -10px;" src="{{ post.image.url }}" alt="">
</div>
<div>
<div>
<strong>
{% if user.is_authenticated %}
<a class="title" href="{% url 'post-detail' post.id %}" >
{% else %}
<a class="title" href="{% url 'login' %}" >
{% endif %}
{% if post.title|length < 30 %}
<span>{{ post.title }}</span>
{% else %}
<span>{{ post.title|cut:27 }}</span>
{% endif %}
<span style="background-color: rgb(253, 98, 98);" class="badge badge-pill danger-color">NEW
</span>
</a>
</strong>
</div>
<div class="star-ratings-css">
<div class="star-ratings-css-top" style="width: {{ post.feedback|calc_rating }}%"><span>★</span><span>★</span><span>★</span><span>★</span><span>★</span></div>
<div class="star-ratings-css-bottom"><span>★</span><span>★</span><span>★</span><span>★</span><span>★</span></div>
</div>
<a href="{% url 'user-posts' post.author.username %}" class="author">
by {{ post.author }}
</a>
<div>
<strong style="text-align: right;" class="price">S${{ post.price }}
</strong>
</div>
<small class="date">
{{ post.date_posted|date:'d F y'}}
</small>
</div>
</div>
</div>
As Nalin Dobhal mentioned in comments, context_object_name should be posts not post. Because in template, you are iterating through posts context variable. Also, when using search functionality, the implementation should be like this:
class PostListView(ListView):
model = Post
template_name = 'store/sub_home.html' # /_.html
context_object_name = 'posts'
ordering = ['date_posted']
paginate_by = 12
def get_queryset(self, *args, **kwargs):
object_list = super(PostListView, self).get_queryset(*args, **kwargs)
search = self.request.GET.get('q', None)
if search:
object_list = object_list.filter(title__icontains = search)
return object_list
Because you are sending the search query through URL querystring(ie: url will look like /posts/?q=title in browser). I am using request.GET.get('q') to fetch those query string values, and use it to filter the queryset.
I've been trying to display the exact values of model with ManyToMany relation but I just couldn't, all what I've achevied is receiving QuerySet
<QuerySet [<Stack: PHP>, <Stack: js>]>
by adding to template tags
{{ brand.technologies.all }}
But I would like to receive and display 2 fields, name and icon. I've tried with some loops like
{% for brand in brands %}
{% for technologies in brand.technologies.all %} {{ technologies.name }} {{ technologies.icon }} {% endfor %}
{% endfor %}
but it doesn't give any results. There is not problem with syntax because page is displaying and looks like this
image
models.py
STACK = (
('PHP', 'PHP'),
('js', 'JavaScript'),
...
)
STACK_ICONS = (
('/static/icons/stack/php.png', 'PHP'),
('/static/icons/stack/javascript.png', 'JavaScript'),
...
)
class Company(models.Model):
name = models.CharField(max_length=100, blank=False)
students = models.CharField(max_length=3, choices=STUDENTS)
type = models.CharField(max_length=15, choices=TYPES)
workers = models.PositiveIntegerField(validators=[MinValueValidator(1)])
city = models.CharField(max_length=15,choices=CITIES)
company_about = models.TextField(max_length=500, blank=False)
slug = models.SlugField(unique=True)
icon = models.ImageField(blank=True, null=True)
image = models.ImageField(blank=True, null=True)
logo = models.ImageField(blank=True, null=True)
technologies = models.ManyToManyField('Stack')
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Company, self).save(*args, **kwargs)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.name
# object stack relation manytomany with Company
class Stack(models.Model):
name = models.CharField(max_length=30, choices=STACK)
icon = models.CharField(max_length=80, choices=STACK_ICONS)
def __str__(self):
return self.name
views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
...
def comp_list(request):
f = CompanyFilter(request.GET, queryset=Company.objects.all())
return render(request, 'company/comp_list.html', {'filter': f})
def companies(request):
company = get_object_or_404(Company)
return render(request, 'company/comp_list.html', {'company': company})
def home(request):
return render(request, 'company/home.html')
def brands(request, slug):
brand = get_object_or_404(Company, slug=slug)
return render(request, 'company/comp_view.html', {'brand': brand})
def stacks(request):
stack = get_object_or_404(Stack)
return render(request, 'company/comp_view.html', {'stack': stack})
comp_view.html
{% extends 'company/base.html' %}
{% block content %}
<div class="row company-details">
<div class="col col-md-2"></div>
<div class="col col-md-8">
<input class="btn btn-success" type="button" value="Go Back" onclick="history.back(-1)" />
<div class="col col-md-12 company-bg" style="background-image: url('{{ brand.image.url }}'); background-repeat: no-repeat, repeat;">
</div>
<div class="bottom-overlay"></div>
<div class="company-description">
<div class="heading">
<div class="title">About us</div>
<div class="social-media">
Facebook
</div>
</div>
<div class="company-about">
{{ brand.company_about }}
</div>
</div>
<div class="company-stats">
<div class="company-logo-container">
<img class="company-logo" src="{{ brand.logo.url }}">
</div>
<div class="company-attributes">
<div class="field-group">
<div class="field">Type</div>
<div class="value">{{ brand.type }}</div>
</div>
<div class="field-group">
<div class="field">Company size</div>
<div class="value">{{ brand.workers }}+</div>
</div>
<div class="field-group">
<div class="field">Headquarters</div>
<div class="value">{{ brand.city }}</div>
</div>
<div class="field-group">
<div class="field">Open for students</div>
<div class="value">{{ brand.students }}</div>
</div>
</div>
<div class="technologies-section">
<p class="tech-heading">Technologies</p>
<div class="technologies-wrapper">
{{ brand.technologies.all }}
{% for brand in brands %}
{% for technologies in brand.technologies.all %} {{ technologies.name }} {% endfor %}
{% endfor %}
</div>
</div>
</div>
<div class="col col-md-2"></div>
</div>
{% endblock %}
I don't understand why you've suddenly added an outer loop through brands. You don't have anything called brands, and you're successfully accessing all the other data via brand. Just continue to do so, and drop the outer loop.
<div class="technologies-wrapper">
{% for technologies in brand.technologies.all %} {{ technologies.name }} {% endfor %}
</div>
**Models.py**
class User(auth.models.User,auth.models.PermissionsMixin):
def __str__(self):
return "#{}".format(self.username)
def get_absolute_url(self):
return reverse("accounts:login")
class Group(models.Model):
name = models.CharField(max_length = 255,unique = True)
slug = models.SlugField(allow_unicode = True,unique = True)
description = models.TextField(default = '')
members = models.ManyToManyField(User,related_name = "group")
def save(self,*args,**kwargs):
self.slug = slugify(self.name)
super(Group,self).save(*args,**kwargs)
def get_absolute_url(self):
return reverse('groups:single',kwargs = {'slug':self.slug})
def __str__(self):
return self.name
**Views.py**
class ListGroups(ListView):
model = Group
**Html code**
<div class="col-md-8">
<div class="list-group">
{% if user.is_authenticated %}
<h2>Your Groups!</h2>
{% if user.group.count == 0 %}
<p>You have not joined any groups yet! <p>
{% else %}
{% for group in user.group.all %}
<a class="list-group-item" href="{% url 'groups:single' slug=group.slug %}">
<h3 class="list-group-item-heading">{{group.name}}</h3>
<div class="list-group-item-text container-fluid">
{{group.description|safe}}
<div class="row">
<div class="col-md-4">
<span class='badge'>{{group.members.count}}</span>
member{{group.members.count|pluralize}}
</div>
<div class="col-md-4">
<span class='badge'>{{group.posts.count}}</span>
post{{group.posts.count|pluralize}}
</div>
</div>
</div>
</a>
{% endfor %}
{% endif %}
{% endif %}
</div>
According to me it should print all the groups and it's details to which current logined user belongs but it is not printing anything.I have no idea what is wrong in this code.I have tried some other approaches but nothing works.Can anyone help?
Thanks in advance.
Well there is no variable named user in the template, hence all what you wrote will probably not work.
We can however obtain a list of Groups where the logged in user is member of, by first of all modifying the ListsGroup a bit:
from django.contrib.auth.mixins import LoginRequiredMixin
class ListGroups(LoginRequiredMixin, ListView):
model = Group
def get_queryset(self):
return Group.objects.filter(members=self.request.user)
Now we can render this like:
<div class="col-md-8">
<div class="list-group">
<h2>Your Groups!</h2>
{% for group in object_list %}
<a class="list-group-item" href="{% url 'groups:single' slug=group.slug %}">
<h3 class="list-group-item-heading">{{group.name}}</h3>
<div class="list-group-item-text container-fluid">
{{group.description|safe}}
<div class="row">
<div class="col-md-4">
<span class='badge'>{{group.members.count}}</span>
member{{group.members.count|pluralize}}
</div>
<div class="col-md-4">
<span class='badge'>{{group.posts.count}}</span>
post{{group.posts.count|pluralize}}
</div>
</div>
</div>
</a>
{% empty %}
<p>You have not joined any groups yet! <p>
{% endfor %}
</div>