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.
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>
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 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>
I am iterating through a queryset in the template using template tags to show the data of existing database entries (i.e. Product Details of each product in a customer order). However, I want to show users some values (i.e. quantity and price) that are located in an intermediate m2m model between the Product and Order models for each product in the order.
My approach was to create the querysets in views and pass them through context into the template but I cannot seem to 'call' the values at the template using template tags for the intermediate m2m data. Perhaps my context is passing the wrong queryset or my approach is just wrong.
My code is below and I am thankful for any help you can give:
Models.py Snippet
class Product(models.Model):
article_number = models.ForeignKey('Article_number')
color = models.ForeignKey('Color')
size = models.ForeignKey('Size')
barcode = models.ForeignKey('Barcode')
product_name = models.ForeignKey('Product_name')
brand = models.ForeignKey('Brand')
category = models.ForeignKey('Category')
manufacturer = models.ForeignKey('Manufacturer')
cost_currency = models.ForeignKey('Cost_Currency', null=True, blank=True)
cost_price = models.DecimalField(decimal_places=2, max_digits=10)
selling_currency = models.ForeignKey('Selling_Currency', null=True, blank=True)
selling_price = models.DecimalField(decimal_places=2, max_digits=10)
description = models.TextField(null=True, blank=True)
created_on = models.DateTimeField(auto_now_add=True, auto_now=False)
updated_on = models.DateTimeField(auto_now_add=False, auto_now=True)
last_edited_by = models.ForeignKey(User, null=True, blank=True)
active = models.BooleanField(default=True)
class Meta:
unique_together = (("article_number", "size", "color"))
verbose_name = "Product"
verbose_name_plural = "*Products*"
def __unicode__(self):
return str(self.article_number) + "-" + str(self.color) + "-" + str(self.size)
class Order(models.Model):
order_status = models.ForeignKey('OrderStatus')
products = models.ManyToManyField(Product, through='OrderProductDetails', through_fields=('order','product'), null=True, blank=True)
counter = models.ForeignKey(Counter, null=True, blank=True)
order_type = models.ForeignKey('OrderType')
order_remarks = models.CharField(max_length=1000, null=True, blank=True)
order_date = models.DateTimeField(auto_now_add=True, auto_now=False)
ordered_by = models.ForeignKey(User, null=True, blank=True)
promo = models.ForeignKey('promo.Promo', verbose_name="Order for which Promotion (if applicable)", null=True, blank=True)
delivery_date = models.DateField(blank=True, null=True)
delivery_remarks = models.CharField(max_length=1000, null=True, blank=True)
updated_on = models.DateTimeField(auto_now_add=False, auto_now=True)
class Meta:
verbose_name = "Order"
verbose_name_plural = "*Orders*"
def __unicode__(self):
return str(self.id)
class OrderProductDetails(models.Model):
order = models.ForeignKey('Order')
product = models.ForeignKey('products.Product')
quantity = models.PositiveIntegerField()
selling_price = models.DecimalField(decimal_places=2, max_digits=10)
order_product_remarks = models.ForeignKey('OrderProductRemarks',blank=True, null=True)
class Meta:
verbose_name_plural = "Order - Product Details"
verbose_name = "Order - Product Details"
def __unicode__(self):
return str(self.id)
Views.py Snippet
from django.shortcuts import render, Http404, HttpResponseRedirect
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib import messages
from django.forms.models import modelformset_factory
from orders.models import Order, OrderStatus, OrderProductDetails
#login_required(login_url='/admin/login/?next=/')
def warehouseOrder(request, id):
try:
order = Order.objects.get(id=id)
products = order.products.all()
orderDetails = OrderProductDetails.objects.filter(order__id=id)
context = {'order': order, 'products': products, 'orderDetails': orderDetails}
template = 'warehouse_order.html'
return render(request, template, context)
except:
raise Http404
Template.html Snippet
<table class="table table-striped table-bordered">
<tr>
<th class="bottom-align-th">#</th>
<th class="bottom-align-th">Article No.</th>
<th class="bottom-align-th">Color</th>
<th class="bottom-align-th">Size</th>
<th class="bottom-align-th">Quantity</th>
<th class="bottom-align-th">Unit Price</th>
<th class="bottom-align-th">Remarks</th>
<th class="bottom-align-th">Barcode No.</th>
<th class="bottom-align-th">Packed</th>
</tr>
{% for product in products %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ product.article_number }}</td>
<td>{{ product.color }}</td>
<td>{{ product.size }}</td>
<td>{{ orderDetails.quantity }}</td>
<td>{{ orderDetails.selling_price }}</td>
<td>{{ orderDetails.order_product_remarks }}</td>
<td>{{ product.barcode }}</td>
<td><input type="checkbox" id="large-checkbox"></td>
</tr>
{% endfor %}
</table>
Btw, using Django 1.7.2 here.
You're looping over the wrong thing. Each Order has multiple OrderProductDetails related objects, each of which has exactly one Product. But you're looping over all products. Try something like:
{% for detail in orderDetails %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ detail.product.article_number }}</td>
<td>{{ detail.product.color }}</td>
<td>{{ detail.product.size }}</td>
<td>{{ detail.quantity }}</td>
<td>{{ detail.selling_price }}</td>
<td>{{ detail.order_product_remarks }}</td>
<td>{{ detail.product.barcode }}</td>
<td><input type="checkbox" id="large-checkbox"></td>
</tr>
{% endfor %}
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 %}