Dynamic Queryset Based on Special Model Django - python

I would like to have a page that contains product and related competitor products with it. I tried, but all the times competitor products stay same. Would you please help me?
models:
class Product(models.Model):
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.CharField(max_length=120)
brand = models.CharField(max_length=120)
product = models.CharField(max_length=120)
price = models.DecimalField(decimal_places=2,max_digits=100)
class Comp_Product(models.Model):
product = models.ForeignKey(Product,on_delete=models.CASCADE)
competitor = models.URLField()
price = models.DecimalField(decimal_places=2,max_digits=100)
change = models.FloatField()
stock = models.BooleanField()
last_update = models.DateField(auto_now_add=True)
views:
class ProductListView (ListView):
model = Comp_Product
context_object_name = 'comp_products'
template_name = 'products.html'
class ProductDetailView (LoginRequiredMixin,DetailView):
model = Product
template_name = 'product.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comp_products'] = Comp_Product.objects.all()
return context
urls.py:
path('product/<int:pk>/', ProductDetailView.as_view(),name='product_detail'),
path('comp_products/', ProductListView.as_view(),name='comp_products'),

Here you say comp_products = All the Comp Products in the database.
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
>>> context['comp_products'] = Comp_Product.objects.all()
return context
What do you display in your template? Is it {{comp_products}} or
{% for pr in product.comp_products.all %}
{{ pr }}
{% endfor %}
For this you need related_name="products" in your product field in the Comp_Product model

You may find the template that I wrote:
{%for comp_product in comp_products %}
{{comp_product.competitor}} - {{comp_product.price}} -
{{comp_product.change}} - {{comp_product.stock}} - {{comp_product.last_update}}
{%endfor%}

Related

How to pass unique objects from a second model in ListView function to the template django

