Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Positional argument after asterisk in Python
I have model in Django. Project. It has foreign key to Organization model with related_name='projects'. So I can call my_org.projects.all(). But what if i'd like to call my_org.projects()? Let's check: (Pdb++) org = Organization.objects.first() (Pdb++) org.projects() *** TypeError: __call__() missing 1 required keyword-only argument: 'manager' (Pdb++) org.projects(None) *** TypeError: __call__() takes 1 positional argument but 2 were given That's really uncommon. So what causes this? Here's the code located in RelatedManager in Django: def __call__(self, *, manager): manager = getattr(self.model, manager) manager_class = create_reverse_many_to_one_manager(manager.__class__, rel) return manager_class(self.instance) Can someone explain me how is this method constructed? As far as I know you can't place positional argument after an asterisk *args. But here we have (self, *, manager). Looks like programmer won't be able to pass manager ever! -
How to get the url of the registered user page through user-auth in django?
I need to get the url of the registered user page through user-auth in django. Once the registration of a user has been completed, I wish to obtain the url to the page of the social network. For example the account https://twitter.com/IBM_ES or in facebook https://www.facebook.com/profile.php?id=100022780573987 has registered, I want to be able to get that url. I implemented registration for Twitter and Facebook. And in case of facebook I had in database UID 20008289656542132 for a certain account but was different to the id on the url of the real account, but anyway I substituted the id for the UID get it from social-auth but says the account doesn't exist and are differents. In case of twitter I know that having the username I can get the URL but there is any way social-auth generates it, or know how to manually do it on facebook. -
__call__() missing 1 required keyword-only argument: 'manager'
class CreateProject(forms.ModelForm): def __init__(self, user, editable_object=None, *args, **kwargs): super(CreateProject, self).__init__(*args, **kwargs) use_required_attribute = True self.fields['tasks'] = forms.ModelMultipleChoiceField( widget=forms.SelectMultiple( attrs={ 'class': 'form-control' } ), queryset=Task.objects.filter(company=user.company), required=True, initial=editable_object.tasks if editable_object else None, label='Tasks' ) When I try to give editable_object parameter (object Project model) it can't make initial value for tasks field, when I remove initial value for this field it works -
Overriding django admin get_queryset method
In Django admin for a given model I am trying to see if a query has been made using a given parameter (in this case it is called 'entry_time'). If it is not used in the query I want to set it myself to limit the search results. For that, I am overriding the get_queryset() method as folows: def get_queryset(self, request): """Overrides default queryset.""" qs = super(HeartbeatCellAdmin, self).get_queryset(request) for param,value in request.GET.items(): if 'entry_time' in param: return qs else: return qs.filter(entry_time__gte=pendulum.now('UTC') - timedelta( seconds=HeartbeatCellAdmin.default_secs_past)) The above code does not work, and I ve tried a couple more options but all unsuccessfully. Does anybody know how to solve this? -
Django rest - router is not creating url path, giving 404, and the api webpage has incorrect urls listed
ive created some urls with the default router as per the below: from django.urls import path, include from rest_framework import routers from rest_framework_bulk.routes import BulkRouter from . import views router = routers.DefaultRouter() ... router.register(r'data/device/routingtable/', views.DataDeviceRoutingTable) ... and then I attempt to hit the URL http://localhost:8100/api/data/device/routingtable/ and I am greeted with a 404, would anyone know why this is? and when I hit my api home page and it lists urls, they are mapped to the wrong views: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { ... "data/device/routingtable/": "http://localhost:8100/api/rt_upload/", ... } views.py: class DataDeviceRoutingTable(viewsets.ModelViewSet): time_threshold = datetime.now() - timedelta(minutes=2) queryset = DeviceData.objects.all().select_related('device','device_use').order_by('monitoring_order') serializer_class = SerializerDataRoutingTable permission_classes = (IsAdminUser,) filter_class = DeviceData filter_backends = (filters.SearchFilter,) search_fields = ('device__hostname','device_use__use') serialisers.py: class SerializerDataRoutingTable(serializers.ModelSerializer): hostname = serializers.ReadOnlyField(source='device.hostname', ) site_id = serializers.ReadOnlyField(source='device.site_id', ) routing_table = serializers.SerializerMethodField(source='routing_table',) use = serializers.ReadOnlyField(source='device_use.use', ) def get_routing_table(self, instance): try: return json.loads(instance.routing_table) except: return instance.routing_table class Meta: model = DeviceData fields = ('id','site_id','device_id','hostname','use', 'timestamp', 'routing_table') depth = 1 -
showing all values null in databse while doing with django
In django when i applied models .py code and save the file its working properly but when user enters the details in the form and when i check the databse its shows null in the rows and just the password appers. Can you help me with the solution. Here's my model.py code class studentinfo(models.Model): id = models.AutoField(primary_key=True) First_Name = models.CharField(max_length=50, blank=False) Last_Name = models.CharField(max_length=50, blank=False) Email = models.EmailField(blank=False, null=False, default="") Date_of_Birth = models.DateField(auto_now=False, auto_now_add=False, blank=False) Number = models.IntegerField(10, blank=False) Password = models.CharField(max_length=25) The database shows every value as null in the row and just the password is appeared in the database here's my views.py def form(request): first_name = request.POST.get('First_Name') last_name = request.POST.get('Last_Name') date_of_birth = request.POST.get('Date_of_Birth') number = request.POST.get('Number') email = request.POST.get('Email') password = request.POST.get('Password') o_ref = studentinfo(First_Name=first_name, Last_Name=last_name, Date_of_Birth=date_of_birth,Number=number,Email=email, Password=password) o_ref.save() print("User Created") return render(request, 'signup.html') -
How add the column to the table of database in django without defining it in Model just due to change in object?
In Python Django, Let's say I have one model defined with 3 Fields. Using django API we can put the data on the database by defining object and populate the fields and save it by save(). But when I define additional field for the object and save(). That data doesnt seen in database. Is there any way to create one extra columns. # Just for demo on attribute is assigned for model 'from django.db import modules' class A(modules.Model): name = models.CharField() # in my django chell after migration b = A(name="surendra) b.save() # It will be saved but b.last = models.CharField() b.last = "tamang" b.save() # works but not save in the database Is there any other way to do so? -
python - change dict keys in a queryset of values
I have something like this: model.objets.values('id', 'name') that returns a list of dicts with 'id' and 'name' as the keys. Is there a way that I can pass custom names to those keys? Something like: model.objets.values('id', 'name').column_names('main id', 'name of de thing I want')? I'm using python + django -
Django - Reuse an annotated count
I have a model that allows me to log errors with a hash that I generate, so the same errors have the same hash so I am able to group and count them. The model looks something like this. class ErrorLog(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date = models.DateTimeField(null=True, blank=True, db_index=True) log = models.TextField(blank=True, null=True) log_hash = models.CharField(max_length=255, blank=True, null=True) In my view, I perform the following query to count the errors by hash. def get(self, request): qs = self.filter_queryset(self.get_queryset()) total_errors = qs.count() qs = qs.values( 'log_hash', 'log' ).annotate( error_count=Count('log_hash') ).annotate( percentage_of_occurrence=Concat( Cast( funcs.Round( (F('error_count') / total_errors) * 100, 1 ), CharField() ), Value('%') ) ) This works like a charm, because I can get my results back just as I want them. "results": [ { "error_count": 2, "percentage_of_occurrence": "50.0%", "log_hash": "8f7744ba51869f93ce990c67bd8d3544", "log": "Error 1" }, { "error_count": 1, "percentage_of_occurrence": "25.0%", "log_hash": "de54a1e3be2cab4d04d8c61f538a71df", "log": "Error 2" }, { "error_count": 1, "percentage_of_occurrence": "25.0%", "log_hash": "05988dc15543ef06e803a930923d11d4", "log": "Error 3" } ] Here comes the problem, this is REALLY slow on a large table, so after inspecting the SQL generated I saw one problem. I am counting 2 times, one to get the error_count, and another one to calculate the percentage_of_occurrence. SELECT `errorlog`.`log_hash`, … -
Generate static openapi schema only for certain app
Is there a way to specify what app to generate a static openapi schema for? I'm looking for something like (fictional example): python manage.py generateschema --apps polls > openapi-polls.yaml I can sort of do it for dynamic schemas, e.g: urlpatterns = [ path('openapi', get_schema_view( title='Polls API', description='Polls API description', version='1.0.0', patterns=[re_path(r'^polls/', include('polls.urls'))] # <-- here ), name='openapi-polls-schema'), ] but I need it for static schemas as I'll have to manually add a lot of responses and parameters (XY problem?) description, and the documentation about DRF dynamic schemas is quite limited. -
Django - save multiple input parameters to database
I'm using the below custom form in my Django app: forms.py class UpdateURLForm(forms.ModelForm): VideoURL = forms.URLField() MainDescription = forms.CharField(max_length=100) class Meta: model = Listing fields = ('VideoURL', 'MainDescription',) Then, in views.py I import the form and then I render the fields into my HTML template: def edit_info(request): if request.method == 'POST': form = UpdateURLForm(request.POST) if form.is_valid(): VideoURL = form.cleaned_data['VideoURL'] MainDescription = form.cleaned_data['MainDescription'] else: form = UpdateURLForm() return render(request, 'myapp/updateinfo.html', {'form': form}) HTML: <form action="#" method='post' class="card shadow-soft border p-4 mb-4">{% csrf_token %} <div class="form-group"> <label for="video">Video URL:</label> {{form.VideoURL|add_class:"form-control shadow-soft"}} </div> <div class="form-group"> <label for="video">Video URL:</label> {{form.MainDescription|add_class:"form-control shadow-soft"}} </div> <div class="row"> <div class="col"> <button class="btn btn-primary btn-dark mt-2 animate-up-2 text-right" type="submit">Update</button> </div> </div> </form> Now, my question is: how can I render the field MainDescription in the template in order to save both information into the database? The way I rendered the second field (MainDescription) doesn't work. Thanks! -
Django "writer.writerow" for each column
I am trying to get each column separately. But I still can't get the right division. My code is added below. I tried to apply a loop, change the format of the list but to no avail. I was looking for answers in the forum, but the code below doesn't work for me at all. #My try wr.writerow(item) #column by column (everything goes to one column) wr.writerows(item) #row by row (divides my word into parts) def export_users_csv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="users.csv"' writer = csv.writer(response) writer.writerows(('Id', 'Username', 'Email', 'Password')) users = CustomUser.objects.all().values_list('id', 'username', 'email', 'password') for user in users: writer.writerow(user) return response Expectations Any help will be appreciated. -
How to see django object query speed
I would like to test different ways of text searching in django models with different functions. Is there a way to print in the console or in the template how long does it take to query the database? Thanks in advance (Might not be necessary but still: These are the 3 functions I want to test the speed of.) def first_results(request): if request.method == 'POST': query = request.POST.get('query') results = Page.objects.search(query) return render(request, 'results.html', {'results': results}) else: return render(request, 'home.html') def second_results(request): if request.method == 'POST': query = request.POST.get('query') results = Page.objects.annotate(search=SearchVector('title', 'content')).filter( search=query ) return render(request, 'results.html', {'results': results}) else: return render(request, 'home.html') def third_results(request): if request.method == 'POST': query = request.POST.get('query') results = Page.objects.filter( Q(title__contains=query) | Q(content__contains=query) ) return render(request, 'results.html', {'results': results}) else: return render(request, 'home.html') -
AnonymousUser when logged with SimpleJWT
I know it's not the first question of that kind, but other topics didn't help me. I want to use djangorestframework-simplejwt to authenticate user and everything is fine since it comes to getting user. I always get AnonymousUser. I obtain token by visiting api/token and passing credentials. Token is created correctly, it contains right user id. When I try to get access to protected view it allows me to, but Django doesn't recognise user. settings.py import os from datetime import timedelta # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ["SECRET_KEY"] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "corsheaders", "djmoney", "bills", "accounts", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "shared_bills.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ] }, } ] WSGI_APPLICATION = "shared_bills.wsgi.application" # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = … -
Return list of users in profile
I would like users classified as students to be able to view all the mentors/teachers profiles along with their linkedin links in their profile pages This is what i have tried. This is my views.py (students.py): #get list of mentors def mentor_list(request): mentor_list = [] users = User.objects.filter(is_teacher=True) mentor = Mentor.objects.get() for mentor in users: data = mentor.get_decoded() mentor_list.append(data.get('_auth_user_id', None)) return User.objects.filter(id__in=mentor_list) def render_mentor_list(): return {'users': mentor_list() } and my html file: ... {% if users %} <ul class="user-list"> {% for user in users %} <li>{{ user.first_name }} {{ user.last_name }}</li> <li>{{ mentor.linkedin }}</li> {% endfor %} </ul> {% endif %} ... and models.py: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) ... class Mentor(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) linkedin = models.URLField(max_length=200,null=True,blank=True) Currently nothing is appearing in the student profile (the html) -
What is the best authentication and permission practice for Django and Angular based project?
I started a Project based on Django and Angular. For Django I use the rest_framework.authtoken to provide a token based on username and password that is sent from Angular login form, and then the provided token store in a cookie and use it to detect that user is eligible to do some thing or not. In my scenario, for each route or request on Angular I need to check the user authentication with checking the token that is valid on cookie or not. I think this way is not the good practice so, what is the best practice for user authentication based on Django and Angular? I have experience on Laravel Auth. That just by checking the user authentication on contractor the whole function in a controller will be protected. As well the auth function is available in whole of project and simply we can do that. What is the nearest package to Laravel Auth on Django or Angular? -
Django Rest Framework gives 302 in Unit tests when force_login() on detail view?
I'm using DJango Rest Framework to serve an api. I've got a couple tests which work great. To do a post the user needs to be logged in and I also do some checks for the detail view for a logged in user. I do this as follows: class DeviceTestCase(APITestCase): USERNAME = "username" EMAIL = 'a@b.com' PASSWORD = "password" def setUp(self): self.sa_group, _ = Group.objects.get_or_create(name=settings.KEYCLOAK_SA_WRITE_PERMISSION_NAME) self.authorized_user = User.objects.create_user(self.USERNAME, self.EMAIL, self.PASSWORD) self.sa_group.user_set.add(self.authorized_user) def test_post(self): device = DeviceFactory.build() url = reverse('device-list') self.client.force_login(self.authorized_user) response = self.client.post(url, data={'some': 'test', 'data': 'here'}, format='json') self.client.logout() self.assertEqual(status.HTTP_201_CREATED, response.status_code) # And some more tests here def test_detail_logged_in(self): device = DeviceFactory.create() url = reverse('device-detail', kwargs={'pk': device.pk}) self.client.force_login(self.authorized_user) response = self.client.get(url) self.client.logout() self.assertEqual(status.HTTP_200_OK, response.status_code, 'Wrong response code for {}'.format(url)) # And some more tests here The first test works great. It posts the new record and all checks pass. The second test fails though. It gives an error saying AssertionError: 200 != 302 : Wrong response code for /sa/devices/1/ It turns out the list view redirects the user to the login screen. Why oh why does the first test log the user in perfectly, but does the second test redirect the user to the login screen? Am I missing something? … -
Kubernetes Django Restframework on GKE
I've tried to get access via the external ip from the load balancer. But I can't connect with my browser through that ip. I've got a connection refused on port 80. I don't know if my yaml file is incorrect or its a config on my load balancer I builded my docker image successfully with my requirements.txt and load it to the bucket from GKE to pull the docker image into Kubernetes. I deployed my image with the command: docker create -f <filename>.yaml with following yaml file: # [START kubernetes_deployment] apiVersion: extensions/v1beta1 kind: Deployment metadata: name: example labels: app: example spec: replicas: 1 template: metadata: labels: app: example spec: containers: - name: faxi image: gcr.io/<my_id_stands_here/faxi command: ["python3", "manage.py", "runserver"] env: # [START cloudsql_secrets] - name: DATABASE_USER valueFrom: secretKeyRef: name: cloudsql key: username - name: DATABASE_PASSWORD valueFrom: secretKeyRef: name: cloudsql key: password # [END cloudsql_secrets] ports: - containerPort: 8080 # [START proxy_container] - image: b.gcr.io/cloudsql-docker/gce-proxy:1.05 name: cloudsql-proxy command: ["/cloud_sql_proxy", "--dir=/cloudsql", "-instances=<I put here my instance name inside>", "-credential_file=<my_credential_file"] volumeMounts: - name: cloudsql-oauth-credentials mountPath: /secrets/cloudsql readOnly: true - name: ssl-certs mountPath: /etc/ssl/certs - name: cloudsql mountPath: /cloudsql # [END proxy_container] # [START volumes] volumes: - name: cloudsql-oauth-credentials secret: secretName: cloudsql-oauth-credentials - name: … -
Default Django Rest Framework HTML POST Forms not showing after upgrading to latest versions
Previously when using the Django REST Framework I got browsable API endpoints, and I could enter data with POST and PUT forms. However, after I recently updated my dependencies the HTML form for POST and PUT doesn't show up anymore [picture 2], and even trying to click my user name in the top right to get options to for example log out, I'm simply redirected back to the same url with /# appended to it [picture 1]. If I go to a specific entry by entering localhost/myEndpoint/1/ and I try the DELETE button, that does not do anything either. There are no logs indicating something went wrong in the output of manage.py runserver Is this a bug or is there some way that I can fix this? I was using an updated to the following versions: Django 2.2 => 2.2.9 djangorestframework 3.9.2 => 3.11.0 djangorestframework-simplejwt => 4.4.0 Picture 1: Picture 2: -
Multiple database implementation in django
I have two databases, which I need to use in the same app of django asynchronously. I have referred following document : https://docs.djangoproject.com/en/3.0/topics/db/multi-db/ which basically tells the configuration of DATABASE_ROUTERS but doesn't really explain how to use methods like db_for_read, db_for_write, etc in views.py let's say. Can someone help me out in configuring tables from different databases(not synchronous to each other) in the same app. Thanks! -
Is it possible to create a type that inherits from a Django model to add constraints on fields?
I am currently improving the typing coverage of my Django app and I ran into a problem: I have a model A that looks like: class CreditRequest(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE) limit_amount = models.BigIntegerField(null=True) In the lifetime of A instances, on a business point of view, I know that some A instances will always have the limit_amount field filled. So, in the code, I will use some functions such as: def get_floored_limit_amount(a: A) -> int: return math.floor(a.limit_amount) But mypy will - rightfully - claim that limit_amount may be None and raise an error. Nonetheless, I don't want to add checks on every field that will have the same behaviour in each function that will assume the instance is in this particular business state. So my first idea was to create a different type hint, such as in pseudo-python: type AVariant(A): limit_amount: int and use it in the said functions. Do you see a way of doing it? The last idea I had is to add a method on A class that will check for every field validity or raise errors; and call this method at the beginning of every function. But I don't know if it's the cleanest way of … -
Unpickle transfered SQAlchemy PickleType field
I want to transfer a database from SQAlchemy to standard DJANGO ORM. One of my fields in the SQLAlchemy model.py is pkl = Column(PickleType) The database itself is stored in marinaDB, so what I did was gave the DB itself to DJANGO, and used python3 manage.py inspectdb This created a DJANGO models.py file without errors. The mentioned field was transformed into pkl = models.TextField(blank=True, null=True) How can I access the PickleType column content? I see, that the content of the fields are <class 'bytes'>, however if I try to unpickel it I get the following error: for i in my_objet.objects.all(): print(pickle.loads(i.pkl)) ... Internal Server Error: / Traceback (most recent call last): print(pickle.loads(i.pkl)) _pickle.UnpicklingError: invalid load key, '\xef'. -
What may be the reason for Django sudden static files load failure?
I have successfully deployed my first Django project(though still working on the addition of other functionalities) http://167.172.62.187 now back to the development machine I wanted to strengthen my understanding of Django by developing an eCommerce app. No error was shown, static files were collected successfully, loaded static files in the frontend but static files didn't work when I tested my app in my localhost. Another strange issue I noticed was that even my blog that's working perfectly before stopped rendering static files too. I set debug=True in both cases and I am using one virtual environment for my Django applications. Please I am confused and I need your help. -
Traversing reverse through some basic logic in a Django model
I have a table (relationship) which relates two rows in another table (context). This allows me to get the context and the relationship between them: i.e. Context 1 - is above - Context 2. Context 2 - is above - Context 3. How do I reverse the logic to return in the template that: Context 2 - is below- Context 1? My models and template follow. models.py class Context(models.Model): context_id = models.AutoField(primary_key=True) class Relationship (models.Model): relationship_id = models.AutoField(primary_key=True) context_id1 = models.ForeignKey(Context, db_column='context_id1', on_delete = models.PROTECT, related_name='relations_through1') context_id2 = models.ForeignKey(Context, db_column='context_id2', on_delete = models.PROTECT, related_name='relations_through2') relationship = models.CharField(max_length = 50, blank=True, null=True) template {% for relationship in context.relations_through1.all %} Context Above: {{________________________________}} <br> Current Context:{{relationship.context_id1.number}} <br> Relationship:{{relationship.relationship}} <br> Context Below: {{relationship.context_id2.number}} {% endfor %} p.s. I know about the _id suffix, Django is set not to manage the database. -
How to use filtering data while using distinct method in django?
I hope my title is enough to understand what I mean, please help me on this problem guys. When I tried this: id_list = grade.objects.filter(Teacher=m.id).values_list('Students_Enrollment_Records_id',flat=True).distinct() I use distinct() to eliminates duplicate rows of Students Enrollment Record from the query results but I wonder why the result is like this: What should I do to show the Students name not that QuerySet in my html? This is my current views.py: id_list = grade.objects.filter(Teacher=m.id).values_list('Students_Enrollment_Records_id',flat=True).distinct() print(id_list) grades = grade.objects.filter(Students_Enrollment_Records_id__in=id_list) print(grades) This is my models.py: class grade(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Average = models.FloatField(null=True, blank=True) UPDATE when I tried this piste = grade.objects.filter(Teacher_id=m.id).values_list('Students_Enrollment_Records').annotate(Average=Avg('Average')).order_by('Grading_Categories').distinct() the computation is fix but the teacher name, Subject and Name of students didn't display but the ID is display just like this this is my desire answer this is how I post in html views.py return render(request, 'Homepage/index.html', {"piste":piste}) html {% for n in piste %} <tr> <td>{{n.Teacher}}</td> <td>{{n.Subjects}}</td> <td>{{n.Students_Enrollment_Records.Students_Enrollment_Records.Student_Users}}</td> <td>{{n}}</td> </tr> {% endfor %} This is model.py class EmployeeUser(models.Model): Image = models.ImageField(upload_to='images', null=True, blank=True) Employee_Number = models.CharField(max_length=500, null=True) Username = models.CharField(max_length=500, null=True) Password = models.CharField(max_length=500, null=True) My_Department …