简体   繁体   中英

Django view only returning primary key from field to template, no data

I have a model which has a column categories in a Product table, which has one entry, 'beds'.

When I try to get a list of categories, or products (all of which have names, descriptions, etc), the only thing I can get returned is numbers.

This is the relevant view from my views.py

def product(request):
    template = loader.get_template('/home/user/webapps/webapp/my_site/main_page/templates/main_page/product.html')
    prods = xroduct.objects.values_list('product')
    context={'prods': prods}
    return HttpResponse(template.render(context))

This is my code within a django template to display data

{% for instance in prods %}
    <li>{{ instance }}</li>
{% endfor %}

However, all that gets returned, going by HTML when viewing the webpage, is:

<li>(2,)</li>
<li>(1,)</li>

There should be a lot more information returned. Names, descriptions, etc. Why is this not being returned via my view?

edit: How xroduct is defined:

from oscar.core.loading import get_class, get_model

xroduct = get_model('catalogue', 'product')

Since we are talking about django-oscar there are number of things to understand:

To retrieve the models from oscar you need to use get_model which is their own implementation of dynamically importing the models of interest. get_model fetched the models from https://github.com/django-oscar/django-oscar/blob/master/src/oscar/apps/catalogue/models.py whic are defined by https://github.com/django-oscar/django-oscar/blob/master/src/oscar/apps/catalogue/abstract_models.py

What you need to do if you want to list products and their information is the following:

from oscar.core.loading import get_model

Product = get_model("catalogue", "Product")

def list_products(request):
    template = loader.get_template(...)
    products = Product.objects.all()
    context = {"products": products}
    return HttpResponse(template.render(context))

And in the template you can simply access the instances like:

{% for instance in prods %}
    <li>{{ instance.title }}</li>
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM