output from different models in Django - python

I'm new in Django. And I have a problem((I can't display fields from different models. A lot of time was executed, but don't understand.
Here is my code.
This is my models:
from django.db import models
class Abonent(models.Model):
osrah = models.IntegerField(db_column='Osrah', primary_key=True)
pib = models.CharField(db_column='PIB', max_length=70)
adress = models.CharField(db_column='Adress', max_length=70)
meter = models.IntegerField(db_column='Meter')
date = models.DateField(blank=True, null=True)
created = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return "%s " % (self.pib)
class Oplata(models.Model):
abonent = models.ForeignKey(Abonent, db_column=False, blank=True,
null=True, default=None,on_delete=models.CASCADE)
idoplata = models.AutoField(primary_key=True)
from_date = models.DateField()
saldo = models.FloatField()
idstala = models.IntegerField(db_column='idStala')
created = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return "%s " % ( self.saldo,)
class Rahunok(models.Model):
abonent = models.ForeignKey(Abonent, blank=True, null=True,
default=None,on_delete=models.CASCADE)
idrahunok = models.AutoField(db_column='idRahunok', primary_key=True)
idstala = models.IntegerField(db_column='idStala')
datarah = models.DateField(db_column='dataRah')
pokaz1 = models.FloatField()
pokaz2 = models.FloatField()
spozkwt = models.FloatField(db_column='SpozKWT')
spozuah = models.FloatField(db_column='SpozUAH')
created = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
class Meta:
managed = False
db_table = 'rahunok'
And this my url.py:
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from abonent.models import Abonent,Oplata
urlpatterns = [
url(r'^$',ListView.as_view(queryset=Abonent.objects.all(),
template_name="abonent/abonents.html")),
url(r'^(?P<pk>\d+)', DetailView.as_view(model=Abonent,
template_name='abonent/persons.html')),
it's my person.html:
{% extends "mainApp/wrapper.html"%}
{% block content %}
<h2 class="text-info">{{ abonent.pib }}</h2>
<h2 class="text-info">{{ abonent.oplata.saldo }}</h2>
<h2 class="text-info">{{ abonent.oplata_set.idstala}}</h2>
<h5 class=" text-info">{{ abonent.adress }}</h5>
{% endblock %}
From model Abonent picks out everything, and doesn't want from Oplata.
What is the problem?
Would be very grateful if someone helps.

Django's DetailView by default puts the object in a key called object
def get_context_data(self, **kwargs):
"""
Insert the single object into the context dict.
"""
context = {}
if self.object:
context['object'] = self.object
context_object_name = self.get_context_object_name(self.object)
if context_object_name:
context[context_object_name] = self.object
context.update(kwargs)
return super(SingleObjectMixin, self).get_context_data(**context)
As you can see, you now have the object in context as the key object
Change your template to the following to make it work:
{% extends "mainApp/wrapper.html"%}
{% block content %}
<h2 class="text-info">{{ object.pib }}</h2>
<h2 class="text-info">{{ object.oplata.saldo }}</h2>
<h2 class="text-info">{{ object.oplata_set.idstala}}</h2>
<h5 class=" text-info">{{ object.adress }}</h5>
{% endblock %}

Related

When I am filtering the product but when I run the project I don't get the images

When I am filtering the product but when I run the project I don't get the images
If I change the code Product.objects.filter(slug=slug)
To
replce the code with Product.objects.get(slug=slug)
the I am facing this type off error in my trminal
Django 'Product' object is not iterable
Views.py
def product_detail(request, slug):
try:
product = Product.objects.filter(slug=slug)
context = {
'product': product,
}
return render(request, 'buyer/product_details.html', context)
except Product.DoesNotExist:
return render(request, 'buyer/product_details.html', {'error': 'No data found.'})
URLs.py
path('product/<slug:slug>', views.product_detail, name="product_detail"),
Models.py
class Product(models.Model):
total_quantity = models.IntegerField()
availability = models.IntegerField()
feature_image = models.ImageField(upload_to='media/Product_image')
product_name = models.CharField(max_length=100)
price = models.IntegerField()
discount = models.IntegerField()
product_information = RichTextField()
model_name = models.CharField(max_length=100)
categories = models.ForeignKey(MainCategory, on_delete=models.CASCADE)
tags = models.CharField(max_length=100)
description = RichTextField()
section = models.ForeignKey(Section, on_delete=models.DO_NOTHING)
slug = models.SlugField(default='', max_length=500, null=True, blank=True)
def __str__(self):
return self.product_name
def get_absolute_url(self):
from django.urls import reverse
return reverse("product_detail", kwargs={'slug': self.slug})
class Meta:
db_table = "buyer_Product"
def create_slug(instance, new_slug=None):
slug = slugify(instance.product_name)
if new_slug is not None:
slug = new_slug
qs = Product.objects.filter(slug=slug).order_by('-id')
exists = qs.exists()
if exists:
new_slug = "%s-%s" % (slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, Product)
class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
image_url = models.ImageField(upload_to='media/Product_image')
def __str__(self):
return self.product.product_name
HTML Page
<div class="product-image-slider">
{% for i in product.productimage_set.all %}
<figure class="border-radius-10">
<img src="{{ i.image_url }}" alt="product image"/>
</figure>
{% endfor %}
</div>
<!-- THUMBNAILS -->
<div class="slider-nav-thumbnails">
{% for i in product.productimage_set.all %}
<div><img src="{{ i.image_url }}" alt="product image"/></div>
{% endfor %}
</div>
</div>
<!-- End Gallery -->
You need to pass .url
{% for i in product.productimage_set.all %}
<figure class="border-radius-10">
<img src="{{ i.image.url }}" alt="product image"/>
</figure>
{% endfor %}
that's because:
Product.objects.get(slug=slug) returns a single object type porduct. and one single object is not iterable
and
Product.objects.filter(slug=slug) returns a Queryset[] of products (list of products)
so if you are looking to treat multiple products use the second way, but if you are looking to treat one single product, use the first one

Django queryset filter based on slug

I want to put a filter on a page which shows videos selecting an album shows up on album page not all the videos but my current filter is showing all the published videos. I couldn't find a way to put a filter based on slug that if an album's slug is matching with the current url then shows the video selecting that album. For example:- Videos created by Gaurav should only visible on Gaurav’s album not anyone else. I am all confused help me.
models.py
from django.db import models
from django.urls import reverse
STATUS = (
(1, "Publish"),
(0, "Draft")
)
class WatchCategory(models.Model):
title = models.CharField(max_length=20)
slug = models.SlugField(max_length=2000, unique=True)
def __str__(self):
return self.title
class Genre(models.Model):
title = models.CharField(max_length=20)
slug = models.SlugField(max_length=2000, unique=True)
def __str__(self):
return self.title
class Album(models.Model):
title = models.CharField(max_length=2000)
slug = models.SlugField(max_length=2000, unique=True)
image = models.CharField(max_length=2000, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('Watch:album', kwargs={
'slug': self.slug
})
class Video(models.Model):
title = models.CharField(max_length=2000)
slug = models.SlugField(max_length=2000, unique=True)
thumbnail = models.CharField(max_length=2000, unique=True)
updated_on = models.DateTimeField(auto_now=True)
file = models.CharField(max_length=2000)
time = models.CharField(max_length=2000, blank=True)
about = models.TextField(blank=True)
category = models.ManyToManyField(WatchCategory)
album = models.ManyToManyField(Album)
genre = models.ManyToManyField(Genre)
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=1)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('Watch:video', kwargs={
'slug': self.slug
})
views.py
class Album(ListView):
queryset = Video.objects.filter(status=1).order_by('-created_on')
template_name = 'Watch/album.html'
paginate_by = 6
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = 'Explore & Watch your favourite'
return context
album.html
{% extends "Watch/layout.html" %}
{% load static %}
{% block content %}
<div class="video-block section-padding">
<div class="row">
{% for video in video_list %}
<div class="col-xl-3 col-sm-6 mb-3">
<div class="video-card">
<div class="video-card-image">
<a class="play-icon" href="{% url 'Watch:video' video.slug %}"><i class="fas fa-duotone fa-circle-play"></i></a>
<img class="img-fluid" src="{{ video.thumbnail }}" alt="">
<div class="time">{{ video.time }}</div>
</div>
<div class="video-card-body">
<div class="video-title">
{{ video.title }}
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}

