I need to display some product's supplier, next to {{product.description}} but I can't get it to show on my table.
models.py
class Supplier(models.Model):
name = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
class Product(models.Model):
sku = models.IntegerField(null=True)
description = models.CharField(max_length=30)
costprice = models.FloatField(null=True, max_length=99, blank=True)
retailprice = models.FloatField(null=True, max_length=99, blank=True)
barcode = models.CharField(null=True, max_length=99, unique=True)
image = models.ImageField(null=True, blank=True)
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.description
views.py
def products(request):
products = Product.objects.all()
suppliers = Supplier.objects.all()
context = {'products': products,
'suppliers': suppliers}
return render(request, 'crmapp/products.html', context)
products.html
<tr>
{% for product in products %}
<td>{{product.id}}</td>
<td><h6><strong>{{product.description}}</strong></h6></td>
<td >{{products.supplier}}</td>
<td>£{{product.costprice |floatformat:2}}</td>
<td>£{{product.retailprice |floatformat:2}}</td>
<td>{{product.barcode}}</td>
</tr>
{% endfor %}
Spelling mistake, I think.
<td >{{products.supplier}}</td>
Must be:
<td >{{product.supplier}}</td>
Notice I've removed the s in products.
Also, you don't need this in your views.py:
suppliers = Supplier.objects.all()
{{product.supplier}} will trigger a query to the db. To avoid that, use prefetch_related.
products = Product.objects.all().prefetch_related('supplier')
Note that this is optional. It will just improve efficency, but merely fixing the spelling mistake answers your question.
Related
I would like to get all items belonging to an invoice and show them to a template without success. What i have done so far is the following:
I have two models:
class Invoice(models.Model):
PAYMENT_OPTIONS = (
('CASH', _('CASH')),
('DEPOSIT', _('DEPOSIT')),
('CARD', _('CARD')),
)
INVOICE_TYPE = (
('Service', _('Service')),
)
invoice_number = models.CharField(max_length=7, unique=True, default='INV4898')
invoice_user = models.ForeignKey(Account, on_delete=models.CASCADE)
invoice_type = models.CharField(max_length=30, choices=INVOICE_TYPE, default='Service')
payment_option = models.CharField(max_length=30, choices=PAYMENT_OPTIONS)
invoice_name = models.CharField(max_length=30, null=True, blank=True)
vat = models.CharField(max_length=9, blank=True, null=True)
gross_amount = models.DecimalField(max_digits=6, decimal_places=2)
vat_amount = models.DecimalField(max_digits=6, decimal_places=2)
net_amount = models.DecimalField(max_digits=6, decimal_places=2)
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.invoice_user.first_name} {self.invoice_user.last_name} - {self.invoice_number}"
class Item(models.Model):
invoice = models.ForeignKey(Invoice, related_name='items', on_delete=models.CASCADE)
title = models.CharField(max_length=255)
quantity = models.IntegerField(default=1)
unit_price = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00'))
net_amount = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00'))
vat_rate = models.CharField(max_length=10, default=0)
discount = models.DecimalField(max_digits=6, decimal_places=2, default=Decimal('0.00'))
is_paid = models.BooleanField(default=False)
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.invoice.invoice_number}"
In the views.py i have a list view like, in which i'm trying to get a list of all invoices based on invoice_number and then match each invoice_number to an invoice in items. However using below code first pring brings all invoice_number(s) and second print brings all items for all invoices, not items per invoice.
def list_invoices(request, userprofile_id):
user_profile = get_object_or_404(Account, pk=userprofile_id)
all_invoices =Invoice.objects.filter(invoice_user=user_profile)
invoice_number = Invoice.objects.values_list('invoice_number')
print(invoice_number)
item_invoice = Item.objects.filter(invoice__invoice_number__in=invoice_number)
print(item_invoice)
context = {
'all_invoices': all_invoices,
'user_profile': user_profile,
'item_invoice': item_invoice,
}
return render(request, 'invoices/list-invoices.html', context)
I would appreciate any help.
You do not need to fetch the Items not the invoice_number of the Invoice. You only need to pass the invoices of the user_profile, and it might be better to also prefetch the Items:
def list_invoices(request, userprofile_id):
user_profile = get_object_or_404(Account, pk=userprofile_id)
all_invoices = Invoice.objects.filter(
invoice_user=user_profile
).prefetch_related('items')
context = {
'all_invoices': all_invoices,
'user_profile': user_profile
}
return render(request, 'invoices/list-invoices.html', context)
then in the template, you can access the .items, so:
<ul>
{% for invoice in all_invoices %}
<li> {{ invoice.invoice_number }}</li>
<ul>
{% for item in invoice.items.all %}
<li>{{ item.quantity }} {{ item.title }}</li>
{% endfor %}
</ul>
{% endfor %}
</ul>
I'm trying to add extra content to Djangos Class-based view to the template
I have some models like this
class District(models.Model):
district = models.CharField(max_length=255, null=False, unique=False, blank=True)
def __str__(self):
return self.district
class Street(models.Model):
street_name = models.CharField(max_length=255, null=False, unique=False, blank=True)
district = models.ForeignKey(District, verbose_name=_('district'), on_delete=models.CASCADE, null=True, blank=True)
zone = models.IntegerField(blank=True, null=True)
def __str__(self):
return self.street_name
class Article(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name="author", on_delete=models.SET_NULL)
timestamp = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=1, choices=STATUS, default=CREATED)
comment = models.CharField(max_length=255, null=True, unique=False, blank=True)
name = models.CharField(max_length=255, null=True, unique=False)
street = models.ForeignKey(Street, verbose_name=_('street'), on_delete=models.CASCADE, null=True, blank=True)
class ArticlesListView(LoginRequiredMixin, PermissionRequiredMixin,ListView):
model = Article
paginate_by = 50
context_object_name = "articles"
permission_required = 'is_staff'
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['Filter_name'] = Article.objects.order_by().values('name').distinct()
context['Filter_user'] = Article.objects.order_by().values('user').distinct()
return context
def get_queryset(self, **kwargs):
return Article.objects.all()
And late in the template
{% for f in Filter_name %}
<ul>
<li>{{f.name}}</li>
</ul>
{% endfor %}
How can I display a list of the district names and a list of the author names in the template with ForeignKey?
U can try something like that
{% for item in model_1.foreign_model_set.all %}
<h1>{{ item }}</h1>
{% endfor %}
I am trying to get my html form to allow me to pass the company model instance. As of now, I can pull the names of each company instance, however, what would I put into the value attibute of the option field to have it select the instance correctly?
<option value="what to put here?">{{Company.name}}</option>
I was hoping to do this through HTML forms and not Django forms as I have used AJAX to make a nice little live-updating interface.
models.py
class Company(models.Model):
name = models.CharField(max_length=30, null=True, blank=True)
email = models.CharField(max_length=40, null=True, blank=True)
phone = models.CharField(max_length=15, null=True, blank=True)
address = models.CharField(max_length=100, null=True, blank=True)
notes = models.CharField(max_length=400, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True, blank=True)
updated = models.DateTimeField(auto_now=True, blank=True)
class Meta:
ordering = ["name"]
def __str__(self):
return self.name
class Contact(models.Model):
firstname = models.CharField(max_length=20, null=True, blank=True)
lastname = models.CharField(max_length=20, null=True, blank=True)
email = models.CharField(max_length=40, null=True, blank=True)
phone = models.CharField(max_length=15, null=True, blank=True)
title = models.CharField(max_length=20, null=True, blank=True)
notes = models.CharField(max_length=400, null=True, blank=True)
company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ["lastname"]
def __str__(self):
return self.firstname
views.py
class contact_manager(ListView):
template_name = 'crm/contact_manager.html'
context_object_name = 'contact_manager'
queryset = Contact.objects.all()
def get_context_data(self, **kwargs):
context = super(contact_manager, self).get_context_data(**kwargs)
context['contact'] = Contact.objects.all()
context['company_list'] = Company.objects.all()
# And so on for more models
return context
contact_manager.html
<div class="form-group">
<select class="form-control" name="company" placeholder="Company">
<option value="">Please select a company</option>
{% for Company in company_list %}
<option value="{{Company.name}}">{{Company.name}}</option>
{% endfor %}
</select>
</div>
If you are looking for a unqiue identifier for each option, that links to a model instance on the backend, that is what the ID field is for (Company.id):
<option value="{{ Company.id }}">{{Company.name}}</option>
Then on the backend you can retrieve the model with the posted id:
Company.get(id=posted_id)
Note: id is by default added to your model as the primary key and is a auto incrememting integer.
I've created these two models: "Property" and "Bedroom". I've created a Class Based View, DetailView to show the details from Property, but now I need to show not only the property details but also the bedroom details.
# models.py
class Property(models.Model):
property_reference = models.CharField(db_column='Property_Reference', max_length=10) # Field name made lowercase.
address = models.CharField(db_column='Address', max_length=250, blank=True, null=True) # Field name made lowercase.
post_code = models.CharField(db_column='Post_Code', max_length=15, blank=True, null=True) # Field name made lowercase.
type = models.CharField(db_column='Type', max_length=25, blank=True, null=True, choices=HOUSE_TYPE_CHOICES) # Field name made lowercase.
bedrooms = models.IntegerField(db_column='Bedrooms', blank=True, null=True) # Field name made lowercase.
bathrooms = models.IntegerField(db_column='Bathrooms', blank=True, null=True) # Field name made lowercase.
usual_cleaning_requirements = models.CharField(db_column='Usual_Cleaning_Requirements', max_length=250, blank=True, null=True) # Field name made lowercase.
notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase.
feature_image = models.ImageField(null=True)
class Meta:
db_table = 'Property'
def __str__(self):
return self.property_reference
def get_absolute_url(self):
return reverse("properties:property_detail",kwargs={'pk':self.pk})
class Bedroom(models.Model):
type = models.CharField(db_column='Type', choices=BEDROOM_TYPE_CHOICES, max_length=50)
bed_dimensions = models.CharField(db_column='Bed_Dimension', choices=BED_DIMENSION_CHOICES, max_length=30)
image = models.ImageField(null=True, blank=True)
ensuite = models.BooleanField(default=False)
notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase.
property = models.ForeignKey(Property, null=False, on_delete=models.CASCADE, related_name='bedroom')
And I've created this view:
class PropertyDetailView(DetailView):
template_name = 'properties/property-detail.html'
model = Property
def get_context_data(self,**kwargs):
context = super().get_context_data(**kwargs)
context['bedrooms'] = Bedroom.objects.get(property = property.property_id)
return context
I must be doing something wrong cause I'm still learning, could you please help me?
I solved my question with the help of #Daniel Roseman. It is working now.
I've deleted the get_context_data() on PropertyDetailView
#views.py
class PropertyDetailView(DetailView):
template_name = 'properties/property-detail.html'
model = Property
I've iterated with a for loop on my property-detail.html
# property-details.html
<tbody>
{% for bedroom in property.bedroom.all %}
<tr>
<td>{{ bedroom.type }}</td>
<td>{{ bedroom.bed_dimensions }}</td>
<td><span class="text-muted"> {{ bedroom.ensuite }}</span> </td>
<td>{{ bedroom.notes }}</td>
</tr>
{% endfor %}
</tbody>
I have a boolean field for whether or not an item is active:
is_active = models.BooleanField(default=True)
It seems pretty straightforward, my template will display items that are active:
{% for p in products|dictsortreversed:"id" %}
{% if p.is_active %}
<a href="{{ p.get_absolute_url }}">
{{ p.name }}
</a>
{% endif %}
For some reason all items are returned even if the field is 0 in the database. When I uncheck the boolean field in the django admin, it updates correctly to 0 in the database, but still shows as being checked in the admin...
It seems like django is reading the field as True, regardless of the boolean value.
Model
class Product(models.Model):
name = models.CharField(max_length=255, unique=True)
slug = models.SlugField(max_length=255, unique=True, help_text='Unique value for product page URL, created from name')
price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, default=0.00)
old_price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, default=0.00)
image = models.CharField(max_length=50)
is_active = models.BooleanField(default=True)
quantity = models.IntegerField()
description = models.TextField()
meta_keywords = models.CharField('Meta Keywords', max_length=255, help_text='Comma-delimited set of SEO keywords for meta tag')
meta_description = models.CharField('Meta Description', max_length=255, help_text='Content for description meta tag')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
categories = models.ForeignKey(Category, null=True)
publish_date = models.DateField(blank=True, null=True)
issue_one = models.CharField(blank=True, null=True, max_length=255)
issue_two = models.CharField(blank=True, null=True, max_length=255)
issue_three = models.CharField(blank=True, null=True, max_length=255)
class Meta:
db_table = 'products'
ordering = ['-created_at']
def __unicode__(self):
return self.name
#models.permalink
def get_absolute_url(self):
return ('catalog_product', (), {'product_slug': self.slug})
View:
def index(request, template_name="catalog/index.html"):
""" site home page """
page_title = 'Visible Language Ordering'
return render_to_response(template_name, locals(), context_instance=RequestContext(request))