Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I force users to enable full screen while taking the test using javascript
I am developing a quiz app for my academic project. whenever a user attempts a quiz, he must enable fullscreen mode before taking the test. If he do so then only he can attempt the quiz. If he disable the full screen mode by pressing esc key then a warning message should be shown and he cannot attempt the quiz until he reenables full screen mode. -
django ORM join two model on a foreign key
The title might be misleading, I'm not sure on how to express my problem I have two models declared this way: class Record(models.Model): # autogen id as primary key name = models.ForeignKey(Product, on_delete=models.DO_NOTHING) value = models.FloatField() date = models.DateTimeField() class Integration(models.Model): # autogen id as primary key action = models.FloatField() on_record = models.ForeignKey(Record, on_delete=models.DO_NOTHING) I have one Record per hour per day on an entire year, thus 24*365. For each Record, there are exactely ten (10) Integrations, each having their distinct action. What I need is a QuerySet on Record that has an "extra column" with the average of the related 10 Integration's actions. So Record | id| name | value | date | |---|------|-------|------| | 1 | A | 120.00| 2020-01-01 00:00 | | 2 | B | 85.00 | 2020-01-01 01:00 | Integration | id | action | on_record | |-----|--------|-----------| | 0x1 | 7.00 | 1 | | 0x2 | 2.00 | 1 | | 0x3 | 9.00 | 1 | | ... | ... | ... | | 0x10 | 8.41 | 1 | | 0x11 | 8.99 | 2 <-- next Record | What I need id name value date integration_avg_action 1 A 120.00 2020-01-01 … -
'User' object has no attribute 'is_staff'
I am working with user authentication system where I created a user registration model using AbstractBaseUser. then I create super User using terminal . But when I go the admin and write email and password there . It gives me the error that: 'User' object has no attribute 'is_staff' My models.py file is: from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager SUBJECT_CHOICES = ( ('math','Math'), ('physics','Physics'), ('chemistry','Chemistry'), ) class UserManager(BaseUserManager): def create_user(self, email, full_name=None, password=None, is_staff=False, is_admin=False): if not email: raise ValueError("User must have an email") if not password: raise ValueError("User must have a password") user_obj = self.model(email=self.normalize_email(email), full_name=full_name) user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,full_name=None,password=None): user = self.create_user(email, full_name=full_name,password=password) return user def create_superuser(self,email, full_name=None,password=None): user = self.create_user(email, full_name=full_name, password=password) return user class User(AbstractBaseUser): full_name = models.CharField(max_length=255, blank=True, null=True) sur_name = models.CharField(max_length=255, blank=True, null=True) email = models.EmailField(max_length=255 ,unique=True) choose_subject = models.CharField(choices=SUBJECT_CHOICES , max_length=100) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) time_stamp = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] object = UserManager() def __str__(self): return self.full_name my forms.py file is: class RegisterForm(forms.ModelForm): # A form for creation new user included all all the required fields including repeated password password1 = forms.CharField(label='Enter Password' , widget=forms.PasswordInput ) password2 … -
Django auth_views.PasswordResetView keep sending raw html email
I'm trying to send a custom email template with the reset token. But it keeps sending raw HTML no matter what I do. I have previous experience of doing exactly the same thing without any problem with the Django and Django rest framework. Here's how I did it, urls.py ... path('password_reset', auth_views.PasswordResetView.as_view(template_name='registration/password_reset_form.html', html_email_template_name='registration/html_password_reset_email.html', email_template_name = 'registration/password_reset_email.html, ), name='password_reset' ), folder structure ... templates |-- registration |-- html_password_reset_email.html |-- password_reset_email.html |-- ... ... Email template {% load i18n %}{% autoescape off %} {% load static %} <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> @media screen and (max-width: 720px) { body .c-v84rpm { width: 100% !important; max-width: 720px !important; } body .c-v84rpm .c-7bgiy1 .c-1c86scm { display: none !important; } body .c-v84rpm .c-7bgiy1 .c-f1bud4 .c-pekv9n .c-1qv5bbj, body .c-v84rpm .c-7bgiy1 .c-f1bud4 .c-1c9o9ex .c-1qv5bbj, body .c-v84rpm .c-7bgiy1 .c-f1bud4 .c-90qmnj .c-1qv5bbj { border-width: 1px 0 0 !important; } body .c-v84rpm .c-7bgiy1 .c-f1bud4 .c-183lp8j .c-1qv5bbj { border-width: 1px 0 !important; } body .c-v84rpm .c-7bgiy1 .c-f1bud4 .c-pekv9n .c-1qv5bbj { padding-left: 12px !important; padding-right: 12px !important; } body .c-v84rpm .c-7bgiy1 .c-f1bud4 .c-1c9o9ex .c-1qv5bbj, body .c-v84rpm .c-7bgiy1 .c-f1bud4 .c-90qmnj .c-1qv5bbj { padding-left: 8px !important; padding-right: 8px !important; } body .c-v84rpm .c-ry4gth .c-1dhsbqv { display: none !important; … -
Adding groups in form django | 'RegisterUserForm' object has no attribute 'groups'
SubjectTeacher model where SubjectClass and TeacherUser has been passed. -
How to find average datetime in a object?
I created an approval system. I have an ApprovalProcess model. This model has end_date and begin_date. And end_date - beginning_date is duration time. I have several ApprovalProcess models I want to find what is the total average duration time of all ApprovalProcess objects. I cannot find the difference between end_date and begin_date. It gives an error: TypeError at /approval/logs unsupported operand type(s) for +: 'int' and 'datetime.timedelta' How can I do it? models.py class ApprovalProcess(models.Model): ... begin_date = models.DateTimeField(null=True) end_date = models.DateTimeField(null=True) ... views.py def log_records(request): ... approval_list = ApprovalProcess.objects.filter(user_id=request.user) delta = 0 approval_list = ApprovalProcess.objects.filter(customer__company=request.user.company) for approval_object in approval_list: delta = abs((approval_object.end_date - approval_object.begin_date).days) ... -
viewing all emails with javasript in django
Im trying to show all objects from Emails model on page. Im trying to make it by creating new elements. I would like the solution to be using javascript. I cant find what the problem may be.I tried inspecting the code, and the elements created with javascript were not there. And yes, there are objects in my Emails module. views.py: import json from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.db import IntegrityError from django.http import JsonResponse from django.shortcuts import HttpResponse, HttpResponseRedirect, render from django.urls import reverse from django.views.decorators.csrf import csrf_exempt from .models import User, Email def index(request): # Authenticated users view their inbox if request.user.is_authenticated: return render(request, "mail/inbox.html") # Everyone else is prompted to sign in else: return HttpResponseRedirect(reverse("login")) @csrf_exempt @login_required def compose(request): # Composing a new email must be via POST if request.method != "POST": return JsonResponse({"error": "POST request required."}, status=400) # Check recipient emails data = json.loads(request.body) emails = [email.strip() for email in data.get("recipients").split(",")] if emails == [""]: return JsonResponse({ "error": "At least one recipient required." }, status=400) # Convert email addresses to users recipients = [] for email in emails: try: user = User.objects.get(email=email) recipients.append(user) except User.DoesNotExist: return JsonResponse({ "error": f"User with email … -
I'm trying to convert a HTML template to PDF with pdfkit but the data from the template not loaded in the pdf
views.py def resume(request,id): user_profile=Profile.objects.get(pk=id) template= loader.get_template("Resume/profile.html") html= template.render({'user_profile':user_profile}) options={ 'page-size':'Letter', 'encoding' : 'UTF-8', } pdf= pdfkit.from_string(html,False,options) response= HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition']= 'attachment' return response profile.html {% extends "Resume/layout.html" %} {% block body %} <h2>{{ user_profile.full_name }}</h2> <h2>{{ user_profile.job_title }}</h2> <hr> <h2>{{ user_profile.email }}</h2> <h2>{{ user_profile.phone }}</h2> <h2>{{ user_profile.home_adress }}</h2> <hr> <p>Summary</p> <p> {{ user_profile.work_experience }}</p> <p> {{ user_profile.skills }}</p> <hr> <p>Education</p> <ul> <li> {{user_profile.diplomes}} </li> </ul> <hr> {% endblock %} ![this is th pdf i get ][1] [1]:( https://i.stack.imgur.com/PXlt3.png) I'm trying to convert a HTML template to PDF with pdfkit but the data from the template not loaded in the pdf can anyone help me with this, i don't know what the problem is -
Add a class field in Django <UL>
<ul> {% topic_menu_full federation "Federation" %} {% topic_menu_full our-school "Our School" %} {% topic_menu_full learning "Learning" %} {% topic_menu_full children "Children" %} {% topic_menu_full parents "Parents" %} </ul> I want to add class to only the last one in the list, for example .red the last one. -
In production mode, react helmet async is not working and How react helmet async works?
Recently, I started playing with meta tags in react. After some research, I found that react-helmet-async is the best library to set meta tags for each page. however, I wanted to want set meta tags for few pages conditionally. I setup metatags for two pages differently, take a look... index.js ReactDOM.render( <React.StrictMode> <HelmetProvider> <App/> </HelmetProvider> </React.StrictMode>, document.getElementById('root') ); pageOne.jsx componentDidMount(){ axios.get('/getTrack/',{params: {id: this.props.match.params.id}}) .then((res) => this.setState({trackData: res.data, isLoading: false})) .catch((err) => console.log(err)) } render() { return ( this.state.isLoading? <div className="page-loader"> <Helmet> {/* Page sittings */} <meta charset="utf-8" /> <meta name="theme-color" content="#000000" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> {/* Primary Meta Tags */} <title>Loading...</title> </Helmet> </div> : <div className="main-page"> <Helmet> {/* Page sittings */} <meta charset="utf-8" /> <meta name="theme-color" content="#000000" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> {/* Primary Meta Tags */} <title>{this.state.trackData.title}</title> <meta name="title" content={this.state.trackData.title}/> <meta name="description" content={this.state.trackData.desc}/> {/* Open Graph / Facebook */} <meta property="og:type" content="website"/> <meta property="og:url" content="https://example.com/"/> <meta property="og:title" content={this.state.trackData.title}/> <meta property="og:description" content={this.state.trackData.desc}/> <meta property="og:image" content="/logo192.png"/> {/* Twitter */} <meta property="twitter:card" content="summary_large_image"/> <meta property="twitter:url" content="https://example.com/"/> <meta property="twitter:title" content={this.state.trackData.title}/> <meta property="twitter:description" content={this.state.trackData.desc}/> <meta property="twitter:image" content="/logo192.png"/> </Helmet> </div> ) } pageTwo.jsx <Helmet> {/* Primary Meta Tags */} <title>XYZ</title> <meta charset="utf-8" /> <meta name="title" content="xyz"/> <meta name="theme-color" content="#000000" /> <meta name="viewport" … -
Expression contains mixed types: DecimalField, IntegerField. You must set output_field
I am trying execute a query with multiple annotates and i keep getting the output_field required error where as i am already writing that. I have tried to change the output to decimal but does not work. Any idea? My targeted code count = ShareAllocation.objects.filter(session_key=self.storage.request.session.session_key). \ values('share_type__id', 'share_type__code', 'share_type__type'). \ annotate(share_count=Sum('share_type__id')). \ annotate(total_shares=Sum('number_of_shares')). \ annotate(total_paid=ExpressionWrapper(F('amount_paid') * F('total_shares'), output_field=models.IntegerField)).\ annotate(total_unpaid=ExpressionWrapper( F('amount_unpaid') * F('total_shares'), output_field=models.IntegerField ) ).\ count() if count == 0: return False else: return True -
I want to send back a list and a dictionary in django for my site in php
I want to send back a list and a dictionary in django for my site in php,I have a python script that flips a list and an dictionary exemple: list=[ [name,ip,country][name2,ip2,country2] ] dictionary={"name":"A","name2":"B"} I want to put them in jango format and use them in my php code. thanks you!! -
Filtering of user related data in Django / DRF
I am working on a Django application with the Django Rest Framework. I try to do things the Django/DRF way. It is already a non-trivial service, so I have extracted the relevant details from the code to show here. I have the following apps: Report Cluster User The User model, serializer, and view can be considered to be standard for this question. Report class Report(models.Model): slug = models.CharField(unique=True, max_length=100, blank=False, null=False) name = models.CharField(max_length=100, blank=False) clusters = models.ManyToManyField(Cluster, blank=True, related_name='report_clusters') users = models.ManyToManyField(User, blank=True, related_name='report_users') class ReportSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Report fields = ("slug", "url", "name", "clusters") read_only_fields = ('slug', 'clusters') lookup_field = "slug" extra_kwargs = { 'url': {'lookup_field': 'slug'}, 'clusters': {'lookup_field': 'slug'}, } class ReportViewSet(viewsets.ModelViewSet, LoginRequiredMixin): queryset = Report.objects.all() serializer_class = ReportSerializer permission_classes = (permissions.IsAuthenticated, IsAdminUserOrReadOnly) lookup_field = "slug" def get_queryset(self): """Only show user related items.""" return Report.objects.filter(users__id=self.request.user.id) Cluster class Cluster(models.Model): slug = models.CharField(unique=True, max_length=100, blank=False, null=False) name = models.CharField(max_length=100, blank=False, unique=True) users = models.ManyToManyField(User, blank=True) observers = models.ManyToManyField(User, blank=True, related_name='cluster_observer') class ClusterTreeSerializer(serializers.HyperlinkedModelSerializer): # children = serializers.SerializerMethodField() class Meta: model = Cluster fields = ('url', 'slug', 'name') read_only_fields = ('url', 'slug') lookup_field = "slug" extra_kwargs = {'url': {'lookup_field': 'slug'}} class ClusterViewSet(viewsets.ModelViewSet, LoginRequiredMixin): queryset = Cluster.objects.all() serializer_class = ClusterTreeSerializer … -
Could not translate host name “postgres” to address
i a working with django, docker and postgree as db , when i try to compile my project with: docker-compose up --build, i got this error "Could not translate host name “postgres” to address". Please Need help ? -
Favicon not loading in Django
I can't seem to get my favicon to load at all, I have the image in my static folder, all other images load fine on both local and production environments, and I can load the favicon as an image no problem. It just doesn't load as the actual favicon. I have the code to load favicon in the head tag (and all other static files that are loaded there are working, such as style sheets and meta tags). I have {% load static %} at the top of the page as well. Here is my code in the tag which attempts to set the favicon: <link rel="icon" type="image/png" href="{% static 'stockdeepdive/images/favicon.ico' %}"> <link rel="icon" type="image/png" sizes="192x192" href="{% static 'stockdeepdive/images/android-icon-192x192.png' %}"> <link rel="icon" type="image/png" sizes="32x32" href="{% static 'stockdeepdive/images/favicon-32x32.png' %}"> <link rel="icon" type="image/png" sizes="96x96" href="{% static 'stockdeepdive/images/favicon-96x96.png' %}"> <link rel="icon" type="image/png" sizes="16x16" href="{% static 'stockdeepdive/images/favicon-16x16.png' %}"> The images are all located within static folder, then stockdeepdive folder, then finally images folder. All other images are working good. Im not getting any errors in console, but I'm also not seeing any "GET" request for the favicons. Any help greatly appreciated, I've spent hours trying to figure this out. -
What are the dependencies for django-allauth python:3.8.3-alpine Dockerfile
I have a Dockerfile, docker-compose.yml, requirements.txt defined below for a django project. The Dockerfile uses python:3.8.3-alpine and the docker-compose.yml have a db service that uses postgres:12.0-alpine image. I made sure that the dependencies are defined in the Dockerfile as required. However, it seems to me that django-allauth require extra dependencies. I have tried for days to fix this issue but get an error that says This package requires Rust >=1.41.0. ERROR: Failed building wheel for cryptography. I haved pasted the whole error for reference sake. Any help will be much appreciated. Thanks in advance. #requirements.txt Django>=3.1.5,<3.2.0 gunicorn>=20.0.4,<20.1.0 psycopg2-binary>=2.8,<2.9 Pillow>=8.1.0,<8.2.0 django-allauth>=0.44.0,<1.0.0 #Dockerfile # pull official base image FROM python:3.8.3-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev \ && apk add libffi-dev libressl-dev \ && apk add --no-cache jpeg-dev zlib-dev libjpeg # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy entrypoint.sh COPY ./entrypoint.sh . # copy project COPY . . # run entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] #docker-compose.yml version: '3.7' services: web: build: ./app command: python manage.py runserver 0.0.0.0:8000 volumes: - … -
Embed matplotlib bar graph in html page
I am trying to embed a matplotlib bar graph in html page. I have tried almost everything. here's my code- views.py- def result(request) plt.bar(x,h) plt.xlabel("Personality") plt.ylabel("course") plt.show() return render(request,'result.html') -
Django doesn't read JWT token
My django backend use JWT token for user auth. I store recieved token in 'Authtorization' header using axios. Everything works well. But I noticed problem when I open any link in new tab (ctrl+click), after this I get on to auth page but I still have the token in my header. Why does it happen? -
Empty space below navbar in header
I'm creating a web app using Python - Django. I'm currently working on the front-end part and below my navbar in the header section is a ton of free white-space that I can't seem to get rid off. Also I want my background image behind the whole page, can't seem to get my head around how to do that. It's always either above the body or below it. Any clues? My html with bootstrap: <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors"> <meta name="generator" content="Jekyll v3.8.5"> <link rel="stylesheet" type="text/css" href="{% static 'styles/stylesheet.css' %}"> <link rel="icon" href="{% static 'images/favicon.ico' %}"> <title> Milk - {% block title_block %}Milk Students{% endblock %} </title> <!-- Bootstrap core CSS --> <link href="https://getbootstrap.com/docs/4.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <!-- Custom styles for this template --> <link href="https://getbootstrap.com/docs/4.2/examples/dashboard/dashboard.css" rel="stylesheet"> </head> <body> <header> <div class ="container"> <!-- Navbar --> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark py-1"> <a class="navbar-brand p-2" href="{% url 'milk_app:home' %}">MilkStudents</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav ml-auto" > <li class="nav-item"><a class="nav-link" href="{% url 'milk_app:home' %}">Home</a></li> … -
Get All checkbox value selected , Table row wise using AJAX : DJANGO
I have code which should select all rows from a table whose checkbox is selected . So first i will describe my table structure . So here there will be many rows , so i should select which server i need and which operation i should perform . So if i have two server ABC and BCD , if i want to perform start operation for ABC and Stop for ABC , i should select respective servers from first checkbox and associated operations from the checkbox on same row as the server name . and i should pass all values row wise to views.py for performing other operations . so currently I wrote a code , which give me the value even if i didn't checked the checkbox . And am not able to figure out issue . Can any anyone help me. this is my AJAX call : $("[name=ButtonSubmit]").click(function(){ var myarrayServer = []; var myarrayStart = []; var myarrayRestart = []; var myarrayStop =[]; var message = " "; $(".form-check-input0:checked").each(function() { var row = $(this).closest("tr")[0]; message += row.cells[1].innerHTML; message += " " + row.cells[2].innerHTML; message += " " + row.cells[3].innerHTML; message += " " + row.cells[4].innerHTML; var checkedValue = … -
How to execute an if statement in ManyToMany Field in Django
I am trying to check if voter already exists in database and execute a different command id the voter exists or not but my if statement returns False if there is a match in the database. My views is: def vote(request, position_id, voting_id): voter = Voter.objects.filter(pk=voting_id) print(voter) position = get_object_or_404(Position, pk=position_id) try: selected_choice = position.candidate_set.get(pk=request.POST['choice']) except (KeyError, Candidate.DoesNotExist): return render(request, 'landing/detail.html', { 'position': position, 'error_message': "You didn't select a Choice." }) else: print(selected_choice.voted_by.all()) if voter in selected_choice.voted_by.all(): print("THIS DOES") else: print("THIS DOESN'T") # selected_choice.votes += 1 # selected_choice.save() return HttpResponseRedirect(reverse('results', args=(position.id,))) When I run this, I have some print statements and it prints; <QuerySet [<Voter: BIS/2019/12345>]> <QuerySet [<Voter: BIT/2020/54321>, <Voter: BIT/2019/12345>, <Voter: BIT/2018/12345>, <Voter: BIS/2020/54321>, <Voter: BIS/2019/12345>]> THIS DOESN'T I was hoping it will print 'THIS DOES' since the voter is in the selected_choice. What might I be doing wrong -
Django- ValueError: signal only works in main thread
is it at all possible to execute Django's call_command code within or alongside Django's signals? What I have tried so far is use a ModelForm to try and update a Model class using a function based views like so: # models.py class Foo(models.Model): ... many = models.ManyToManyField("FooMany") class FooMany(models.Model): ... many = models.CharField(choices=CHOICE, max_length=2) Now, every request to update this triggers a signal that's designed to run specific tests using Django's call_command # signals.py import ntpath from my_dir import execute @receiver(m2m_changed, sender=Executor.path.through) def run_test(sender, instance, action, **kwargs): files = instance.path.all() base = [ntpath.basename(str(f)) for f in files] for file in base: execute(file) # execute function comes next # my_dir.py def execute(file): with open("executor/results/output", "w") as FILE: call_command("test", f"executor.tests.{test}", verbosity=3, interactive=False, stdout=FILE) However, these all yield a server 500 error. Further investigation yielded a ValueError: signal only works in main thread, the reason I asked if it is possible to do it this way and if not could you suggest a different approach. Thank you. -
django model's inheritance
I want to have two registration type. for example : employee and employer type. i want two different form. i override AbstractUser and after i use this class (inheritance) class User(AbstractUser): age=models.BooleanField(default=True) class employee(User): is_employee=models.BooleanField(default=True) ser=models.BooleanField() sag=models.CharField(max_length=1) class Meta: verbose_name="employee" class employer(User): is_employer=models.BooleanField(default=True) address=models.CharField(max_length=100) but when i save employee or employer class also created User class. can i do when i save only employee save just that and not User -
django static png not found
when i go to localhost/static/images.png it shows image cannot be found i have added STATIC_URL = '/static/' staticfile_dir = [static_dir, ] please ignore .html and .css and .js file is polls folder already tried pycharms default path and base_dir then changed it to os.join also tried adding static file finder -
How to capture dropdown selection into a view for conversion to excel
Hello fellow learned friends. I'd like to add a filter to a model query from a dropdown selection before converting the results to excel for download. I can't get it right since I don't know how to capture the dropdown selected item into the view. How do I get it working?? def convert_to_excel(file_name, columns, values): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="{}.xls"'.format(file_name) wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet(file_name.capitalize()) # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() for row in values: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response def archive_to_excel(request): mark_list = Marks.objects.filter(school=request.user.school).annotate(total = \ F("eng") + F("kis") + F("mat") + F("che") + F("phy") + F("bio") + F("cre")+ F("ire")+ \ F("hre") + F("geo") + F("his") + F("agr") + F("hsc") + F("bst")+ F("mus")+ F("ger")+ F("fre"))\ .order_by('-total').annotate(mean = F('total')/15).values_list('student__name',\ 'student__adm', 'student__form__name', 'student__stream__name', 'student__kcpe','eng','kis','mat','che','phy','bio','cre','ire','hre','geo',\ 'his','agr','total','mean').order_by('-id') columns = [('name'), ('adm'),('form'),('stream'), ('kcpe'), ('eng'), ('kis'), ('mat'), ('che'), ('phy'), ('bio'), ('cre'),\ ('ire'), ('hre'), ('geo'), ('his'), ('agr'),('total'),('mean') ] return convert_to_excel("Marks", columns, mark_list)