Printing model fields organized by category

25 views
Skip to first unread message

Jay

unread,
Aug 27, 2018, 1:41:31 PM8/27/18
to Django users
I have a Class called "Model" that has a field called "model_numbers". I have another class called "Category" that has a field called "category". In the Model Class, I have a field called category that is a Foreign Key to the field category in the Class category.

Screen Shot 2018-08-27 at 8.58.54 AM.png


Also, here is the html that prints the modeul_number and category fields:

Screen Shot 2018-08-27 at 9.01.10 AM.png



What the code is printing:

CATEGORY 1:
 - Field 1
 - Field 2
 - Field 3 

CATEGORY 2:
 - Field 1
 - Field 2
 - Field 3

What I want it to print is:

CATEGORY 1:
 - Field 1
 - Field 2

CATEGORY 2:
- Field 3

In this way it prints out all the model numbers under their respective category name (instead of all model numbers under every category, which is not correct as each model number only has one category). 


Thank you!

Matthew Pava

unread,
Aug 27, 2018, 1:52:56 PM8/27/18
to django...@googlegroups.com

Hi Jay,

Firstly, I would avoid calling a model “Model.”  Maybe “Product” would be better?  It’s only because of Django’s models.Model class.  That will likely cause confusion in the future for you.

 

You’ll want to work with the Category model primarily and use a reverse lookup to get to the corresponding “Model” instead of working with a model_list.  The reverse lookup of category to model is model_set by default.  You can change the name if you want.

 

{% for category in category_list %}

      <strong>{{ category }}</strong>

      <ul>

      {% for model in category.model_set %}

            <li><a href="{{ model.get_absolute_url }}">{{ model }}</a></li>

      {% endfor %}

      </ul>

{% empty %}

      <p>There is no equipment in the database with a category.</p>

{% endfor %}

 

 

Check out https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_one/

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/098cc4aa-374a-4e9a-9da1-ee49bab591aa%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Jay

unread,
Aug 27, 2018, 2:20:19 PM8/27/18
to Django users
Thanks for the suggestions, I will change the name from Model after I can get this working. 

So, I've changed the code using your help to:

  {% if category_list %}
    {% for category in category_list %}
        <li><strong>{{ category }}</strong></li>
          <ul>
            {% for model in category.model_set %}
              <li>
              <a href="{{ model.get_absolute_url }}"> {{ model.model_number }}..........{{ model.description }} </a>
              </li>
            {% endfor %}
          </ul>
    {% endfor %}
  {% else %}
        <p>There is no equipment in the database</p>
  {% endif %}

{% endblock %}

However, this just prints "There is no equipment in the database". Am I missing something? I will try to experiment a little more. 

To post to this group, send email to djang...@googlegroups.com.

Matthew Pava

unread,
Aug 27, 2018, 3:00:57 PM8/27/18
to django...@googlegroups.com

We need to see your view code.  I’m assuming now that you don’t have category_list in your context variable that you submitted to the template.

To post to this group, send email to django...@googlegroups.com.

Jay

unread,
Aug 27, 2018, 3:28:28 PM8/27/18
to Django users
Thanks Matthew, here is my views.py file:


from django.shortcuts import render #generates HTML fiels using a template and data
#from django.http import HttpResponse
from .models import Book, Author, BookInstance, Genre, Model, ModelInstance, Category, Ownership, Manufacturer, Location #imports model classes to access data in views
from django.views import generic

# Create your views here.

#def index(request):
#    return HttpResponse("Hey")

def index(request):
    """View function for home page of site."""

    #Generate counts of some of the main objects
    num_books = Book.objects.all().count()
    num_instances = BookInstance.objects.all().count()

    #Available books (status - 'a')
    num_instances_available = BookInstance.objects.filter(status__exact='a').count()

    #The 'all()' is implied by default.
    num_authors = Author.objects.count()

    #Num visits to this view, as counted in the session variable
    num_visits = request.session.get('num_visits', 0)
    request.session['num_visits'] = num_visits + 1


    context = {
        'num_books': num_books,
        'num_instances': num_instances,
        'num_instances_available': num_instances_available,
        'num_authors': num_authors,
        'num_visits': num_visits,
    }

    #Render the HTML template index.html with the data in the context variable
    return render(request, 'index.html', context=context)

class BookListView(generic.ListView):
    model = Book

class BookDetailView(generic.DetailView):
    model = Book

class ModelListView(generic.ListView):
    model = Model

class ModelDetailView(generic.DetailView):
    model = Model

class CategoryListView(generic.ListView):
    model = Category

class CategoryDetailView(generic.DetailView):
    model = Category

from django.contrib.auth.mixins import LoginRequiredMixin

class LoanedBooksByUserListView(LoginRequiredMixin,generic.ListView):
    """Generic class-based view listing books on loan to current user."""
    model = BookInstance
    template_name ='catalog/bookinstance_list_borrowed_user.html'
    paginate_by = 10

    def get_queryset(self):
        return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back')

Matthew Pava

unread,
Aug 27, 2018, 3:33:14 PM8/27/18
to django...@googlegroups.com

Okay, your URL should point to your CategoryListView.  That should have category_list in its context.  And the template should in the category_list template.

To post to this group, send email to django...@googlegroups.com.

Jay

unread,
Aug 27, 2018, 4:04:56 PM8/27/18
to Django users
Hmm, I'm getting an error:

Screen Shot 2018-08-27 at 11.58.32 AM.png








I've changed my urls.py to this:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('books/', views.BookListView.as_view(), name='books'),
    path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'),
    path('category/', views.CategoryListView.as_view(), name='categories'),

Matthew Pava

unread,
Aug 27, 2018, 4:16:09 PM8/27/18
to django...@googlegroups.com

Oh, yes.  I do it all the time myself.

 

You need to change

 

category.model_set

 

to

 

category.model_set.all

 

model_set is the manager.  You need to treat it like any other manager.

To post to this group, send email to django...@googlegroups.com.

Message has been deleted

Jay

unread,
Aug 27, 2018, 4:51:53 PM8/27/18
to Django users
Thank you so much! That worked!!
Reply all
Reply to author
Forward
0 new messages