i'm try to display foreign key value , but it instead return the id , in template
models.py
class Product(models.Model):
product_name = models.CharField(unique=True, max_length=50)
pass
def __str__(self):
return self.product_name
class Order(models.Model):
id = models.AutoField(primary_key = True)
products = models.ManyToManyField(Product ,through='ProductOrder')
pass
def __str__(self):
return str(self.products.all())
class ProductOrder(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
ordering = models.ForeignKey(Order,
on_delete=models.CASCADE,blank=True,null=True)
pass
def __str__(self):
return str(self.product)
this is my views.py
class ListOfOrder(ListView):
template_name = 'order/product_group.html'
context_object_name = 'productss'
def get_queryset(self):
return ProductOrder.objects.all()
template.html
{% for product in productss %}
<tr class="">
<td style="text-align: center;">{{ product.product }}</td>
{% endfor %}
i expected to display the product name but it instead displayed the ID of the product
thanks for your answer
Related
I am working a Supplier Management System. I need to make a particular type of query which I am having issue implementing. I have the user models, and then the user_type which is of two types the suppliers and the admin. Of Course, the filter I need to implement is based of the supplier because only the supplier is able to create product in which they have to specify what categories as well.
My Problem: How can I get all categories a supplier products belongs to.
My Problem Edit: How can get each suppliers products and pass into the templates on the <td> tag
models.py
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=254, unique=True)
def get_email(self):
return self.email
class user_type(models.Model):
is_admin = models.BooleanField(default=False)
is_supplier = models.BooleanField(default=False)
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
if self.is_supplier == True:
return User.get_email(self.user) + " - is_supplier"
else:
return User.get_email(self.user) + " - is_admin"
#property
def get_categories(self):
return Category.objects.filter(product__user=self.id).distinct()
class Category(models.Model):
name = models.CharField(max_length=256)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=36)
price = models.PositiveIntegerField()
category = models.ForeignKey(Category, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.name
views.py
def Viewsupplier(request):
title = "All Suppliers"
suppliers = User.objects.filter(user_type__is_supplier=True)
categories = Category.objects.filter(product__user='2').distinct()
context = {"suppliers":suppliers, "title":title, "categories":categories}
return render(request, 'core/view-suppliers.html', context)
view-suppliers.html
<table class="table table-borderless table-data3">
<thead>
<tr>
<th>No</th>
<th>Email</th>
<th>Telephone</th>
<th>Category(s)</th>
<th>Country</th>
</tr>
</thead>
<tbody>
{% for supplier in suppliers %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{supplier.email}}</td>
<td>{{supplier.telephone}}</td>
<td>{{supplier.get_categories}}</td>
<td>{{supplier.country}}</td>
</tr>
{% empty %}
<tr><td class="text-center p-5" colspan="7"><h4>No supplier available</h4></td></tr>
{% endfor %}
</tbody>
</table>
You can filter with:
Category.objects.filter(product__user=myuser).distinct()
where myuser is the user you want to filter on.
The .distinct(…) [Django-doc] will prevent returning the same Category that many times as there are Products for that user.
In my model I have a ManyToManyField to select related products. I'm wondering what would be the best way to bring these into my view and render them in my template.
models.py
class Product(models.Model):
title = models.CharField(max_length=80)
category = models.ManyToManyField(ProductCategory)
featured_image = models.ImageField(upload_to=image_dir)
about_this_product = models.TextField()
standard_features = models.TextField(null=True)
featured = models.BooleanField(default=False)
related_models = models.ManyToManyField("self", blank=True, null=True)
model_slug = AutoSlugField(null=True, default=None,
unique=True, populate_from='title')
class Meta:
verbose_name_plural = "Products"
def __str__(self):
return self.title
views.py
def model_detail_view(request, category_slug, model_slug):
product_model = get_object_or_404(Product, model_slug=model_slug)
context = {
"title": "Products | %s" % product_model.title,
"product": product_model,
}
return render(request=request, template_name='main/product_model_detail.html', context=context)
You can use .prefetch_related(..) just like you do on any one-to-many relation in the view:
def my_view(request):
products = Product.objects.prefetch_related('related_models')
return render(request, 'some_template.html', {'products': products})
Then in the template, you can iterate over the .related_models collection:
{% for product in products %}
{{ product.title }}
related:
{% for rel in product.related_models.all %}
{{ rel.title }}
{% endfor %}
{% endfor %}
I have three tables user, Profile and booking. Profile and booking table have foreign key with user table. Profile and Booking table are not directly linked. In BookingList view i want to access the profile data is it possible if yes how i can i do this.
models.py
class Profile(models.Model):
uid = models.UUIDField(unique=True, editable=False, default=uuid.uuid4)
name = models.CharField(max_length=100, unique=True)
contact_person = models.CharField(max_length=100)
mobile = models.CharField(max_length=15)
email = models.CharField(max_length=40)
created_by = models.ForeignKey(User, on_delete=models.PROTECT)
profile_status = models.BooleanField(default=False)
def __str__(self):
return self.name
class Booking(models.Model):
port_of_loading = models.ForeignKey(LoadPort, on_delete=models.PROTECT)
port_of_discharge = models.ForeignKey(DestinationPort, on_delete=models.PROTECT)
equipment_type = models.CharField(max_length=10, choices=CONT_TYP)
quantity = models.IntegerField()
pick_up_date = models.DateField(null=True, blank=True)
hand_over_date = models.DateField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
created_by = models.ForeignKey(User, on_delete=models.PROTECT)
def __str__(self):
return self.port_of_loading
views.py
class BookingList(LoginRequiredMixin, ListView):
model = Booking
template_name = 'documentation/details_booking.html'
context_object_name = 'all_bk'
def get_queryset(self):
queryset = super(BookingList, self).get_queryset().order_by('-pk')
return queryset
In template i want to access the profile.name
{% for item in all_bk %}
<tr>
<td>{{ item.created_by.profile.name }}</td>
</tr>
{% endfor %}
There can be multiple profiles created by a user so you will have to loop over them
{% for item in all_bk %}
{% for profile in item.created_by.profile_set.all %}
{{ profile.name }}
{% endfor %}
{% endfor %}
My model has a foreignkey:
class Status(models.Model):
status_code = models.CharField(max_length=10, verbose_name="Status Code")
description = models.CharField(max_length=256, verbose_name="Description")
def __unicode__(self):
return "%s - %s" % (self.status_code, self.description)
def __str__(self):
return "%s - %s" % (self.status_code, self.description)
class PickUp(models.Model):
name = models.CharField(max_length=60, verbose_name="Name")
status = models.ForeignKey(Status, verbose_name="Status", default=None, blank=True, null=True)
deleted = models.BooleanField(default=False)
def __unicode__(self):
return self.name
This is my (abbreviated) view:
def index(request):
context = dict()
PickupFormSet = modelformset_factory(PickUp, fields='__all__', form=PickupForm)
qs = PickUp.objects.filter(deleted=False).prefetch_related('status')
context['pickupformset'] = PickupFormSet(queryset=qs)
return render(request, "index.html", context)
This is part of the template:
{% for pickup in pickupformset %}
{% if pickup.id.value %}
<tr>
<td>{{ pickup.id }}{{pickup.deleted}}</td>
<td>{{pickup.name}}{{pickup.name.value}}</td>
<td>{{pickup.status}}</td>
</tr>
{% endif %}
{% endfor %}
Each record displayed triggers a database query to get the status description.
SELECT `frontend_status`.`id`, `frontend_status`.`status_code`, `frontend_status`.`description` FROM `frontend_status`
Do you know why or how I can prevent this?
i want to get the images form the image model in the template.
class Products(models.Model):
category = models.ForeignKey(Category)
name= models.CharField(max_length=120, unique=True)
slug = models.SlugField(unique = True)
price = models.IntegerField(default=100)
class Image(models.Model):
property = models.ForeignKey(Products, related_name='images')
image = models.ImageField(upload_to='static/images/home',blank=True,null=True)
views.py
def index(request):
queryset = Products.objects.all()
return render_to_response('site/index.html',
locals(),
context_instance=RequestContext(request))
{% for query in queryset %}
<img src='/ {{ query.????? }} ' alt="" width = 'auto' height='340'/>
{% endfor %}
i want to get the images which is connected to that product
i have readed that link
i have tried:
{% for query in queryset %}
<img src='/ {{ query.images_all.0.image }} ' alt="" width = 'auto' height='340'/>
{% endfor %}
but no success ..
just try to understand the model that how i get the image url from models which related with foreignkey relationship.
my models:
class Product(models.Model):
title = models.CharField(max_length = 400)
slug = models.SlugField(max_length = 400,unique=True,null=True,blank=True)
is_popular = models.BooleanField(default=True)
category = models.ForeignKey(Category,on_delete=models.CASCADE)
subcategory = models.ForeignKey(Subcategory,on_delete=models.CASCADE,null=True,blank=True)
childcategory = models.ForeignKey(Childcategory,on_delete=models.CASCADE,null=True,blank=True)
brand = models.ForeignKey(Brand,on_delete=models.CASCADE,null=True,blank=True)
description = models.TextField()
is_active = models.IntegerField(choices=STATUS_CHOICES)
created_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = unique_slug_generator(self)
super(Product, self).save(*args, **kwargs)
def show_image(self):
return self.productmeaserment_set.first().first_image()
class ProductMeaserment(models.Model):
product = models.ForeignKey(Product,on_delete=models.CASCADE)
measerment = models.ForeignKey(Measerment,on_delete=models.CASCADE,null=True,blank=True)
selling_price = models.DecimalField(max_digits=20,decimal_places=2)
offer_price = models.DecimalField(max_digits=20,decimal_places=2)
available_quantity = models.IntegerField();
is_active = models.IntegerField(choices=STATUS_CHOICES)
created_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.measerment.name
def first_image(self):
return self.productmeasermentimage_set.first()
class ProductMeasermentImage(models.Model):
productmeaserment = models.ForeignKey(ProductMeaserment,on_delete=models.CASCADE)
image = models.FileField(upload_to='uploads/products')
is_active = models.IntegerField(choices=STATUS_CHOICES)
created_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.productmeaserment.product.title
views.py
from products.models import Product
def adminpanel(request):
products=Product.objects.all()
return render(request,'adminpanel/index.html',{'productsall':products})
templates/adminpanel/index.html
{% for item in productsall %}
<tr>
<div class="border1">
<td class="image-cell">
<img src="{{item.show_image.image.url}}"> #this is how i got image url.
</td>
</div>
<td data-label="title">{{item.title}}</td>
<td data-label="category">{{item.category}}</td>
<td data-label="subcategory">{{item.subcategory}}</td>
<td data-label="brand">
{{item.brand}}
</td>
<td data-label="description">
{{item.description}}
</td>
<td class="created">
{{item.created_date}}
</td>
</tr>
<tr>
{% endfor %}
There is so much wrong with your code, I suggest that you do the Django Tutorial first.
https://docs.djangoproject.com/en/1.8/intro/tutorial01/
But if you wan't it working, here is how:
models.py
class Product(models.Model):
category = models.ForeignKey(Category)
name= models.CharField(max_length=120, unique=True)
slug = models.SlugField(unique = True)
price = models.IntegerField(default=100)
def first_image(self):
# code to determine which image to show. The First in this case.
return self.images[0]
class ProductImage(models.Model):
image = models.ImageField(upload_to='static/images/home',blank=True,null=True)
product = models.ForeignKey(Product, related_name='images')
views.py
def index(request):
queryset = Products.objects.all()
return render_to_response('site/index.html', {'products': queryset})
index.html
{% for product in products %}
<img src="{{ product.first_image.src }}" alt="" width="auto" height="340"/>
{% endfor %}