Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to construct nested QuerySet with django ORM?
How can construct the JSON format I expect with just QuerySet? Use Prefetch or Subquery? Only use QuerySet, I don't want change JSONField or serializer. models: class Product(models.Model): name = models.CharField(max_length=128, ) product_attr = models.ManyToManyField("ProductAttr", through="ProductBindAttr", ) class ProductAttr(models.Model): attr_name = models.CharField(max_length=128, unique=True, ) class ProductBindAttr(models.Model): class Meta: UniqueConstraint("product", "attr_key", "attr_value", name='unique_bind_attr') product = models.ForeignKey("Product", on_delete=models.CASCADE, ) attr_key = models.ForeignKey("ProductAttr", on_delete=models.CASCADE, ) attr_value = models.CharField(max_length=128, ) serializers: class ProductBindAttrNestedSerializer(serializers.ModelSerializer): class Meta: model = ProductBindAttr fields = ('attr_value', 'product') product = serializers.StringRelatedField() class ProductGroupByBindAttrSerializer(serializers.ModelSerializer): class Meta: model = ProductAttr fields = ("attr_name", "attr_values") attr_values = ProductBindAttrNestedSerializer(many=True, source="productbindattr_set") views: class ProductGroupByBindAttrViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = ProductAttr.objects.all() # how can I just change `queryset` to do that? serializer_class = ProductGroupByBindAttrSerializer json: [ { "attr_name": "Height", "attr_values": [ { "attr_value": "13 cm", "products": { "name": "G304" } }, { "attr_value": "13 cm", "products": { "name": "G305" } }, { "attr_value": "14 cm", "products": { "name": "G306" } } ] } ] The result I expect: [ { "attr_name": "Height", "attr_values": [ { "attr_value": "13 cm", "products": { "name": "G304", "name": "G305", // I want to merge products which same `attr_value` } }, { "attr_value": "14 cm", "products": { "name": "G306" } } ] } ] -
Cannot use None as a query value error when i try to view page without search query
I have a working search form in my base.html but when itry to access the listing page without passing a search query i get a "Cannot use None as a query value" error. views.py def listing(request): if request.method == 'GET': search = request.GET.get('search') propertys = Paginator(Property.objects.filter(property_name__icontains =search).order_by('-listed_on'), 2) page = request.GET.get('page') propertys = propertys.get_page(page) nums = "p" * propertys.paginator.num_pages return render(request,"listing.html",{"propertys":propertys, "nums": nums, 'search':search}) else: p = Paginator(Property.objects.order_by('-listed_on'), 2) page = request.GET.get('page') propertys = p.get_page(page) nums = "p" * propertys.paginator.num_pages return render(request,"listing.html", {"propertys":propertys, "nums": nums}) -
Object of type Modul is not JSON serializable while trying to set the value of another model in the session
i am trying to save the id of a created model in the session so i can update it later in anothe page, but the set function shows me an error i am using request.session['ORDER'] = serializers.serialize('json', Order.objects.all()) right now but i also used request.session['ORDER'] = order.id, i got the same error if form.is_valid(): if(form.cleaned_data['paymentmethod'] == "PayPal"): print("Paypal choosed") first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] address = form.cleaned_data['address'] zipcode = form.cleaned_data['zipcode'] place = form.cleaned_data['place'] paymentmethod = 'pypnt' order = checkout(request, first_name, last_name, email, address, zipcode, place, phone, cart.get_total_cost(), paymentmethod) print(order.id) print(order) request.session['ORDER'] = serializers.serialize('json', Order.objects.all()) return redirect('cart:process') this is the Order Model lass Order(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.CharField(max_length=100) address = models.CharField(max_length=100) zipcode = models.CharField(max_length=100) place = models.CharField(max_length=100) phone = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) paid_amount = models.DecimalField(max_digits=8, decimal_places=2) vendors = models.ManyToManyField(Vendor, related_name='orders') id = models.AutoField(primary_key=True) class paymentmethod(models.TextChoices): the error: Internal Server Error: /de/cart/ raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Product is not JSON serializable -
class FormularioAlumno(forms.ModelsForm): AttributeError: module 'django.forms' has no attribute 'ModelsForm'
Estoy realizado el proyecto de una pagina web y al momento de correr el programa me sale ese error y no he podido solucionarlo agradecería mucho una pronta solución, ahí adjunte los codigos que me sacan el error del modulo gracias from django.urls import path from Models.Alumno.views import FormularioAlumnoView from Views.HomeView import HomeView urlpatterns = [ #path('admin/', admin.site.urls), path('', HomeView.home, name='home'), path('pagina/', HomeView.pagina1, name='pagina1'), path('pagina2/<int:parametro1>', HomeView.pagina2, name='pagina2'), path('pagina3/<int:parametro1>/<int:parametro2>', HomeView.pagina3, name='pagina3'), path('formulario/', HomeView.formulario, name='formularioprueba'), path('registrarAlumno/', FormularioAlumnoView.index, name='registrarAlumno'), path('guardarAlumno/', FormularioAlumnoView.procesar_formulario(), name='guardarAlumno') ] from django.http import HttpResponse from django.shortcuts import render from Models.Alumno.forms import FormularioAlumno class FormularioAlumnoView(HttpResponse): def index(request): alumno = FormularioAlumno return render(request, 'AlumnoIndex.html', {'form': alumno}) def procesar_formulario(request): alumno = FormularioAlumno if alumno.is_valid(): alumno.save() alumno = FormularioAlumno return render(request, 'AlumnoIndex.html', {'form': alumno, 'mensaje': 'ok'}) from django import forms from Models.Alumno.models import Alumno class FormularioAlumno(forms.ModelsForm): class Meta: model = Alumno fields = '__all__' widgets = {'fecha_nacimiento': forms.DateInput(attrs={'type': 'date'})} -
get sum based on another field django
I have these models: status_choices = ['not received', 'received'] class Investment(Model): # Offering offering = models.ForeignKey(Offering, blank=False, null=False, on_delete=models.CASCADE) invested = models.DecimalField(max_digits=9, default=0, decimal_places=2, blank=True, null=True) status = models.CharField(max_length=200, choices=status_choices, blank=True, null=True, default='not received') class Offering(Model): ... I want to make a property to display the sum of all investments inside the Offering model. I did so like this: @property def amount_invested(self): return Investment.objects.filter(offering_id=self.id).aggregate(Sum('invested'))['invested__sum'] or 0 But, I also want to display the amount_invested iff the status inside the Investment model is 'received'. May I know how I should be able to do this? -
Django project to display multiple styles, one at a time
I have a project in Django. One of the pages uses a ui selector, that is to say, clicking a button changes the style displayed. The button is implemented using javascript. It is done such that there are two divs both initially hidden: <div class="c2" style="display: none"> content </div> <div class="c3" style="display: none"> content </div> The code within those divs uses Django commands to iterate over the same stuff. However, switiching to the second style (I tested putting each div first and it is always the second div) displays a page without all the data that is iterated over again. How does one fix that? -
Difference between User models
I'm learning django now, watch tutorials. The questions is: What is the difference between using: from django.contrib.auth import get_user_model User = get_user_model() User = get_user_model() and from django.contrib.auth.models import User I've seen both of them and both of them used in model with ForeignKey, but I don't know the difference between these two model, for example: author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='posts' ) title = models.CharField(max_length=100) text = models.TextField()``` -
Django rest framework datatables foreign key data could not be obtained
My problem here is when i add a foreign key to my table i face issues like not getting value and not filtering the table below i share the models and serializers. class Foo(models.Model): name = models.CharField(max_length=77, unique=True) phone = models.CharField(max_length=40, null=True, blank=True) email = models.CharField(max_length=80, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.name}" class Process(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE) class ProcessSerializer(serializers.ModelSerializer): class Meta: model = Process fields = '__all__' <th data-data="foo.name" data-name="foo.name">Kisi</th> I am adding a foreign key to my model then utilize djangorestframework-datatables package i can not get the name attribute i just get an id like "1" for the foreign key and after adding .name to the foo model in data-data i could not get any value. I get the following error DataTables warning: table id=processes - Requested unknown parameter 'foo.name' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4 I don't see any problem in the code any help is appreciated. -
How do I solve - column libman_llrguides.id does not exist
I have a model in my django app as shown below... class LLRGuides(models.Model): title = models.CharField(max_length=40) heading = models.CharField(max_length=60) body = models.TextField(default='Type the description of the guide here') I manually created the table in my databse thro' the pg_admin, manually added the columns. The problem comes in when I try to create an instance of the model, it complains of id column not being present. null value in column "id" of relation "libman_llrguides" violates not-null constraint DETAIL: Failing row contains (d, d, Type the description of the guide here, null). This is the sql that created the id field in the pg_Admin ALTER TABLE IF EXISTS public.libman_llrguides ADD COLUMN id integer NOT NULL; -
Generate file from Base64 encoded django file read
During a file upload, i decided to read the file and save as base64 until s3 becomes available to our team. I use the code below to convert the file to bs64. def upload_file_handler(file): """file -> uploaded bytestream from django""" bs4 = base64.b64encode(file.read()) return {'binary': bs4, 'name': file.name} I store the binary derived from the above in a str to a db. Now the challenge is getting the file back and uploading to s3. I attempted to run bs64.decode on the file string from the db and write to a file. But when i open the file, it seems broken, I've attempted with breakthrough. q = Report.objects.first() data = q.report_binary f = base64.b64decode(data) content_file = ContentFile(f, name="hello.docx") instance = TemporaryFile(image=content_file) instance.save() This is one of the files i am trying to recreate from the binary. https://gist.github.com/saviour123/38300b3ff2c7a0d1a01c15332c583e20 How can i generate the file from the base64 binary? -
Python, Heroku: Why isn't the file hosted?
So, I was building a Django app, I created an intro field for a post formular, I did that in my models.py file: class Post(models.Model): title = models.CharField(max_length=100) intro = models.CharField(max_length=1024) content = models.TextField() pub_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('donut-post-detail', kwargs={'pk': self.pk}) I renamed 'description' into 'intro' so, when I did the makemigrations command it maked me a file named: 0002_rename_description_post_intro.py I deleted this file and the inital migration for recreating one, hosted it on heroku and did the python manage.py migrate command but it told me that there was no migrations to apply: I don't understand why. When I go back to the website it shows me this: -
Creating a simple password protected Django app to display Folders/Text Files
I would like to ask this question before I start going down unnecessary rabbit holes. What I want to achieve: Create a simple Django Application that only shows a login form when opening the url. After login (no user registration required, I just want to use it for myself), I want to be able to access my files. Files/Folders: I need to look at a ton of data coming from reconaissance from Bug Bounty Programs. So there are a lot of text files and folders. What would be a good way to display them with Django? Think: -ProjectFolder -Subfolder1 -file1.txt -Subfolder2 -SubSubFolder2 -file1.txt -Subfolder3 Would be great if I could get some pointers on an easy way on how to acheive this! :) -
returning user instead of True or False in Django Permission class
I have a custom permission class which I am importing in one of the views. In that permission class, I am using return user instead of True or False. But it seems to be working. But I dont really understand why. The class is as follows: class ExamplePermission(BasePermission): def has_permission(self, request, view): user = CustomUser.objects.filter(user=request.user).first() if view.action == 'list': return user elif request.method == 'POST' or 'PATCH' or view.action == 'destroy' or 'update': return user and user.user_type == ADMIN else: return False Here in above permission class , I am returning user in some places instead of boolean true or false. What is the meaning of returning user? How it is still working?? -
return empty form django
i have a form fill for register but when i try to save it it involves a none object. the problem is : The view pages.views.essai didn't return an HttpResponse object. It returned None instead. here is my code : views.py from django.shortcuts import redirect, render from django.template import RequestContext from .models import Login def essai(request): if not request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') data = Login(username,password) print(data) return render(request,'pages/essai.html') urls.py from django.urls import URLPattern, path from . import views urlpatterns = [ path('essai', views.essai, name = 'essai'), ] essai.html <form action="" method ="POST" > {% csrf_token %} <input type="text" name="username"> <input type="password" name="password"> <input type="submit" value ="Save"> </form> admin.py from django.contrib import admin from .models import Login admin.site.register(Login) model.py from django.db import models class Login(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=100) PS : I tried with the forms but it's the same problem. I do not understand where is the problem is it the views or the model -
django model based forms - why isn't form valid?
I'm trying to make model based form but something went wrong. model: class Topic(models.Model): name = models.CharField(max_length=200) icon = models.ImageField(upload_to = 'images/') form: class TopicCreationForm(ModelForm): class Meta: model = Topic fields = '__all__' view: def TopicCreateView(request): form = TopicCreationForm() if request.method == 'POST': form = TopicCreationForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: print('aaa') # It displays in console context = {'form':form} return render(request, 'blog/topic_form.html', context) where did i make mistake ? -
How to cache QuerySet in Django
I am starting with my web application in Django. I tried to do some optimilization and loaak at queries and loading time. I did some refactor with select_related or prefetch_related, but I get stacked. I have some structured ratings according to object which is assigned to. I need on every level in structure (Employee, Team, Company..) do some calculations with ratings data. I have created class method in every model and filtered relevant ratings according to object which it belongs to. def get_ratings(self): employee_projects = EmployeeManagement.objects.filter(employee=self) feedbacks = Feedback.objects.filter(rate_for__in=employee_projects) ratings = Rating.objects.filter(feedback__in=feedbacks) return ratings I use data from this method in many place as input for calculations as property in model. But problem is that every time I call this method, query is created into DB. I think I would need some kind of cache, but when I tried to decorate as property, exception was thrown : 'QuerySet' object is not callable. Next issue I have is connected with number of instances of same object. Every instance has unique values and place in structure and returned ratings is different, but is not posible with large amount of instances doing query for each of that. So when I have 10 instances … -
Django Issue on Docker
I am running the Django rest framework and it is running fine but > when It goes to docker then I see this issue. Is anyone knows how to resolve the issue? I am searching on the internet but did not find any solution, anyone who encounters the same issue? Attaching to jdx_web_1 web_1 | Watching for file changes with StatReloader web_1 | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.10/threading.py", line 1009, in _bootstrap_inner web_1 | self.run() web_1 | File "/usr/local/lib/python3.10/threading.py", line 946, in run web_1 | self._target(*self._args, **self._kwargs) web_1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run web_1 | autoreload.raise_last_exception() web_1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception web_1 | raise _exception[1] web_1 | File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 398, in execute web_1 | autoreload.check_errors(django.setup)() web_1 | File "/usr/local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup web_1 | apps.populate(settings.INSTALLED_APPS) web_1 | File "/usr/local/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate web_1 | app_config.import_models() web_1 | File "/usr/local/lib/python3.10/site-packages/django/apps/config.py", line 304, in import_models web_1 | self.models_module = import_module(models_module_name) web_1 | File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module web_1 | … -
Ucenik matching query does not exist
I have a problem in views.py: def profil(request, pk): context = { 'profesor': Profesor.objects.get(id=pk), 'ucenik': Ucenik.objects.get(id=pk), } return render(request, 'profil.html', context) when i go to page i got this error: Ucenik matching query does not exist. my url.py: path('profesor/', views.profesor, name='profesor'), path('ucenik/', views.ucenik, name='ucenik'), path('profil/<str:pk>/', views.profil, name='profil'), if i delete: 'ucenik': Ucenik.objects.get(id=pk) then work, but on my profil.html page i need to display details Prfesor model and Ucenik model, i need both of them in def profil -
hey can anyone help me with this i am new to django,how can i get the user details using the token authentication when the message is created
Authenticate the user using token authentication. (NOT JWT Token) There's a quota of 10 messages per hour per user. After a successful message creation, return the message object (JSON) in the response. Example: { "id": 102, "message": "Lorem ipsum", "created_at": "created time in UTC", "updated_at": "last updated time in UTC", "created_by": { "id": 3, "username": "testuser", "email": "test@mail.com", ... } } In case of any error, return the error message. -
Need help saving a base64 image to django image field
i am working on a django project which returns a base64 encoded image and i want to save the image to the django image field.however i am missing something and would appreciate any help. Here is the model: class Catalogue(models.Model): products = models.ForeignKey(Product, on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=True) description = models.CharField(max_length=255, blank=True) image_link = models.CharField(max_length=255, blank=True) image = models.ImageField(blank=True, null=True, default=None) def save(self, *args, **kwargs): self.name = self.products.name self.description = self.products.description super(Catalogue, self).save(*args, **kwargs) def __str__(self): return str(self.products) in views.py which i am getting the image from an api cat_name = [] for e in Catalogue.objects.all(): cat_name.append(e.name) print(cat_name) for prod_id in cat_name: print(prod_id) image_url = f"API URL HERE" b64 = requests.get(image_url, headers=headers).json() b64_img_code = b64['data'] Catalogue.image = base64_to_image(b64_img_code) Catalogue.save() messages.success(request, "Product Added") return redirect('home') This is the utils file that am decoding the passed base64 string: def base64_to_image(base64_string): return ContentFile(base64.b64decode(base64_string), name=uuid4().hex + ".png") Thanks again in advance -
Django Celery Periodic task is not running on mentioned crontab
I am using the below packages. celery==5.1.2 Django==3.1 I have 2 periodic celery tasks, in which I want the first task to run every 15 mins and the second to run every 20 mins. But the problem is that the first task is running on time, while the second is not running. Although I'm getting a message on console: Scheduler: Sending due task <task_name> (<task_name>) But the logs inside that function are not coming on the console. Please find the following files, celery.py from celery import Celery, Task app = Celery('settings') ... class PeriodicTask(Task): @classmethod def on_bound(cls, app): app.conf.beat_schedule[cls.name] = { "schedule": cls.run_every, "task": cls.name, "args": cls.args if hasattr(cls, "args") else (), "kwargs": cls.kwargs if hasattr(cls, "kwargs") else {}, "options": cls.options if hasattr(cls, "options") else {} } tasks.py from celery.schedules import crontab from settings.celery import app, PeriodicTask ... @app.task( base=PeriodicTask, run_every=crontab(minute='*/15'), name='task1', options={'queue': 'queue_name'} ) def task1(): logger.info("task1 called") @app.task( base=PeriodicTask, run_every=crontab(minute='*/20'), name='task2' ) def task2(): logger.info("task2 called") Please help me to find the bug here. Thanks! -
python.exe: No module named django-admin Vscode Error
(venv) PS D:\Project> python -m django-admin startproject home . D:\Project\venv\Scripts\python.exe: No module named django-admin I have no clue what I am doing wrong. I am pretty new to this. Vscode doesn't show python in the status bar. I have already set the interpreter. Every video on Youtube shows how to create the project directly. Google gave me no results on this question. -
Django local variable 'cart' referenced before assignment
i am trying to add a product to the cart and then redirect to the 'cart' page/url but when i select the button to add to cart, i get this error UnboundLocalError at /cart/add_cart/3/ local variable 'cart' referenced before assignment this is the function to get cart id : def _cart_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart this is the function to add a product to cart and redirect to the cart page: def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) #use cart_idin session to get cart except Cart.DoesNotExist: cart = cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity = 1, cart = cart, ) cart_item.save() return redirect('cart') -
How to upload file to Django rest framework API using Axios and react hook form?
I have created an API using Django Rest Framework. It has an image uploading option. But I can not upload the file. I am using Axios for API calls and react hook form for form handling. I am posting the code below for better understanding. Django: Model: class BlogModel(models.Model): user = models.ForeignKey(user_model.User, on_delete=models.CASCADE, related_name="user_blog") blogtitle = models.CharField(max_length=250) blogcontent = models.TextField() blogimg = models.ImageField(upload_to="blog_image", blank=True) slug = models.SlugField(max_length=250, unique=True) tags = models.ManyToManyField(BlogTagsModel, related_name='blog_tags', blank=True, null=True) published_date = models.DateTimeField(auto_now_add=True) edit_date = models.DateTimeField(auto_now=True) Serializer class BlogSerializer(serializers.ModelSerializer): class Meta: model = blog_model.BlogModel fields = '__all__' extra_kwargs = { 'user': {'read_only': True}, 'slug': {'read_only': True}, } View class BlogPostView(generics.ListCreateAPIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = blog_ser.BlogSerializer queryset = blog_model.BlogModel.objects.all() def perform_create(self, serializer): rand_num = random.randint(99, 222) blog_slug_str = f"{serializer.validated_data.get('blogtitle')}{rand_num}" sample_string_bytes = blog_slug_str.encode("ascii") base64_bytes = base64.b64encode(sample_string_bytes) slug = base64_bytes.decode("ascii") serializer.save(user=self.request.user, slug=slug) React: Form JSX <form className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" onSubmit={handleSubmit(onSubmit)}> <div className="mb-4"> <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="title" > Title </label> <input className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="title" type="text" {...register('title', { required: true })} /> {errors.title && <p className="text-red-500 text-xs italic">Title is required</p>} </div> <div className="mb-4"> <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="image" > Image </label> <input … -
Django html display from model
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 %}