I am creating a blog app in django. For that, I have made a page where all available blogs are listed. I am using generic.ListView view to achieve this. But, I also want to create a writer's section where I can list some details about the writers that have written those blogs. For this, I need to get all the users that have written a blog and then find distinct users from that and list out their username. I have an author field in my Blog model that keeps track of the writer user. How can I get the distinct usernames of these writers and pass it into my template?
Models.py:
class Blog(models.Model):
blog_head = models.CharField(max_length=100)
blog_header_image = models.ImageField(upload_to="photos/blogs/", null=True, blank=True)
#blog_content = models.TextField()
blog_content = RichTextField(blank=True, null=True)
#blog_summary = models.TextField(max_length=355)
blog_summary = models.CharField(max_length=100)
author = models.ForeignKey(User, on_delete=models.CASCADE)
blog_date = models.DateField(auto_now_add=True)
likes = models.ManyToManyField(User, related_name='blog_post_likes', blank=True)
def __str__(self):
return self.blog_head
def get_absolute_url(self):
return reverse('blog-full', args=[str(self.id)])
def blog_likes_count(self):
return self.likes.count()
Views.py:
class blogs_getting_Listview(ListView):
model = Blog
template_name = 'blogs.html'
ordering = ["-blog_date"]
def get_context_data(self, *args, **kwargs):
context = super(blogs_getting_Listview, self).get_context_data()
authors_id_list = Blog.objects.get(id=id).author
authors_list = ""
for author_in in authors_id_list:
author_obj = User.objects.get(id=author_id)
authors_list = authors_list + author_obj
context.update({
"authors_list": authors_list
#'more_context': Model.objects.all(),
})
print(type(context["authors_list"]))
return context
urls.py:
urlpatterns = [
#path('', views.blogs_getting, name='blogs/'),
path('', blogs_getting_Listview.as_view(), name='blogs/'),
path('blog/<int:pk>', blogs_getting_Detailview.as_view(), name='blog-full'),
path('new_blog/', add_blog_view.as_view(), name='add_blog'),
path('update_blog/<int:pk>', edit_blog_view.as_view(), name='update_blog' ),
path('delete_blog/<int:pk>', delete_blog_view.as_view(), name='delete_blog' ),
path('like/<int:pk>', like_view, name='like_blog' ),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
template:
{% for author in authors_list %}
<p>{{ author }}</p>
{% endfor %}
(Here I am trying to render the author objects' queryset on my page.)
Thankful for any help
Try accessing directly the author entitie:
class blogs_getting_Listview(ListView):
model = Blog
template_name = 'blogs.html'
ordering = ["-blog_date"]
def get_context_data(self, *args, **kwargs):
context = super(blogs_getting_Listview, self).get_context_data()
authors = Blog.objects.get(id=id)
authors_list = ""
for author in authors:
author_obj = User.objects.get(id=author.id)
authors_list.append(author_obj)
context["authors_list"] = authors_list
return context

How can exculde the data in Django

I am trying to exclude that orders which in my orderRequest table, but it show only that orders which is in orderRequest table and exclude the others.Function get the right id's of orders but it not exclude that orders. It exclude the other orders and show that orders which already in orderRequest table
View.py
class OrderProduct_View(TemplateView):
template_name = 'purchase/orderProduct.html'
def get(self, request, *args, **kwargs):
allOrder = OrderProduct.objects.all()
allOrd = Order.objects.all()
categories = Category.objects.all()
categoryId = self.request.GET.get('SelectCategory')
product = Product.objects.filter(category_id=categoryId)
def filter_order(order):
try:
orderReq = order.orderRequest
return orderReq
except:
return True
filteredOrders = list(filter(filter_order, allOrd))
args = {'categories': categories, 'product': product, 'filteredOrders': filteredOrders}
return render(request, self.template_name, args)
Model.py
class OrderProduct(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
description = models.CharField(max_length=90)
quantity = models.IntegerField()
order_cancel = models.BooleanField(default=False)
class Order(models.Model):
orderProduct = models.ForeignKey(OrderProduct, on_delete=models.CASCADE)
created_by = models.CharField(max_length=20)
created_at = models.DateTimeField(auto_now_add=True)
destination = models.CharField(max_length=30)
vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE)
shipping_cost = models.IntegerField()
class OrderRequest(models.Model):
order_status = models.CharField(max_length=10)
order = models.OneToOneField(Order, related_name='orderRequest', on_delete=models.CASCADE)
HTML
{% for allOrders in filteredOrders%}
{{ allOrders.orderProduct.id }}
{{ allOrders.orderProduct.product.name }}
{{ allOrders.orderProduct.quantity }}
<button>Place Order</button>
{% endfor %}
You can use the isnull lookup [Django docs] to find instances which don't have a related instance, so to find Order instances which have no OrderRequest instances you can use:
Order.objects.filter(orderRequest__isnull=True)
Hence you can write your view as:
class OrderProduct_View(TemplateView):
template_name = 'purchase/orderProduct.html'
def get(self, request, *args, **kwargs):
filteredOrders = Order.objects.filter(orderRequest__isnull=True)
categories = Category.objects.all()
categoryId = self.request.GET.get('SelectCategory')
product = Product.objects.filter(category_id=categoryId)
args = {'categories': categories, 'product': product, 'filteredOrders': filteredOrders}
return render(request, self.template_name, args)
Note: Class names should be in PascalCase so OrderProductView instead of OrderProduct_View. Variable names should be in
snake_case so filtered_orders instead of filteredOrders,
etc. See PEP 8 -- Style Guide for Python
Code
A:your function filter_order does not work, it always True;
B: return False in your try part

Django: the detail page is not showing(template error)

am working on a Django project where showing the details of post and amount
here is my models.py of post
class Loader_post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader")
pick_up_station = models.CharField(max_length=150)
destination_station = models.CharField(max_length=150)
sender_name = models.CharField(max_length=150)
phone_number = PhoneNumberField(null=False, blank=False, unique=True)
receiver_name = models.CharField(max_length=150)
def __str__(self):
return self.user.username
def get_absolute_url(self):
return reverse("Loader:my_job", kwargs={"pk": self.pk})
this is my second models which I inherit Loader post
class price(models.Model):
my_post = models.ForeignKey(Loader_post, related_name='prices',on_delete=models.CASCADE,
null=True, default='')
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, default='')
driver_price = models.CharField(max_length=150, null=True)
driver_name = models.CharField(max_length=150, null=True)
approved_price = models.BooleanField(default=False)
status = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse("Driver:Driverview")
def __str__(self):
return self.driver_price
this is the view.py of both list and details view
class offer_view(ListView, SelectRelatedMixin):
context_object_name = 'offern'
model = Loader_post
template_name = "offer.html"
def get_queryset(self):
qs = Loader_post.objects.filter(user=self.request.user)
return qs
class offer_view_detail(DetailView):
context_object_name = 'offernew'
model = Loader_post
template_name = "offer_detail.html"
here is my HTML page of list view ...when someone clicks on it it shows the detail of next post
offer.html
{% for my in offern %}
{{my.sender_name}} {% endfor %}
and when someone clicks on its route to the detail page .. but it shows template doesn't exist
this is my detail page ie. offer_details.hml
<p>{{offernew.sender_name}}</p>
<p>{{offernew.receiver_name}}</p>
{% for x in offernew.prices.all %}
<p>
<p>{{x.driver_name}}</p>
</p>
and this is urls.py
path('offerdetail/<int:pk>', views.offer_view_detail.as_view(),name="offerdetail"),
path('offer/', views.offer_view.as_view(), name="offer"),
Following on from comments,
In you ListView,
{{my.sender_name}}
here, the url specified is not defined in your urls.py, that's why it was showing no template doesn't exist, changing to this would solve this.
{{my.sender_name}}
Now, To show prices model in your DetailView, i would do something like this.
class offer_view_detail(DetailView):
context_object_name='offernew'
model = Loader_post
template_name = "offer_detail.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['price_model'] = self.object.prices.all()
return context
and In your Template
<p>{{offernew.sender_name}}</p>
<p>{{offernew.receiver_name}}</p>
{% for x in offernew.price_model %}
<p>{{x.driver_name}}</p>
{% endfor %}
Django Docs for DetailView

how to get all records of related models and display dynamic data in django

I'm new in django.I want to retrieve all the records from related models and display the dynamic data in templates. I tried by using raw sql also but i could not display dynamic data templates.
models.py:
class NewRegistration(models.Model):
houseowner_name_en = models.CharField(max_length=30)
ward_no = models.ForeignKey(system_settings.models.Wardno)
contactno = models.CharField(max_length=30)
construction_type = models.ForeignKey(system_settings.models.ConstructionType)
taxpayer_id = models.CharField(max_length=30, blank=True, null=True)
cen = models.IntegerField()
is_forwarded = models.BooleanField(default=False)
class Application(models.Model):
registration_date = models.CharField(max_length=15)
building_use = models.ForeignKey(to=system_settings.models.BuildingUse)
building_category = models.CharField(max_length=30)
building_structure_category = models.ForeignKey(to=system_settings.models.BuildingStructureCategory)
building_storey = models.IntegerField(blank=True, null=True, default=0)
reg = models.ForeignKey(NewRegistration)
class Landowner(models.Model):
landowner_type = models.CharField(max_length=30)
lo_salutation = models.CharField(max_length=30)
lo_name_np = models.CharField(max_length=30)
lo_citizenship_issue_date = models.CharField(max_length=30)
reg = models.ForeignKey(NewRegistration)
views.py:
def export(request):
all_objects = NewRegistrationModel.objects.all()
# houseowner= all_objects.houseownerinfo_set.all()
app_all=Application.objects.all()
landinfo=Landinfo.objects.all()
return render(request, 'exports.html', {'all_objects': all_objects})
I did it like this.
views.py
def export(request):
all_objects = NewRegistration.objects.all()
return render(request, 'exports.html', {'all_objects': all_objects})
exports.html
# in template when displaying
{% for registration in all_objects %}
{{ registration.fiscalyear }}
{% for owner in registration.landowner_set.all %}
{{owner.landowner_type}}
{{owner.lo_wardno}}
{% endfor %}
{% endfor %}
you can use generic.ListView in your views.py file like that:
class Export(generic.ListView):
model = NewRegistration
template_name = "your_template_name.html"
def get_queryset(self):
return NewRegistration.objects.all()
def get_context_data(self, **kwargs):
context = super(Export, self).get_context_data(**kwargs)
context['app_all'] = Application.objects.all()
context['landinfo'] = Landingo.objects.all()
return context
you can accees the datas in your template like that {{ app_all }} or {{ landinfo }}.

Django view with get context not working

Have a quick question. Trying to use a relational model in one DetailView. However, no matter what I try the data does not display. I've tried a few versions of template tags to no avail.
html
{% for parts in relatedparts %}{{ parts.name }}
</div>{% endfor %}
views.py
class ErrorCodeView(DetailView):
context_object_name = 'error_code_details'
model = models.ErrorCodes
template_name = 'error_code_details.html'
def get_context_data(self, **kwargs):
# xxx will be available in the template as the related objects
context = super(ErrorCodeView, self).get_context_data(**kwargs)
context['relatedparts'] = RelatedParts.objects.filter(name=self.get_object())
return context
models.py
class ErrorCodes(models.Model):
name = models.CharField(max_length=256)
description = models.CharField(max_length=400)
instructions = models.CharField(max_length=256)
PartsNeeded = models.CharField(max_length=120, default='')
usercomments = models.CharField(max_length=400, default='', blank=True)
relpic = models.ImageField(upload_to='media/',blank=True)
relpictwo = models.ImageField(upload_to='media/',blank=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("errorcodes:errorcodeview",kwargs={'name':self.name})
class RelatedParts(models.Model):
name = models.CharField(max_length=256)
related_error_code = models.ForeignKey(ErrorCodes, on_delete=models.PROTECT)
def __str__(self):
return self.name
You don't need to do this at all. You can follow the relationship in the template.
{% for part in object.relatedparts_set.all %}{{ part.name }}{% endfor %}
You don't need any code in the view to enable this.
could it be that "name=self.get_object()" should be "name=self.get_object().name" ?
You currently have:
context['relatedparts'] = RelatedParts.objects.filter(name=self.get_object())
but that is probably producing an empty queryset.

Categories

Resources