Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
strange error with serializer and the json response
I have a profile model that I serialize and set fields using "all". The problem is that when I run it, I get the error that: AttributeError at /api/accounts/profile/ 'User' object has no attribute 'following' I tried setting the fields manually and get the same error, but when I remove following from the field it runs properly and I get the normal JSON response, but all the fields show null instead of the data I set in the admin panel. { "pk": 2, "date_of_birth": null, "bio": null, "profile_photo": null, "sex": null, "type_of_body": null, "feet": null, "inches": null, "lives_in": null } below is the code to the rest of the app models.py class Profile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) following = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followers', blank=True) date_of_birth = models.DateField(blank=True, null=True, verbose_name="DOB") bio = models.TextField(max_length=500, null=True, blank=True) profile_photo = models.CharField(blank=True, null=True, max_length=300) sex = models.CharField(max_length=1, choices=SEX, blank=True, null=True) type_of_body = models.CharField(max_length=8, choices=BODYTYPE, blank=True, null=True) feet = models.PositiveIntegerField(blank=True, null=True) inches = models.PositiveIntegerField(blank=True, null=True) lives_in = models.CharField(max_length=50, blank=True, null=True) updated_on = models.DateTimeField(auto_now_add=True) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' read_only_fields = ('pk', 'user', 'following', 'height') views.py class CurrentUserProfileAPIView(APIView): permission_classes = [IsAuthenticated] def get(self, request): serializer = ProfileSerializer(request.user) return Response(serializer.data) urls.py urlpatterns = [ … -
I want add two annotation for two foreign keys using Django. How do I do this?
# models.py from django.db import models class Elephant(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE) families = models.ForeignKey(Families, on_delete=models.CASCADE) def add_families_and_locations_counts(elephants): return elephants.annotate( families_number=Count('families'), location_number=Count('location') ) # Run output = add_families_and_locations_counts(elephants) In the above, the counts are incorrect. How do I get the correct counts? -
Is there an REST API where i can send a POST and make a comment in a TripAdvisor Profile?
I'm developing a personal project where I must publish a comment in a Tripadvisor profile. According to the TripAdvisor's Rest API, there is no endpoint for me to make a POST. Is there a generic API REST that allows this functionality? Or has anyone in this community been able to solve this? I'm developing my project in Django Thanks! -
How to Query search model with key words Django? (Current dropdown)
I have multiple models in Django that hold hundreds of different fields. One of which describes a uniform class Uniform(models.Model): category = models.CharField(max_length = 50) description = models.CharField(max_length = 50) price = models.FloatField(max_length = 6) size = models.CharField(max_length = 10) def __str__(self): return '{}: {} - {} - ${}'.format(self.category, self.description, self.size, self.price) And a transaction model which inherits from the uniform class Transaction(models.Model): employee_id = models.ForeignKey(Employee, on_delete = models.PROTECT) uniform = models.ForeignKey(Uniform, on_delete = models.CASCADE) date = models.DateTimeField(default=timezone.now) def __str__(self): return '{}: {} - {}'.format(self.employee_id, self.uniform, str(self.date)) There are hundreds of different uniforms I have loaded into the SQLite Db that connects to a form class TransactionForm(forms.ModelForm): class Meta(): model = Transaction fields = '__all__' Right now the current query is a HUGE dropdown and the user must scroll through the uniform options to record the right uniform as a transaction How can I query the uniform as a search on the user side, rather than it being a dropdown? I have seen queries done within the app, and qutocomplete-light package, but the package isn't readable as a module, and even installed on my machine. I have gone through different query sets, but trouble implementing the form as a search, … -
Django LDAP3 security with TLS: am I secure?
I'm concerned the login with LDAP in my Django app is not secure. After trying several methods, I was able to get a working custom backend using ldap3. I was advised by other programmers (unfortunately non-Django programmers) in my organization to use TLS, but when I make a connection with ldap3, it looks like it's not using TLS. I'm new to LDAP and security, but I've tried to do as much reading as possible, so hopefully I'm not missing something obvious. Based on the ldap3 documentation, and trial-and-error, it seems that the connection has to be bound (conn.bind()) before TLS can be started (conn.start_tls()). Is this true? If the connection is bound without TLS, is this exposing a vulnerability? If so, what's the point of start TLS after the connection? Am I using ldap3 and TLS correctly? Is this login method insecure, exposing passwords? #backends.py import ldap3 import ssl class LDAPBackend(ModelBackend): def authenticate(self, request, username=None, password=None): server = ldap3.Server('ldap://<url>', use_ssl=True) conn = ldap3.Connection(server, user=request.POST.get('username'), password=request.POST.get('password')) try: conn.bind() conn.start_tls() search_filter = '(&(objectClass=user)(userPrincipalName='+request.POST.get('username')+'))' conn.search(search_base='<search terms>', search_filter=search_filter, search_scope='SUBTREE', attributes='*') attrs = conn.response[0]['attributes'] username = attrs['userPrincipalName'] except: return None If I switch the conn.bind() and conn.start_tls() order (so TLS starts first), the login fails … -
Getting the same output in Gunicorn as runserver
I'd like to use gunicorn in dev just to have as close to production an environment as possible. I really like the output though of runserver: I'm launching gunicorn with: gunicorn -b :5000 --log-level debug config.wsgi:application Which has a mess of information, but not what runserver includes. Is there a setting in either gunicorn or django I should be looking at to get it to have similar output as runserver? -
Django: logging messages from raised exceptions in REST API
I'm using Django REST Framework for a simple API. I have the following custom exception that subclasses DRF's APIException: class BadRequest(APIException): status_code = 400 default_detail = 'Invalid request' default_code = 'bad_request' The project uses the following logging setup: LOGGING = { 'handlers': { 'log_to_file': { 'level': 'DEBUG', 'class': 'logging.handlers.TimedRotatingFileHandler', } }, 'loggers': { # "catch all" logger '': { 'handlers': ['log_to_file'], 'level': 'INFO', 'propagate': True, }, 'django': { 'handlers': ['log_to_file'], 'propagate': False, 'level': 'INFO', }, } Now if I test the exception handling with this view: @api_view(['GET']) def hello_world(request): raise BadRequest('test') I correctly get a 400 response with a {'detail': 'test'} JSON, but the log file contains only: 2019-11-19 [django.request] ERROR: Internal Server Error: /api/hello [in log.py:228] How can I get it to display the actual exception message (test) in the log file? Note that this is the behavior I get when DEBUG = False. -
Python django 'QueryDict' object has no attribute 'subject'
Hola que tal escribo aquí porque no se como solucionar mi problema, resulta que estoy creando un portal de pruebas en linea y necesito saber que estoy fallando, explico el contexto al momento de crear una pregunta se debe indicar un indice de evaluación, y este tiene un filtro que va de acuerdo la asignatura y curso de la prueba en cuestión. Bueno el filtro funciona me muestra los indicadores que son de un curso y asignatura en especifico, pero solo cuando le ingreso un id manual en cambio cuando le paso las variables del quiz este me tira el error: 'QueryDict' object has no attribute 'subject'dejo el codigo del form y la vista para que me puedan decir en que estoy fallando porfavor. forms.py class QuestionForm(forms.ModelForm): class Meta: model = Question context_object_name = 'questions' fields = ('number','planificacion','text','description', 'puntaje' ,'image','document' ) label = 'Pregunta' def __init__(self ,quiz ,*args, **kwargs): super().__init__(*args, **kwargs) self.fields['planificacion'].queryset = PlanificacionIndicador.objects.filter(planificacion__asignatura__id=quiz.subject.id, planificacion__curso__id=1) Como se logra apreciar en el filter que hice el planificacion__curso__id=1 tiene una id puesta de manera manual y la otra tiene como quiero, debo decir que el filtro funciona lo que falla es que al momento de querer guardar me tira el error. view.py … -
Sending a Base64 to Backend using Ajax ---- Django receiving just part of the data sent by ajax
I made a simple Konva Js app that draws on a image, and i intend to send the image in base64 to the backend were i will decode it and store it, but i have a problem the backend is only receiving part of the data Can you guys help me out, Thanks in Advance !!! The Base64 is working on the Javascript side Javascirpt and Ajax document.getElementById('save').addEventListener( 'click', function () { var imagesrc = stage.toDataURL(); console.log(imagesrc) $.ajax({ url: '', data: { 'imagesrc': imagesrc }, type: 'POST' }).done(function (response) { console.log(response); }); } Django View @csrf_exempt def project_chapter_drawing_view(request, id, pk, name): project = get_object_or_404(Project, id=id) chapter_project = get_object_or_404(Chapter_Project, pk=pk) chapter = get_object_or_404(Chapter, name=name) try: chapter_menu = Chapter_Project.objects.filter(project__id=id).order_by('chapter__theme__name') except Chapter_Project.DoesNotExist: chapter_menu = None if request.method == 'POST': form = Plant_Drawn_Form(request.POST, request.FILES, instance=chapter_project) if request.is_ajax(): image = request.POST.get('imagesrc') print(image) image_data = base64.b64decode(image + "===") image_drawn = ContentFile(image_data, 'stage.jpg') chapter_project_plant = form.save(commit=False) chapter_project_plant.plant_image_drawn = image_drawn chapter_project_plant.save() else: form = Plant_Drawn_Form() return render(request, 'project-chapter-drawing.html', {'project': project, 'chapter_project': chapter_project, 'chapter_menu': chapter_menu, 'form': form, 'chapter': chapter}) ) -
Django REST with SPA - what structure
Django REST with SPA "within" or completely stand alone? I'm diving into a new project where I'll try to build a SaaS web application and I've set on using Django Rest (with Postgres to utilize schemas) and React/Vue on the frontend. What I'm unsure and what I can't seem to get an answer to is the way people structure these frameworks. E.g, on https://www.valentinog.com/blog/drf/ the author writes: /// I see the following patterns (which are common to almost every web framework): React in its own “frontend” Django app: load a single HTML template and let React manage the frontend (difficulty: medium) Django REST as a standalone API + React as a standalone SPA (difficulty: hard, it involves JWT for authentication) Mix and match: mini React apps inside Django templates (difficulty: simple) And here are my advices. If you’re just starting out with Django REST and React avoid the option 2. Go for option number 1 (React in its own “frontend” Django app) if: you’re building an app-like website the interface has lot of user interactions/AJAX you’re fine with Session based authentication there are no SEO concerns you’re fine with React Router /// Why is this beneficial, and is it actually … -
Why threads stopped in heroku?
I have been uploaded my project in heroku, and my script create 4 threads, each thread perform specific task, but sometimes log file tells me that some threads stopped like this, (Thread 13)! How can I solve it? this is the code! segmentationProcess = SegmentationProcess() dataList = request.body.decode("utf-8").split(',') data = segmentationProcess.preProcess(dataList) lock = multiprocessing.Lock() thread1 = ThreadWithLogAndControls(target=segmentationProcess.searchWorkExperience, args=(data, "W", manager.result, lock)) thread2 = ThreadWithLogAndControls(target=segmentationProcess.searchEducation, args=(data, "E", manager.result, lock)) thread3 = ThreadWithLogAndControls(target=segmentationProcess.serchSkills, args=(data, "S", manager.result, lock)) thread4 = ThreadWithLogAndControls(target=segmentationProcess.searchOthers, args=(data, "O", manager.result, lock)) thread1.start() thread2.start() thread3.start() thread4.start() thread1.join() thread2.join() thread3.join() thread4.join() Am using nbmultitask library for creating threads, it's like multiprocessing. https://github.com/micahscopes/nbmultitask -
How to override values on submission to update a field from a modal in Django?
I have a form that keeps track of when people enter/leave different areas. Whenever there is a discrepancy, for example, someone forgets to "leave" an area before entering a new one, the user is prompted an "estimate" of the time they believe they left the previous area at(edited_timestamp). The only two required fields on the main form are the employee number and the work area, as these are used to verify/keep track of data. When I try to reproduce the situation that would make the modal show up, it works, but when I attempt to submit it, I get these messages: and these are the errors that are being returned. Now, while I don't understand why the "Enter valid date/time" error is showing, I'm guessing the other two errors are due to the main form requiring the employee_number and the work_area and probably for this request, even though it is updating by the ID, it still wants the other two fields. I guess my question is, how could I modify this so that these two fields are not required for the modal? models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, … -
Django view works for only one url ,despite the appropriate queryset being generated in the view
I am trying to access a lesson belonging to a course in my application. When I use the url http://127.0.0.1:8000/courses/1/lessons/1/" the appropriate results get returned. However when I try anyother url such as "http://127.0.0.1:8000/courses/1/lessons/2/" I get an error instead Result for http://127.0.0.1:8000/courses/1/lessons/1/ { "id": 1, "title": "course 1 lessson 1", "owner": 1, "course": 1 } Expected Result for http://127.0.0.1:8000/courses/1/lessons/2/ { "id": 1, "title": "course 1 lessson 2", "owner": 1, "course": 1 } actual result { "detail": "Not found." } URL path('courses/<int:pk>/lessons/<int:lpk>/', LessonDetail.as_view()), Serializer class LessonSerializer(serializers.ModelSerializer): class Meta: model = Lesson fields = ['id','title','owner','course'] view class LessonDetail(generics.RetrieveUpdateDestroyAPIView): # queryset = Lesson.objects.all() serializer_class = LessonSerializer def get_queryset(self): # GET PK FROM URL USING KWARGS course_pk = self.kwargs['pk'] lesson_pk = self.kwargs['lpk'] qs = Lesson.objects.filter(course_id=course_pk,id=lesson_pk) print(qs) return qs model class Lesson(models.Model): title = models.CharField(max_length=150, help_text='Enter course title') video = models.CharField(max_length=150, help_text='Enter course title', null=True) thumbnail = models.CharField(max_length=150, help_text='Enter course title', null=True) pub_date = models.DateField(null=True, blank=True) course = models.ForeignKey('Course', on_delete=models.CASCADE,related_name='lessons') description = models.TextField(max_length=1000, help_text='Enter a brief description of the course') owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) The view returns the object <QuerySet [<Lesson: course 1 lessson 1>]> for http://127.0.0.1:8000/courses/1/lessons/1/ and <QuerySet [<Lesson: course 1 lessson 2>]> for http://127.0.0.1:8000/courses/1/lessons/2/. To my inexperienced eye, it looks as … -
Set Field = To Variable Django
Im trying to set one of my fields equal to a variable. New to Django and Python, appreciate the help. The field in my models week_of i want set to a variable. I made a variable in my Views.py titled weeknumber. week_of = weeknumber Views.PY def K8Points (request): if request.method == 'POST': form = K8PointsForm(request.POST) weekNumber = date.today().isocalendar()[1] if form.is_valid(): points = form.save() Models.PY class K8Points(models.Model): date = models.DateField(default=timezone.now) teacher_class_id = models.ForeignKey(TeacherClass, on_delete = models.PROTECT, default = "") student_id = models.CharField(max_length=50, default = "") total = models.IntegerField() week_of = models.DateField() day = models.CharField(max_length= 10, choices= DAY_OF_THE_WEEK) -
Adding attributes to the Product field Django Ecommerce
I am creating an e-commerce web application on Django and now i just want to know which is the most suitable or the best way to add attributes to the Base Product field (without repeating the base product) and also adding a unique SKU code for each product to find item individually The attributes are "Color", "Size" etc.. This is my Base product field class Item(models.Model): title = models.CharField(max_length=130) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=2, blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True, blank=True, null=True) slug = models.SlugField() description = models.TextField() image = models.ImageField() -
Pagination Concept in Django & efficient way to implement over large objects
While learning Django Concepts, I Came across the pagination concept at: https://docs.djangoproject.com/en/2.2/topics/pagination/ I understand that pagination is used for rendering the object fields of the model into discrete pages. In the documentation, the Author provided the following snippet that : contact_list = Contacts.objects.all() paginator = Paginator(contact_list, 25) Which is basically loading all objects of model Contacts and putting them into pagination to limit the per page size to 25. My Question here is: Imagine we have thousands of objects under Contacts model with large TextField, doing Contacts.objects.all() will take some time, In this situation what would be the best efficient way to implement pagination such that pagination happens over Contacts.objects instead of loading all and then passing to Paginator. -
How can I update a field on a foreign key when creating a new object?
Im quite new to Django and im having a problem with a model. class RestaurantAvailability(models.Model): """RestaurantAvailability Model""" DayTime = models.DateTimeField() restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) availability = models.IntegerField(null=True) def __str__(self): """What to show when we output an object as a string.""" restaurant = self.restaurant.name time = self.DayTime return restaurant + " " + str(time) class Reservation(models.Model): """Reservation Model""" name=models.CharField(max_length=100) email=models.CharField(max_length=100) note=models.CharField(max_length=100) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) restaurantAvailability = models.ForeignKey(RestaurantAvailability, on_delete=models.CASCADE) def __str__(self): """What to show when we output an object as a string.""" person = self.name place = self.restaurant.name time = self.restaurantAvailability.DayTime return person + " " + place + " " + str(time) def save(self, *args, **kwargs): """decrement resturant avalability by 1 on create""" if not self.pk: print('|||||||||||||||||||||||||||||||||||||||||') print(self.restaurantAvailability.availability) print('|||||||||||||||||||||||||||||||||||||||||') self.restaurantAvailability.availability -= 1 # decrement resturant avalability by 1 on create print(self.restaurantAvailability.availability) super(Reservation, self).save(*args, **kwargs) When I create a new Reservation I want to decrement Resturant availability by 1. The save method is running because im successfully creating a new reservation, and I even print out the correct availability after decrement. But when I go to the admin panel to see RestaurantAvailability's I don't see any change in the availability. Its as if the availability is not being saved. My question … -
Setup Bitbucket Pipelines to test django app (need to clone in project & test app)
In Bitbucket, I have a 'project' repo that contains my django project level files, and each app for said project is in its own repo. project_repo app_repo other_app_repo I'm trying to configure Pipelines so I can run tests automatically when pushing up to an app repo to ensure tests pass, coverage is acceptable, etc. Currently, to test an app here are my steps: clone in the project cd into project directory virtualenv venv source venv/bin/activate clone in the app (git clone https://bitbucket.com/myapp) cd up one level (back to the project directory) pip install -r requirements.txt pytest myapp My main question: is something like that even possible with Pipelines? Secondly: What would a pipelines file look like to accomplish that? I can't seem to find any good examples online of even accomplishing this. From what I've been reading it seems like the repos all would have to be the full self-contained project & app to accomplish that. -
Is there a way to use search_fields in a compound field in django-admin?
I have a model whose representation is a junction of 4 fields, so its representation is something like MEDICINE - 1 period (2000/1), if I try to filter for example just for MEDICINE it works, but it does not work if my search I put the exact name in the case: MEDICINE - 1 period (2000/1), This my model: def __str__(self): return ( f'{self.term.course_offer.course} - {self.term} ({self.year}/{self.number})' And my admin: class TermYearAdmin(BaseModelAdmin): search_fields = ( 'term__name', 'year', 'term__course_offer__course__nome', ) def get_queryset(self, request): qs = super().get_queryset(request) return qs.select_related( 'term', 'term__course_offer', 'term__course_offer__course', ).order_by('term__course_offer__course__nome', 'year', 'number', 'term__name') -
Working On Projects With Teams. Hoq Do We Integrate Source Control? Bitbucket Or GitHub?
So, i would like to know if there is a way of programming say a website using a couple of libraries and languages but with different people(a team of 5 to be exact) each working on a specific task. How exactly do I achieve this such that at the end of the day, we can merge the contributions of each person to form one complete and error free project? I have used GitHub before with a team of classmates with whom we were working on a PHP class project but pull requests always disorganized the code. We were always lucky because we were always keen to duplicate the original directories of the code before pushing to GitHub. But merging the commits non GitHub always resulted in disorganized stuff. So, I would like some advice on this one. If I am to use GitHub, am i supposed to commit all our code to the master branch? or is everyone supposed to commit to their own branch... and we then pull everything to the master branch? Anyways, I just get so confused by the whole idea and always wonder how teams that code do it because i know large firms use source … -
Celery or urllib3 is redirecting me to https
I have a problem with making requests trough urllib3. So, I'm connecting through proxy and running script trough celery. urllib3 setup: self.http = urllib3.ProxyManager('http://127.0.0.1:24000') Urllib3 request: page = self.http.request('get', self.start_url, headers=self.headers) And after that I see in celery logs something like this: [2019-11-19 16:13:54,038: INFO/ForkPoolWorker-2] Redirecting http://www.olx.pl/nieruchomosci/mieszkania/wynajem/wroclaw/ -> https://www.olx.pl/nieruchomosci/mieszkania/wynajem/wroclaw/ How can I disable this redirect? -
How to set DateTimeField of Django to the value of form input type datetime-local?
So I have a form input datetime-local: <input type="datetime-local" name="dateTime" value="{{object.date_time_collection}}"> And these are fields of that object in the models.py: date_time_collection = models.DateTimeField() date_of_birth = models.DateField() To set the DateField of Django to the value of a form input date, I know you have to do this: <input type="date" name="dateOfBirth" value="{{object.date_of_birth |date:"Y-m-d"}}"> This is what a DateTimeField looks like pgAdmin4: 2018-12-31 10:56:00+08. So how do I convert that to the format of datetime-local? -
Iterate through a QuerySelectMultipleField Flask
I've been trying to use a QuerySelectMultipleField to serve as a checklist for attendance. But I'm not sure about how to extract the data from the form field into the Attendance model for each member present in routes.py. I was unable to iterate through the form field since it threw an error that it's unsubscriptable. Also, the query factory pulls data from a different model (club_user_query() is from "Club" model) than the model I'm trying to insert the form data into ("Attendance" model). Also, I'm not sure if I can label (get_label) from a different model using a many to many relationship (Club to User) in forms.py. form.py def create_club_minutes_form(club, purchase, fund): def club_user_query(): return club.members #Club to User relationship class ClubMinutesForm(FlaskForm): attendance = QuerySelectMultipleField( query_factory=lambda: club_user_query, get_label=lambda a: a.firstname + a.lastname, #pulls from User model widget=ListWidget(prefix_label=False), option_widget=CheckboxInput() ) **other fields omitted for brevity** submit = SubmitField('Submit') return ClubMinutesForm() models.py user_club_assoc_table = db.Table('user_club_assoc_table', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('club_id', db.Integer, db.ForeignKey('club.id'))) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) firstname = db.Column(db.String(20), nullable=False) lastname = db.Column(db.String(20), nullable=False) school = db.Column(db.String(30), nullable=False) schoolid = db.Column(db.String(60), unique=True, nullable=False) email = db.Column(db.String(60), unique=True, nullable=False) password = db.Column(db.String(60), nullable=False) role = db.Column(db.Integer(), nullable=False, default=ROLES['student']) clubs = db.relationship('Club', … -
Stuck while using django-select2 because of small documentation, better use "pure" select2?
A few days ago, I started using django-select2. So far I've had serveral problems (and spent lots of hours) to get sth. simple to work. Maybe because I am not the greatest programmer or maybe because (in my opinion) the documentation really sucks. Sry to the doc-author (I know you did it in your free time), but 2-3 pages more with good examples would have been great. Furthermore I found out that there is only a small community on stackoverflow using django-select2. Therefore I am wondering if I should invest more time on "pure" select2 (especially of its much better documentation). So my question is, where do I have to invest my time, django-select2 or select2? About me: Advanced in django 2x, Intermediate in Javascript -
Changing dango admin's change_list.html
I wanted to customize the django admin and therefore I copy pasted change_list.html from django admin to my project under templates/admin/section4/section4/change_list.html Now I have view and I have written another template : total_review_count.html where I have extended change_list.html In view: change_list_template = 'admin/section4/section4/total_review_count.html' Code : {% extends "admin/change_list.html" %} {% load i18n admin_urls %} {% block result_list %} <footer style="color:blue;"> <p >The total review upto date: {{ total_review_upto_date}}<br> </p> <p>The total review to be updated: {{ total_review_tobe_updated}}<br></p> <p>Total review to be added : {{ total_review_tobe_added }}</p> </footer> {% endblock %} But doing this I override all the other previous stuff and only getting the one in this template. Is this the correct way of overriding change_list.html? How do I get previous stuff ?