Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django web page times out with xxx.objects.all()[:nnn] when nnn > 200
I'm familiar with Python 3 and am learning Django to try and create a web front end which uses information from a MySQL database. I'm using a development server on local machine (http://127.0.0.1:8000/) Package Version ---------------------- ------- Django 2.1.7 mysql-connector-python 8.0.15 I've defined the Customers class in 'models.py' and set up the customers app in Django. The app works perfectly (i.e.: I see output and the web page returned looks as expected. I use the following in the 'views.py' file: # Create your views here. def index(request): customers = Customers.objects.all()[:200] context = { 'title': 'Latest Customers', 'customers': customers } return render(request, 'customers/index.html', context) I get: [26/Mar/2019 21:30:11] "GET / HTTP/1.1" 200 38377 When I change the limit to anything higher than 200, e.g.: customers = Customers.objects.all()[:201] the web page fails to render (times out). Is there a hard limit set somewhere? What would be the best way to find out why the web page is not rendering? -
Django: How to show user specific data
so I'm a beginner at django and I'm trying to implement a login system with my calendar website. What I'm having trouble with is displaying events on the calendar which only the logged in user has posted, instead of seeing all the events in the database on the calendar. views.py from datetime import datetime, timedelta, date from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.views import generic from django.urls import reverse from django.utils.safestring import mark_safe import calendar from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib.auth import logout from django.views.generic import View from .models import * from .utils import Calendar from .forms import EventForm from .forms import UserForm class CalendarView(generic.ListView): model = Event template_name = 'cal/calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) d = get_date(self.request.GET.get('month', None)) cal = Calendar(d.year, d.month) html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) return context def event(request, event_id=None): instance = Event() if event_id: instance = get_object_or_404(Event, pk=event_id) else: instance = Event() form = EventForm(request.POST or None, instance=instance) if request.POST and form.is_valid(): form.save() return HttpResponseRedirect(reverse('cal:calendar')) return render(request, 'cal/event.html', {'form': form}) def login_user(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) … -
how to know table to refrence when creating json web token in django
Am trying to implement json wen token in Django. I have been following tutorial from this source.link I have installed and configured all the necessary requirements. To obtain users token here is the curl example $ curl --request POST \ --url http://localhost:8000/jwt-auth/ \ --header 'content-type: application/json' \ --data '{"username": "myusername", "password": "mypass"}' {"token": "YOUR_JWT_TOKEN"} Here is my code for making call import requests item = { "username": "admin", "password": "admin"} resp1 = requests.post("http://localhost:8000/auth-jwt/", data=json.dumps(item), headers={ "Content-Type":"application/json", "Accept": "application/json" } ) print (resp1.status_code) #print (resp1.content) content = json.loads(resp1.content) print(content) #print(content['status']) My issues: When I run the above code, it returns error non field error: unable to login with provided credentials What does this mean. which table do I have to create to use their credentials. Currently I have users nancy on auth_user table. Consequently, This similar issues has been resolved here but I cannot get it to work Stackoverflow link Can someone tell me what that error above is all about and next step in solving the problem. Thanks -
Django ModelViewSet keep returning empty list from create method
So here is what I am trying to do. I have a meeting and an agenda table. The relation is simple, a meeting can have multiple agenda ( you can take a look at the schema for better understanding ). Meeting Table +----+-------------+ | ID | Title | +----+-------------+ | 1 | Meeting One | | 2 | Meeting Two | +----+-------------+ Agenda Table +----+----------------+---------+ | ID | title | meeting | +----+----------------+---------+ | 1 | Agenda One | 1 | | 2 | Agenda Two | 1 | | 3 | Agenda One | 2 | | 4 | Agenda Another | 2 | +----+----------------+---------+ What I am trying to do is to create a viewset that will allow me to create multiple agenda at once and then return the list of agenda I just created. Here is what I have done so far. urls.py path('update', BulkAgendaCreateView.as_view({ 'get': 'list', 'post': 'create', 'put': 'update', })), view.py class BulkAgendaCreateView(ModelViewSet): queryset = Agenda.objects.all() model = Agenda def get_queryset(self): queryset = Agenda.objects.all() return queryset def get_serializer_class(self): print(self.action) if self.action == 'list' or self.action == 'retrieve': return AgendaListSerializer return AgendaBulkCreateSerializer serializer.py class AgendaListSerializer(ModelSerializer): class Meta: model = Agenda fields = ('id', 'title', 'meeting') class … -
Django ORM relatedmanager adding defaults to filters
Unexpected filters in SQL for related manager. Filters appear to be on fields where I've set a default value in their declaration in the model. We've upgraded from Python 2.7 / Django 1.8 to Python 3.6 / Django 2.1 and have started seeing this unexpected behaviour in our ORM queries. Given the models JobResponseGroup - respondent JobResponse - job_response_group - job_info_request - answer - audofile - videofile - imagefile JobInfoRequest - question_text - internal_question (default=0) print(jrg.jobresponse_set.filter(pk=1).values('id').query) SELECT "job_jobresponse"."id" FROM "job_jobresponse" INNER JOIN "jobInfoRequest" ON ("job_jobresponse"."jobInfoRequest_id" = "jobInfoRequest"."id") WHERE (((NOT ("job_jobresponse"."audioFile" = AND "job_jobresponse"."audioFile" IS NOT NULL) AND "job_jobresponse"."audioFile" IS NOT NULL) OR (NOT ("job_jobresponse"."videoFile" = AND "job_jobresponse"."videoFile" IS NOT NULL) AND "job_jobresponse"."videoFile" IS NOT NULL) OR (NOT ("job_jobresponse"."imageFile" = ) AND "job_jobresponse"."imageFile" IS NOT NULL) OR (NOT ("job_jobresponse"."imageFile2" = ) AND "job_jobresponse"."imageFile2" IS NOT NULL)) AND "jobInfoRequest"."internalQuestion" = 0 AND "job_jobresponse"."group_id" = 16212728 AND "job_jobresponse"."id" = 1 ) If I've just got a single job response group, and I'm looking for its response with and ID of 1, why are all the other bits in there filtering on internalquestion and imageFile, and audioFile, etc. I'm looking for answers in the django release notes, but coming up empty. Hopefully someone who's … -
How can I add python bot script to my Django project
I'm a beginner on Django and Python and plan to make an Instagram bot site with Django. I want to use instabot: https://github.com/instabot-py/instabot.py Now have a few questions: 1. Should I add instabot to my Django packages and use it like a library? 2.where should I write business logic? in the model? -
Empty value for string in model function
First project newbie here - In this model I am trying to create a field that combines first and last names of two people depending if they are the same or not. If the last name is the same, I want it to display as "first_name1 & first_name2 last_name1". It works except that when last_name1 is empty, which will be the case a lot of the time, it displays something like "John & Jane None". I had to specify last_name1 as a string or else I got an error: must be str, not NoneType. How do I do this properly? Also what do I call this type of function in a model...is it a manager? I wasn't sure how to title this post. class Contact(models.Model): first_name1 = models.CharField(max_length=100, verbose_name='First Name', null=True) last_name1 = models.CharField(max_length=100, verbose_name='Last Name', null=True, blank=True) first_name2 = models.CharField(max_length=100, verbose_name='First Name (Second Person)', null=True, blank=True) last_name2 = models.CharField(max_length=100, verbose_name='Last Name (Second Person)', null=True, blank=True) def get_full_name(self): combined_name = '' if self.last_name1 == self.last_name2: combined_name = self.first_name1 + ' & ' + self.first_name2 + ' ' + str(self.last_name1) return '%s' % (combined_name) full_name = property(get_full_name) -
Django custom datadump from two tables to one fixture using call_command
I am trying to write a module in the management/command folder using the call_command to do a custom datadump in Django, where multiple database tables can be combined into a single json file. There is a solution for single files here: How to use call_command with dumpdata command to save json to file But it does not work if you input two database tables. If I do it without Django I would run this in the command line: python manage.py datadump table1 table2 > table.json -
How to override django-allauth signup form when custom user contains FK relation to another model?
I have an abstract user that contains a relation to a Company model by a FK (so each user belongs to a Company) and some additional fields. I have created a CustomSignupForm(SignupForm) that inherits django-allauth SignupForm and takes additional fields like first_name, last_name but I need to expand it so that every time a user does signup I create a Company and then assign the user to (set the FK). This is my forms.py that creates a User with extra fields (but without a company): class CustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') # company_name = forms.CharField(max_length=30, label='Company') def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() return user How do I create a Company object inside def signup(self, request, user) function and set its FK to the created User? -
Django: "order" a queryset based on a boolean field
I want to get all Menù instances in this way: -at the top positions those instances who have my_boolean_field set to True -at the last positions those instances that have my_boolean_field set to False Here is my Menù model and the my query: class Menù(models.Model): id_menù = models.AutoField(primary_key=True) name = models.CharField(max_length=100, unique=True) my_boolean_field = models.BooleanField(default=False) # In my View: my_query_set = Menù.objects.all().order_by('my_boolean_field') I've also searched for a group_by by option but I didn't find anything in Django ORM -
Django Bootstrap + Angular?
I am creating a website with the latest version of Django and Bootstrap 4 with REST. I was wondering if I should use a frontend JS framework like Angular or react but I am not sure if that is the best approach. should I integrate Angular into the site or should i just rely on more traditional frameworks like jquery? The site will be mobile friendly and I will be adding more content and functionallity over time. Im not asking how to do it. just if its the right direction to go. -
Django: How to list products of a category
Trying to get the children of a one to many relationship using the related_name property. What I've tried so far doesn't work: models.py class Category(models.Model): name = models.CharField(max_length=30, unique=True) slug = models.SlugField(max_length=30, unique=True) class Product(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(max_length=30, unique=True) category = models.ForeignKey( Category, related_name='products', on_delete=models.PROTECT, default=1 ) views.py from django.shortcuts import render, get_object_or_404 from Shop.models import Category def product_list(request, slug): category = get_object_or_404(Category, slug=slug) products = category.products.all() context = { 'customCSS': '/static/css/product_list.min.css', 'title': category.name, } return render(request, template, context) product_list.html {% block content %} <ul> {% for product in products %} <li>{{ product.name }}</li> {% endfor %} </ul> {% endblock %} -
Why can't I reference this class from another app in my Django project?
I'm using Django and Python 3.7. I have two applications in my project -- common and mainsite . In common, I have a file "model_utils.py" at the root of my application (right next to models.py). It contains this code class RawCol(Expression): def __init__(self, model, field_name): field = model._meta.get_field(field_name) self.table = model._meta.db_table self.column = field.column super().__init__(output_field=CharField()) def as_sql(self, compiler, connection): sql = f'"{self.table}"."{self.column}"' return sql, [] How do I reference this class from my other application, "mainsite"? I put this at the top of one of my files in mainsite .. from common import RawCol but when I run some tests, I get this error ... ImportError: cannot import name 'RawCol' from 'common' (/Users/davea/Documents/workspace/mainsite_project/common/__init__.py) -
How to update images (like from my computer) to my django-tinymce formField?
I have an HTML page (not django admin) showing a WYSIYYG tinymce field: What i need to do with it is writing some text (it works), upload some images to illustrate the text (it doesn't work) and finally if possible give a class to these uploaded images. This is for a kind of 'page' generator, every content written in the edidor will show up as new page on my webite. the form : class PageForm(forms.Form): name = forms.CharField(max_length=255) content = forms.CharField(widget=TinyMCE()) the model: class Page(models.Model): name = models.CharField(max_length=255, null=False, blank=False, unique=True,) content = models.TextField(null=False, blank=False) slug = models.CharField(max_length=255) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Page, self).save(*args, **kwargs) the html page (basic): <body> {% if error %} <p>Une erreur est survenue</p> {% endif %} {% if action == "update-page" %} <form method="post" action="{% url "page_update" page.slug %}"> {% elif action == "create-page" %} <form method="post" action="{% url 'page_create' %}"> {% endif %} {% csrf_token %} {{ form.as_p }} <input type="submit" value="Enregistrer" /> </form> </body> For the moment when i click on the insert/edit icon it just offers me to give a 'link' and not upload an image. So how do i have to setup my django and/or setup tinymce Thank … -
How to fix: Django calendar not displaying when trying to show user specific data
so I'm a beginner at django and I don't understand why my calendar isn't being displayed. What I'm trying to do is get the user to login and be able to view their own specific events instead of all the events in the database. When I access the /calendar/ url the calendar works fine, however all events in the database are shown. When trying to access the calendar through /login_user/ url, the calendar is not displayed, only the buttons. views.py from datetime import datetime, timedelta, date from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.views import generic from django.urls import reverse from django.utils.safestring import mark_safe import calendar from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib.auth import logout from django.views.generic import View from .models import * from .utils import Calendar from .forms import EventForm from .forms import UserForm class CalendarView(generic.ListView): model = Event template_name = 'cal/calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) d = get_date(self.request.GET.get('month', None)) cal = Calendar(d.year, d.month) html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) return context def event(request, event_id=None): instance = Event() if event_id: instance = get_object_or_404(Event, pk=event_id) else: instance = Event() form = EventForm(request.POST or … -
adding context variables in python logs
I am developping a python application and I would like to include a very detailed stack info in case of exceptions, including all local variables. This is what is done in Django I have set up the Python (in Python 3) log and with logger.debug (' error in knitting ',exc_info = True, stack_info = True, extra = dicte) I get the stack trace but not the list of internal variables and their content. How can I do this? what I would like to get is th following: ▼ Local vars Variable Value args () kwargs {'tech_number': 108} name 'get' self -
Previous post list inside of detail view
In my PostDetailView I'm trying to display previous posts for the Game that is related to the Post in the PostDetailView. I'm unsure of how to filter Post by the game in the PostDetailView class Game(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True) cover = models.ImageField(upload_to='cover_images') class Post(models.Model): author = models.ForeignKey(User, models.SET_NULL, blank=True, null=True, ) # If user is deleted keep all updates by said user article_title = models.CharField(max_length=250, help_text="Use format: Release Notes for MM/DD/YYYY") content = models.TextField() date_published = models.DateTimeField(db_index=True, default=timezone.now, help_text="Use date of update not current time") game = models.ForeignKey(Game, on_delete=models.CASCADE) Views.py class PostDetailView(DetailView): model = Post -
Ubuntu / Django / Logging / PermissionError: [Errno 13] Permission denied
Ubuntu 18.04.1 using the Bitnami Django Stack: bitnami-djangostack-2.1.5-1 I get this error when starting apache service: [16:21:20.028270 2019] [wsgi:error] Traceback (most recent call last): [16:21:20.028373 2019] [wsgi:error] File "/opt/djangostack-2.1.5-1/python/lib/python3.7/logging/config.py", line 562, in configure [16:21:20.028395 2019] [wsgi:error] handler = self.configure_handler(handlers[name]) [16:21:20.028421 2019] [wsgi:error] File "/opt/djangostack-2.1.5-1/python/lib/python3.7/logging/config.py", line 735, in configure_handler [16:21:20.028438 2019] [wsgi:error] result = factory(**kwargs) [16:21:20.028463 2019] [wsgi:error] File "/opt/djangostack-2.1.5-1/python/lib/python3.7/logging/handlers.py", line 147, in __init__ [16:21:20.028479 2019] [wsgi:error] BaseRotatingHandler.__init__(self, filename, mode, encoding, delay) [16:21:20.028504 2019] [wsgi:error] File "/opt/djangostack-2.1.5-1/python/lib/python3.7/logging/handlers.py", line 54, in __init__ [16:21:20.028520 2019] [wsgi:error] logging.FileHandler.__init__(self, filename, mode, encoding, delay) [16:21:20.028545 2019] [wsgi:error] File "/opt/djangostack-2.1.5-1/python/lib/python3.7/logging/__init__.py", line 1092, in __init__ [16:21:20.028562 2019] [wsgi:error] StreamHandler.__init__(self, self._open()) [16:21:20.028601 2019] [wsgi:error] File "/opt/djangostack-2.1.5-1/python/lib/python3.7/logging/__init__.py", line 1121, in _open [16:21:20.028618 2019] [wsgi:error] return open(self.baseFilename, self.mode, encoding=self.encoding) [16:21:20.028666 2019] [wsgi:error] PermissionError: [Errno 13] Permission denied: '/opt/djangostack-2.1.5-1/apps/django/django_projects/myproject/static/logs/ca.myproject.app.cleaner.log' [16:21:20.028701 2019] [wsgi:error] [16:21:20.028716 2019] [wsgi:error] The above exception was the direct cause of the following exception: [16:21:20.028729 2019] [wsgi:error] [16:21:20.028753 2019] [wsgi:error] Traceback (most recent call last): [16:21:20.028832 2019] [wsgi:error] File "/opt/djangostack-2.1.5-1/apps/django/django_projects/myproject/myproject/wsgi.py", line 19, in <module> [16:21:20.028851 2019] [wsgi:error] application = get_wsgi_application() [16:21:20.028886 2019] [wsgi:error] File "/opt/djangostack-2.1.5-1/apps/django/lib/python3.7/site-packages/Django-2.1.5-py3.7.egg/django/core/wsgi.py", line 12, in get_wsgi_application [16:21:20.028903 2019] [wsgi:error] django.setup(set_prefix=False) [16:21:20.028928 2019] [wsgi:error] File "/opt/djangostack-2.1.5-1/apps/django/lib/python3.7/site-packages/Django-2.1.5-py3.7.egg/django/__init__.py", line 19, in setup [16:21:20.028944 2019] [wsgi:error] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [16:21:20.028968 2019] [wsgi:error] … -
Serializing raw values from postgres in a custom django field
I'm trying to create a custom field to be able to store BC dates in my database. It will take a Julian Date tuple as input and convert this to a JDN through the jdcal lib. The issue is that python's built-in datetime module doesn't support BC dates, so I cannot parse db values through it. I think I've gotten my field to save correctly, but I'm not sure how to serialize a raw postgres value into my own representation, probably through a tuple of (year, month, day) to keep in line with the jdcal library. from jdcal import gcal2jd class JDNField(models.DateField): description = "A field to save JDN values as postgres `date` types" def get_db_prep_value(self, value, *args, **kwargs): if value is None: return None jd = gcal2jd(*value)[0] + gcal2jd(*value)[1] + 0.5 return f'J{jd}' def to_python(self, value): if value is None: return None return # should it go here? def from_db_value(self, value, expression, connection, context): return self.to_python(value) -
IntegrityError: NOT NULL constraint failed Django
when I am trying to post any image though API its tells "IntegrityError: NOT NULL constraint failed" . here is my django app krisi_image_problem/model.py from django.db import models from krisi_user.models import krisi_user class problem_image(models.Model): full_name = models.CharField(max_length=250) email = models.CharField(max_length=100) image = models.ImageField(upload_to='images') phone = models.CharField(max_length=50) krisi_user = models.ForeignKey(krisi_user,on_delete= models.CASCADE,null=True) def __str__(self): return self.full_name here is my django app krisi_image_problem/url.py from django.urls import path , include from . import views from rest_framework import routers #image_router = routers.DefaultRouter('api/image/v1.0',views.problem_image_view) router = routers.DefaultRouter() router.register('image',views.problem_image_view) urlpatterns = [ path('',include(router.urls)), ] here is my django app krisi_image_problem/views.py from django.shortcuts import render from rest_framework import viewsets from .models import problem_image from .serializers import problem_image_serializer class problem_image_view(viewsets.ModelViewSet): queryset = problem_image.objects.all() serializer_class = problem_image_serializer here is my django app krisi_image_problem/serializers.py from rest_framework import serializers #from rest_framework.exceptions import ValidationError from .models import problem_image class problem_image_serializer(serializers.ModelSerializer): class Meta: model = problem_image fields = ('full_name','email','image','phone') the project/urls.py from django.contrib import admin from django.urls import path , include from krisi_image_problem.urls import router from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('',include('krisi_user.urls')), #path('',include('krisi_image_problem.urls')), path('api/', include('krisi_image_problem.urls')), ]+static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT) AND the settings.py is """ Django settings for krisi_doctor project. Generated by 'django-admin startproject' using Django 2.1.7. For more information … -
How to configure the django forms to sell custom products?
I have just started learning Django and have a simple shopping cart setup following the tutorial by Antonio Mele in his book "Django 2 by Example". I can select products and then the quantity will be an option. This works fine for generic products. What if I have custom products such as engraved pens? The buyer selects quantity of 3 but he wants different names engraved on the pens. How would I do that? Here is the code for the forms.py that controls the quantity. from django import forms PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 11)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) and the relevant part of the HTML template looks like {% for item in cart %} {% with product=item.product %} <tr> <td>{{ product.name }}</td> <td> <form action="{% url "cart:cart_add" product.id %}" method="post"> {{ item.update_quantity_form.quantity }} {{ item.update_quantity_form.update }} <input type="submit" value="Update"> {% csrf_token %} </form> </td> <td><a href="{% url "cart:cart_remove" product.id %}">Remove</a></td> <td class="num">${{ item.price }}</td> <td class="num">${{ item.total_price }}</td> </tr> {% endwith %} {% endfor %} -
How to properly build json web token in python
Am trying to build Json web token in python django using pyjwt library by referencing suggestion by Madhu_Kiran_K from stackoverflow link In the code below, Am trying Generates a JSON Web Token that stores this user's ID, email and has an expiry date set to 2 days into the future. I can succesfully encode and decode the token to get all the required users information and token expiration time. My Requirement Now: 1.)Please how do I validate and ensure that the token sent by client is still valid and hence not tampered. 2.)how to check for expiration time and print a message. Here is what I have done to that effect #check if the token were tampered if content['user_id'] =='' or content['email'] == '': print("Invalid Token") else: print("Token is still valid") #check if token has expired after 2 days if content['exp'] > dt: print("Token is still active") else: print("Token expired. Get new one") The time expiration checking returns error message not supported between instances of int and datetime.datetime. What is the proper way to validate. Thanks below is the full code #!/usr/bin/python import sys import re import json from datetime import datetime, timedelta import jwt #https://www.guru99.com/date-time-and-datetime-classes-in-python.html #timedelta(days=365, hours=8, minutes=15) #'exp': … -
Atributte models.TextField() error "OperationalError at /"
so im new in Django and im triyng to setup a simple blog. Here u can check all files. So my problem is: when I run the Django server and try to view my site (the template is available here ) i get this error message that is apparently related to models.TextField() attribute in my post model. Could someone help me solve this error? Thank you very much. -
django multiple many to many fields with same relationship on model
Can the same many to many relationship exist on a model multiple times (with different field names for the field)? I can't seem to get this to work when doing the migration as python complains about the relationship already existing when I try to duplicate it to a different name. -
I try to add loading image during the file conversion process
So i am using a script that hide the content when we click on upload image and show the please wait gif file, but it hide the content successfully but no able to show the new content I am little new to css <script type="text/javascript">// <![CDATA[ function loading(){ $("#content").hide(); $("#loading").show(); } // ]]></script> div#loading { width: 35px; height: 35px; display: none; background: url(/static/loadingimage.gif) no-repeat; cursor: wait; } <div style="text-align:center"> <div class="loading" ></div> <div id="content"> <h2>Upload</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="document"> <button type="submit" value='Next' name='Next' onclick="loading();">Upload file</button> </form> </div> </div>