Search code examples
pythondjangodjango-viewsmodels

Django 1.6: model fields not showing


I'm trying to get a list of all the doctor listings from the Doctor model in one of the templates. But the template is not showing anything. It's not like there is no data in the models, I can see it's populated through the admin panel.

here is the template doclistings.py

{% for doc in doctor.all %}
    <p>{{doc.name}}</p>
    <p>{{doc.specialization}}</p>
    <p>{{doc.clinic}}</p>

{% endfor %}

Here is the views.py

def allDocs(request):
    return render(request, 'meddy1/doclistings.html')

Here is the models.py

class Doctor(models.Model):
    name = models.CharField(max_length=30)
    specialization = models.ForeignKey(Specialization)
    scope = models.CharField(max_length=100, blank = True)
    clinic = models.ForeignKey(Clinic)
    seekers = models.ManyToManyField(DoctorSeeker, through='Review')
    language = models.ManyToManyField(Language)
    education1 = models.CharField(max_length=100)
    education2 = models.CharField(max_length=100, null = True)
    gender_choices = ( ('M', 'Male'), ('F','Female'),)
    gender = models.CharField(max_length=5, choices = gender_choices, null=True)
    profile_pic = models.ImageField(upload_to='meddy1/images/', blank=True)
    statement = models.TextField(null=True)
    affiliation = models.CharField(max_length=100, null = True)

Here is urls.py

url(r'^doclistings/$', views.allDocs, name='allDocs'),

Solution

  • You need to pass the list to template from the view. In your code, the variable doctor is not defined in the template, so it doesn't show anything.

    Change your view to pass doctlist as

    def allDocs(request):
        return render(request, 'meddy1/doclistings.html', {'doclist': Doctor.objects.all()})
    

    Update template to use doclist to show each item.

    {% for doc in doclist %}
        <p>{{doc.name}}</p>
        <p>{{doc.specialization}}</p>
        <p>{{doc.clinic}}</p>
    
    {% endfor %}