how to use Exists and OuterRef in prefetch_related in Django?

I have 3 models and I need to display the area and need items only if there is at least 1 product connected. If there are no products in particular Area and Need models then it should not appear in my HTML file.
I have checked the documentation and several answers related to this topic but I cannot implement it in my script.
I also tried to create my custom filter so I can apply it directly in my template but nothing worked.
My problem is that I am getting the list of all items from Need model and I don't know how to exclude empty items from HTML page.
I will appreciate any help.
models.py
class Area(models.Model):
title = models.CharField(max_length=75, blank=False)
body = models.CharField(max_length=150, default='-', blank=False)
publish = models.DateTimeField('publish', default=timezone.now)
class Need(models.Model):
title = models.CharField(max_length=75, blank=False, null=False, help_text='max 75 characters')
body = models.CharField(max_length=150, default='-', blank=False)
publish = models.DateTimeField(default=timezone.now)
need_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='need_area')
class ProductCategory(models.Model):
title = models.CharField(max_length=400, blank=False, null=False, help_text='max 400 characters')
body = models.TextField(default='-')
publish = models.DateTimeField('publish', default=timezone.now)
category_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='category_area', null=True)
category_need = models.ForeignKey(Need, on_delete=models.CASCADE, related_name='category_need', null=True)
class Product(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=400, blank=False)
category = models.ForeignKey(ProductCategory, on_delete = models.CASCADE, blank=True, related_name='products')
status = models.IntegerField(choices=STATUS, default=0)
def get_absolute_url(self):
return reverse("product", kwargs={'slug': self.slug})
views.py
class Search(ListView):
template_name = 'search.html'
model = Product
queryset = Product.objects.filter(status=1)
def get_context_data(self, **kwargs):
context = super(Search, self).get_context_data(**kwargs)
filter_need = Area.objects.filter(Exists(Need.objects.filter(need_area=OuterRef('pk'))))
areas = Area.objects.prefetch_related(Prefetch('need_area', queryset=filter_need, to_attr='need_area__category_need__product')).filter(need_area__category_need__product__status=1).distinct()
context['areas'] = areas
return context
search.html
{% if areas %}
{% for area in areas %}
<div class="border mb-4 pb-4 px-2">
<h2 class="fw-bold my-2">{{area.title}}</h2>
{% for need in area.need_area.all %}
<h4 class="text-muted mt-4">{{need.title}}:</h4>
{% for product_category in need.category_need.all %}
{% for product in product_category.product.all %}
<span class="rounded-pill bg-hubble text-dark f-12 p-2">{{product.title}}</span>
{% endfor %}
{% endfor %}
{% endfor %}
</div>
{% endfor %}
{% endif %}

