-1

i am new to django and i am unable to get to print to the html page.How do you display the information retrieved from the database into a blank html page?

blank.hml

<body>
<h1>Classes Added</h1>
{% for i in classInfo %}
    <h1>{{ i.label }}</h1>
{% endfor %}
</body>

models.py

class EventType(models.Model):
    '''
    Simple ``Event`` classifcation.
    '''
    objects = models.Manager()
    abbr = models.CharField(_('abbreviation'), max_length=4, unique=False)
    label = models.CharField(_('label'), max_length=50)

    class Meta:
        verbose_name = _('event type')
        verbose_name_plural = _('event types')

    def __str__(self):
        return self.label

views.py

def displayClass(TemplateView):
    templateName = 'blank.html'

def get(self,request):
    form = ClassCreationForm() 
    classInfo = EventType.objects.all()
    print(classInfo)

    args = {'form' : form, 'classInfo' : classInfo}
    return render(request,self,templateName,{'form':form})

forms.py

class ClassCreationForm(forms.Form):
classroom = forms.CharField(label = 'Class Name',max_length=50)
fips
  • 4,319
  • 5
  • 26
  • 42
Tahmid
  • 1
  • 1

1 Answers1

0

I think you need to understand how the views.py file works. You should have your business logic included in there and the pass it along to the template to be rendered. It can be passed along by the return feature you have included in your code. Although, in your return feature you are only passing a templatename and the form you wanted to render. There isn't data related to the EventType queryset being passed to your template as it is not included in the return context.

Now, personally I like working with Django Class-Based-generic-Views (CBV), since a lot of the code is included in there for you. I am not sure if you have got to the point of learning these yet but I would check them out.

If you would like to add a form into this, you could do so by adding FormMixin which is part of the generic mixins Django provides.

How I would structure your view.py code using generic views is as follows:

from django.views import generic
from django.views.generic.edit import FormMixin
from YourApp.forms import ClassCreationForm
from YourApp.models import EventType

class DisplayClass(FormMixin,generic.ListView):
    template_name = 'blank.html'
    form_class = ClassCreationForm

    def get_queryset(self, *args, **kwargs):
        return EventType.objects.all()

If you decide to use class based views you will need to add additional criteria to your urls.py file (the .as_view()):

from django.urls import path
from . import views

urlpatterns = [
    path('yoururlpath/', views.DisplayClass.as_view()),
]

Then in your template:

{% for i in object_list %}
    <h1>{{ i.label }}</h1>
{% endfor %}

rendering your form...

{{ form.as_p }}
HoneyNutIchiros
  • 541
  • 3
  • 9