I am trying to show names of the cities of a certain countries {{city}}.
For example if I click "USA" it should show the list of the cities in my database.
But I don't know how to filter it right.
I tried this but nothing show up.
Post.objects.filter(country='country').filter(city='city')
This is my model
class Post(models.Model):
title = models.CharField(max_length=255)
country = models.CharField(max_length=255)
city = models.CharField(max_length=255)
address = models.CharField(max_length=255)
email = models.EmailField(max_length=255)
phone = models.CharField(max_length=255)
website = models.CharField(max_length=255)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('users:blog')
This is my view
def cities(request):
context = {
'posts': Post.objects.filter(country='country').filter(city='city')
}
return render(request, 'users/cities.html', context)
This is my template:
{% for post in posts %}
<table class="table table-hover text-left col-sm-6" style="table-layout: fixed; word-wrap: break-word;">
<tbody>
<tr>
<td>{{ post.id }}</td>
<td>{{ post.city }}</td>
</tr>
</tbody>
</table>
{% endfor %}
{% endblock %}
</div>
You can use values_list and call distinct() to get city names from Post model:
views
def cities(request):
queryset = Post.objects.filter(country='country').values_list(
'city', flat=True).distinct().order_by('city')
return render(request, 'users/cities.html', {'cities': queryset})
template
<table>
<tbody>
{% for city in cities %}
<tr>
<td>{{ city }}</td>
</tr>
{% endfor %}
</tbody>
</table>
Related
how to get book name which is related author,
i want author name in first column and book name in 2nd column,
by querying Author.objects.all() i got author name but i want book name which is related to that author in 2nd column like.
col-1, author-mahesh, book-Harry potter
col-2, author-naresh, book-game of thrones
models.py
class Author(models.Model):
author_name = models.CharField(max_length = 100)
def __str__(self):
return self.author_name
class Book(models.Model):
book_title = models.CharField(max_length = 100)
desc = models.TextField(max_length = 300)
authors = models.ManyToManyField(Author, related_name ='author')
def __str__(self):
return self.book_title
def written_by(self):
return ",".join([str(p) for p in self.authors.all() ])
views.py
from .models import Author, Book
# Create your views here.
def manytomany(request):
authors = Author.objects.all()
book = Book.objects.all()
# author_first = Author.objects.get(author_name='Mahesh')
# book_author = author_first.author.all()
book_author = Author.objects.get(id=1).author.all()
context = {
'authors':authors,
'book': book,
'book_author':book_author,
}
return render(request, 'many-to-many.html', context)
HTML
<div class="col-lg-12">
<table class="table table-striped">
<thead>
<tr>
<th>Author Name</th>
<th>Book</th>
</tr>
</thead>
<tbody>
{% for author in authors %}
<tr>
<td>{{ author.author_name }}</td>
{% for j in book_author %}
<td>{{ j }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
app1/model
class Deployment(models.Model):
uid = models.CharField(max_length=255, blank=True)
target = models.CharField(max_length=255)
name = models.CharField(max_length=255, blank=True)
description = models.TextField(blank=True)
app2/model
class AccountRecord(models.Model):
name = models.CharField(max_length=255, blank=True)
file_name = models.CharField(max_length=255, blank=True)
national_id = models.CharField(max_length=255, default="")
app3/views.py
class IndexView(LoginRequiredMixin, ListView):
model = AccountRecord
template_name = "tableview/table_view.html"
paginate_by = 25
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['deployment'] = Deployment.objects.all()
return context
app3 html template
<table class="table card-table table-vcenter text-nowrap">
<thead>
<tr>
<th>Deployment</th>
<th>Account</th>
<th>National ID</th>
<th>Filename</th>
</tr>
</thead>
<tbody>
{% for account in object_list %}
<tr>
<td>DEPLOYMENT.NAME HERE!</td>
<td>{{ account.name }}</td>
<td>{{ account.national_id }}</td>
<td>{{ account.file_name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
I am trying to pass data from these 2 model to another apps html template.
with my current app3/views.py the table only show blank column even after i put {{ deployment.name }}
can anyone point out how to do it correctly.
Here is my Model_Items:
class Model_Items(models.Model):
title = models.CharField(max_length=20, default='')
manufacturer = models.CharField(max_length=10, default='')
make = models.CharField(max_length=20, default='')
model = models.CharField(max_length=20, default='')
sku = models.CharField(max_length=10, default='')
Which the Po has a ManyToMany relationship with:
class Po(models.Model):
po_number = models.CharField(max_length=10, default='')
receive_date = models.DateField(auto_now=False, auto_now_add=False, default='')
model_item = models.ManyToManyField(Model_Items)
site_code = models.CharField(max_length=10, default='')
comment = models.TextField(max_length=50, default='')
Now in my View I query it :
def po_page(request, *args, **kwargs):
po = Po.objects.all()
context = {
'po_list': po,
}
return render(request, 'po/po_page.html', context)
On my Template:
{% for my_po_list in po_list %}
<div class="card">
<table class="table table-bordered" >
<tr>
<td class="col-md-2">{{ my_po_list.po_number }}</td>
<td class="col-md-2">{{ my_po_list.receive_date }}</td>
<td class="col-md-2">{{ my_po_list.model_item.all }}</td>
<td class="col-md-2">{{ my_po_list.site_code }}</td>
<td class="col-md-2">{{ my_po_list.comment }}</td>
<td class="col-md-2">{{ model }}</td>
</tr>
</table>
</div>
{% endfor %}
I have been struggling to get get title from Model_Items class and displaying it.
However the line with:
{{ my_po_list.model_item.all }}
Displays the following instead
<QuerySet [<Model_Items: Mac 16 Dev>, <Model_Items: Mac 13 Std>]>.
I know the line is suppose to do that but how can I filter it so it just displays the Model_Items title.
I would recommend using a for loop to loop through the model items. I also added in what you would do to add commas between the titles.
<td class="col-md-2">
{% for model_item in my_po_list.model_item.all %}
{{model_item. title}}{% if not forloop.last %}, {% endif %}
{% endfor %}
</td>
I'm trying to display a product, and available brands(has product as ForeignKey) for that product through DetailView. Based on Django documentation and similar answers on stackoverflow, I tried below code but it doesn't work. Product details are rendering but names of brands are not. I've checked through django-admin, that the brands the products are present in the database.
Could someone please help.
Models.py
class Product(models.Model):
name = models.CharField(max_length=256)
price = models.IntegerField()
class Brand(models.Model):
name = models.CharField(max_length=256)
product = models.ForeignKey(Product,on_delete=models.PROTECT,related_name='Brands')
Views.py
class ProductDetailView(DetailView):
model = Product
Urls.py
path('detail/<int:pk>/',views.ProductDetailView.as_view(),name='product_detail'),
product_detail.html
<table class="table table-bordered table-hover table-secondary">
<tr>
<th class="bg-secondary th-customer-detail">Name</th>
<td>{{ product.name }}</td>
</tr>
<tr>
<th class="bg-secondary th-customer-detail">Price</th>
<td>{{ product.price }}</td>
</tr>
</table>
<br>
<ul>
{% for brand in product.brand_set.all %}
<li>{{ brand.name }}</li>
{% endfor %}
</ul>
You can do it this way
class ProductDetailView(DetailView):
model = Product
context_object_name = 'product'
def get_context_data(self,**kwargs):
context = super(ProductDetailView,self).get_context_data(**kwargs) #returns a dictionary of context
primary_key = self.kwargs.get('pk')
brands = Brand.objects.filter(product = primary_key)
new_context_objects = {'brands':brands}
context.update(new_context_objects)
return context
<table class="table table-bordered table-hover table-secondary">
<tr>
<th class="bg-secondary th-customer-detail">Name</th>
<td>{{ product.name }}</td>
</tr>
<tr>
<th class="bg-secondary th-customer-detail">Price</th>
<td>{{ product.price }}</td>
</tr>
</table>
<br>
<ul>
{% for brand in brands %}
<li>{{brand.name}}</li>
{% endfor %}
</ul>
I playing around with a simple addressbook application and I'd like to show the company of a contact in a DetailView of a contact.
In my template:
<table class="table table-bordered table-condensed" style="width:50%;">
{% for company in companies %}
{% if company.name == contact.company %}
<tr>
<td>{{ company.name }}</td>
<td>{{ company.street }}</td>
<td>{{ company.plz }}</td>
<td>{{ company.city }}</td>
</tr>
{% endif %}
{% endfor %}
</table>
My view:
class ContactView(DetailView):
model = Contact
template_name = 'contact.html'
def get_context_data(self, **kwargs):
context = super(DetailView, self).get_context_data(**kwargs)
# Companies
context['companies'] = Company.objects.all()
# Return
return context
In my models:
class Company(models.Model):
name = models.CharField(max_length=255,)
and
class Contact(models.Model):
first_name = models.CharField(max_length=255, blank=True, null=True)
last_name = models.CharField(max_length=255,)
company = models.ForeignKey(Company, blank=True, null=True)
What is wrong with the if statement in my template?
Thanks for your help in advance!
You should compare the company itself, not the name.
Change
{% if company.name == contact.company %}
to
{% if company == contact.company %}