Attempting to create view for a list of all books on loan to the current user

I am attempting to create a view that lists all the books on loan to a specific user in my library app. However I keep getting the following error :
When the user clicks on the books borrowed link the user should be redirected to the list view which contains the books the user borrowed with the name of the book rendered as a link that allows the user to access the detail view of the book.
Here is the code :
models.py
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from datetime import date
class Genre(models.Model):
genre_name = models.CharField(max_length = 200, help_text = "Enter a book genre")
def __str__(self):
return self.genre_name
class Mind_Book(models.Model):
Title = models.CharField(max_length=200)
author = models.ForeignKey('Author', on_delete=models.SET_NULL, null = True)
Summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book")
isbn = models.CharField('ISBN', max_length=13, help_text='13 Character ISBN Number')
genre_relation = models.ManyToManyField(Genre, help_text = "Selct a genre for this book")
language_relation = models.ForeignKey('Language', on_delete=models.SET_NULL, null = True)
def __str__(self):
return self.Title
# returns the url to access a particular book instance
def get_absolute_url(self):
return reverse('book-detail', args= [str(self.id)])
def genre_representation(self):
return ', '.join([genre_relation.genre_name for genre_relation in self.genre_relation.all()[:3]])
genre_representation.short_description = 'Genre'
import uuid
from datetime import date
class Instance_Book(models.Model):
Instance_ID = models.UUIDField(primary_key = True, default = uuid.uuid4, help_text = 'Unique ID for this particular book across whole library')
Book = models.ForeignKey('Mind_Book', on_delete=models.SET_NULL, null =True)
Imprint = models.CharField(max_length = 200)
due_back = models.DateField(null = True, blank = True)
borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null = True, blank = True)
#property
def is_overdue(self):
if self.due_back and date.today() > self.due_back:
return True
return False
LOAN_STATUS = (
('M', 'Maintenance'),
('O', 'On Loan'),
('A', 'Available'),
('T', 'Taciturn'),
)
Status =models.CharField(max_length = 1, choices=LOAN_STATUS, blank=True, default='M', help_text='Book availability')
class Meta:
ordering = ["due_back"]
permissions = (("can_mark_returned", "Set books as returned"),)
def __str__(self):
return '%s (%s) %s' % (self.Instance_ID, self.Book.Title, self.due_back)
class Author(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
date_of_birth = models.DateField(null=True, blank=True)
date_of_death = models.DateField('Died', null=True, blank=True)
def get_absolute_url(self):
return reverse('author-detail', args = [str(self.id)])
def __str__(self):
return '%s, %s' %(self.last_name, self.first_name)
class Language(models.Model):
language_Title = models.CharField(max_length=30, help_text="Enter a the book's natural language (e.g. English, French, Japanese etc.)")
def __str__(self):
return self.language_Title
views.py
class Mind_List_view(generic.ListView):
model = Mind_Book
paginate_by = 2
class Mind_Specific_view(generic.DetailView):
model = Mind_Book
class Author_List_view(generic.ListView):
model = Author
paginate_by = 2
class Author_Specific_view(generic.DetailView):
model = Author
class Mind_loan_By_UserListView(LoginRequiredMixin, generic.ListView):
model = Instance_Book
template_name = 'catalog/instance_book_list_borrowed_user.html'
def get_queryset(self):
return Instance_Book.objects.filter(borrower=self.request.user).filter(Status__exact='O').order_by('due_back')
class Mind_loanBooks_AllListView(PermissionRequiredMixin, generic.ListView):
model = Instance_Book
permission_required = 'catalog.can_mark_returned'
template_name = 'catalog/instance_book_list_borrowed_all.html'
def get_queryset(self):
return Instance_Book.objects.filter(Status__exact='O').order_by('due_back')
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.nest, name = 'nest'),
url(r'^index-page/$', views.index, name = 'index'),
url(r'^books/$', views.Mind_List_view.as_view(), name = 'books'),
url(r'^book/(?P<pk>\d+)$', views.Mind_Specific_view.as_view(), name='book-detail'),
url(r'^authors/$', views.Author_List_view.as_view(), name = 'authors'),
url(r'^author/(?P<pk>\d+)$', views.Author_Specific_view.as_view(), name = 'author-detail'),
]
urlpatterns += [
url(r'^user-books/$', views.Mind_loan_By_UserListView.as_view(), name = 'user-borrowed'),
url(r'^borrowed/$', views.Mind_loanBooks_AllListView.as_view(), name = 'all-borrowed')
]
template
{% extends "base_generic.html" %}
{% block content %}
{% if instance_book_list %}
<ul>
{% for instanceMind in instance_book_list %}
<li class="{% if instanceMind.is_overdue %}text-danger{%endif%}">
{{instanceMind.book.Title}}
{{instanceMind.Imprint }}
{{instanceMind.due_back}}
</li>
{% endfor %}
</ul>
{% endif %}
{% endblock %}
base template
{% block sidebar %}
<ul class="sidebar-nav">
<li>Dashboard</li>
<li>All authors</li>
<li>Home</li>
<li>All books</li>
{% if user.is_authenticated %}
<li>User: {{ user.get_username }}</li>
<li>Books Borrowed</li>
<li>Logout</li>
{% else %}
<li>Login</li>
{% endif %}
</ul>
{% if user.is_staff %}
<hr />
<ul class="sidebar-nav">
<li>Staff</li>
{% if perms.catalog.can_mark_returned %}
<li>All borrowed</li>
{% endif %}
</ul>
{% endif %}
{% endblock %}
the error tells you that there's there's no pk argument, wich is expected by the url book-detail

