Home > Software engineering >  Django html display from model
Django html display from model

Time:05-16

I need on my html page to display data from Profesor and Ucenik model: ime, prezime, jmbg.

{{profesor.ime}}
{{profesor.prezime}}
{{ucenik.ime}}
{{ucenik.prezime}}
{{ucenik.jmbg}}

my profile page id dynamic, need to display profesor data or if ucenik to display ucenik data

what i need to add on my views.py

models.py

class Profesor(models.Model):
   user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
   ime = models.CharField(max_length=200, null=True)
   prezime = models.CharField(max_length=200, null=True)
 
class Ucenik(models.Model):
   user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
   ime = models.CharField(max_length=200, null=True)
   prezime = models.CharField(max_length=200, null=True)
   jmbg = models.IntegerField(null=True)

urls.py

path('profesor/', views.profesor, name='profesor'),
path('ucenik/', views.ucenik, name='ucenik'),
path('posetioc/', views.posetioc, name='posetioc'),
path('profil/<str:pk>/', views.profil, name='profil'), ]

views.py

def profesor(request):

   return render(request, 'pocetna_profesor.html')


def ucenik(request):

   return render(request, 'pocetna_ucenik.html')


def profil(request, pk):

   return render(request, 'profil.html')

HTML:

{% extends 'base.html' %}
<title>profesor</title>

{% block content %}

<body>
{% include 'navbar.html' %}
   <h1>Ime:</h1>
   {{profesor.ime}}
</body>

{% endblock %}

CodePudding user response:

You need to add a Professor and Ucenik instance to your view context.

context = {
    'professor': Professor.objects.get(),
    'ucenik': Ucenik.objects.get()
}
return render(request, context, 'url.html')

CodePudding user response:

You can make your profile view dynamic by introducing an extra parameter which defines your role (i.e, Professor/Ucenik)

/profil/profesor/2/ for profesor /profil/ucenik/1 for ucenik

from django.urls import path

urlpatterns=[
    path('profil/<str:role>/<int:pk>/', views.profil, name='profil'),
]
# views.py
from .models import Profesor,Ucenik # import your model
def profil(request,role,pk):
    context = {}
    context['role'] = type 
    if type=="profesor":
        context['person'] = Profesor.objects.get(id=pk)
    else:
        context['person'] = Ucenik.objects.get(id=pk)
    return render(request, 'profil.html',context)
<!-- profil.html -->
{% extends 'base.html' %}
<title>{{role}}</title>

{% block content %}

<body>
{% include 'navbar.html' %}

   <h1>Ime:</h1>
   {{person.ime}}
</body>

{% endblock %}

  • Related