pythondjangodjango-viewsdjango-templates

Show product name in template django


I want to show all of the user orders in its panel so, I have following models: this is my product model in django and in my order model I have productfk field that is id of user product.

class Product(models.Model):
    id= models.IntegerField(primary_key=True)
    activedate = models.DateField()
    name= models.CharField(max_length=256)
    description = models.TextField()
    
    #following u can set user owner for this row
    #owner =models.ForeignKey(to=User,on_delete=models.CASCADE)
    category = models.CharField(max_length=256)
    unit =models.CharField(max_length=50)
    active = models.BooleanField(default=False)
    
    unitprice = models.DecimalField(max_digits=18, decimal_places=0)
    quantity = models.FloatField()
    minorder = models.FloatField()
    maxorder = models.FloatField()
    readytopay = models.BooleanField(default=False)
    showquantity = models.BooleanField(default=False)
    lastupdate = models.DateField()
    def __str__(self):
        return self.name

and folloring is my order model:

class Orders(models.Model):
    id = models.IntegerField(primary_key=True)
    customerfk = models.ForeignKey(to=User,on_delete=models.CASCADE)
    oxygenid = models.IntegerField()
    financialfk = models.IntegerField()
    orderdate = models.DateTimeField()
    productfk = models.IntegerField()
    unit = models.CharField(max_length=50)
    quantity = models.FloatField()
    unitprice = models.DecimalField(max_digits=18, decimal_places=0)
    discount = models.DecimalField(max_digits=18, decimal_places=0)
    totalprice = models.DecimalField(max_digits=18, decimal_places=0)
    onlinepayment = models.DecimalField(max_digits=18, decimal_places=0)
    customerdesc = models.TextField()
    companydesc = models.TextField()
    userip = models.CharField(max_length=20)
    status = models.CharField(max_length=50)
    creationdate = models.DateTimeField()
    
    def __str__(self):
        return self.status

and this is my order view

@login_required(login_url='/authentication/login')
def index(request):
    unit=Unit.objects.all()
    orderstatus=OrderStatus.objects.all()
    #order=Orders.objects.all()
    order =Orders.objects.select_related('customerfk')
    paginator = Paginator(order,20)
    page_number = request.GET.get('page')
    page_obj = Paginator.get_page(paginator,page_number)
    #currency = UserPreference.objects.get(user=request.user).currency
    context={
        'order':order,
        'orderstatus':orderstatus,
        'unit':unit,
        'page_obj':page_obj
    }
    return render(request,'orders/index.html',context)

how i can show my product name in template view for each order


Solution

  • There should be a product relation in the orders table, e.g., a foreign key. After that, you can access the product name in the Django template while looping through orders with the syntax.

    {{ orderItem.product.name }}.