Django sub models do not appear in template

Maybe I cannot see the forest because of all the trees, but I have a very strange issue.
views.py:
from django.shortcuts import render
from models import Question, QuestionAnswerAlloc, Section
def home(request):
sections = Section.objects.all()
for s in sections:
questions = Question.objects.filter(section=s)
for q in questions:
answersalloc = QuestionAnswerAlloc.objects.filter(question=q)
q.answers.append(answersalloc)
s.questions.append(questions)
return render(request, "questionaire/index.html", {'sections': sections})
models.py:
from django.db import models
from portal.models import Customer
class Section(models.Model):
title = models.CharField(max_length=150)
weight = models.FloatField()
maxscore = models.FloatField()
questions = []
def __unicode__(self):
return "%s" % (self.title)
class Question(models.Model):
title = models.TextField()
section = models.ForeignKey(Section)
weight = models.FloatField()
answers = []
def __unicode__(self):
return self.title
class Answer(models.Model):
title = models.CharField(max_length=150)
points = models.IntegerField(default=0, help_text="This has to be a value between 0 and 5")
is_weighted = models.BooleanField(default=True, help_text="If this answer does not apply (N/a) it is not weighted!")
def __unicode__(self):
return self.title
class QuestionAnswerAlloc(models.Model):
question = models.ForeignKey(Question)
answer = models.ForeignKey(Answer)
def __unicode__(self):
return "Possible Answer"
class Report(models.Model):
STATUS_STARTED = "started"
STATUS_FIN = "finished"
STATUS_INPROG = "inprogress"
STATUS_ABORT = "aborted"
date = models.DateField(auto_now_add=True, blank=True)
title = models.CharField(max_length=150)
started_time = models.DateTimeField()
end_time = models.DateTimeField()
status = models.CharField(max_length=150, default=STATUS_STARTED)
guid = models.CharField(max_length=150, unique=True)
def __unicode__(self):
return self.title
class ReportAnswer(models.Model):
title = models.CharField(max_length=150)
orignal_answer = models.ForeignKey(Answer)
question = models.ForeignKey(Question)
section = models.ForeignKey(Section)
report = models.ForeignKey(Report)
points = models.FloatField()
weight = models.FloatField()
is_weighted = models.BooleanField(default=True)
customer = models.ForeignKey(Customer, blank=True, null=True)
def __unicode__(self):
return self.title
And my template:
{% for s in sections %}
<div class="row">
<div class="col-sm-12">
<div class="FormStepInfo">
<p class="QuestionaireSectionTitle">{{s.title}}</p>
<p class="QuestionaireSectionDesc"></p>
</div>
</div>
</div>
{% for q in s.questions %}
<div class="row">
<hr/>
<div class="col-sm-2 quest-num">{{forloop.counter }}</div>
<div class="col-sm-10 quest-title">
<label>
{{q.title}}
</label>
<br/>
<div class="CheckboxQuestion">
{% for a in q.answers %}
<label for=""><input type="radio" name="Q3" value="{{a.points}}" id="q3a1">{{a.title}}</label>
{% endfor %}
</div>
</div>
</div>
{% endfor %}
{% endfor %}
Unfortunately, the question title is not shown, neither the answers.
If I print out to sys.stderr i can see that there are questions assigned to the section. Am I missing something? I have restarted my "webserver", as I am using "python manage.py runserver" about 10 times and deleted my cache.
You have a fairly large misunderstanding of class definitions in Python. Usually when you define an attribute at class level it is shared by all members of the class. Django fields do some special magic to ensure that the values are per-instance rather than per-class, but your questions and answers lists do not do that. So even if you could get your code to work, all the answers would be associated with all the questions.
Luckily there's no need to do any of this. Django provides you with reverse accessors that provide exactly what you need. So the view can be simplified to just:
def home(request):
sections = Section.objects.all()
return render(request, "questionaire/index.html", {'sections': sections})
and the view becomes:
{% for s in sections %}
...
{% for q in s.question_set.all %}
...
{% for a in q.questionansweralloc_set.all %}
...etc

Categories

Resources