Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to import something from one directory above in a Django project?
In my Django project, I have split models. The project directory kinda looks like this: myproject/ app1/ validators.py views.py __init__.py models/ __init__.py model1.py model2.py And of course, the models work properly thanks to this: #myproject/app1/models/__init__.py: from .model1 import Model1 from .model2 import Model2 Anyway, in my model1.py module, I want to import a validator from the validators.py module. But as you can see, its one directory above. How can I do this? Preferably, I would want a solution that works in all types of filesystems. Thanks for any answers. -
Why is my base navbar doesn't show the groups that I have at /groups/?
I am trying to do a dropdown list in the base navigation bar of the groups that are available inside the /groups/ which is a ListView. The navigation bar shows the groups only when I am at /groups/ on my website. in views.py at Groups application class ListGroups(generic.ListView): model = Group context_object_name = 'All_Groups' def get_queryset(self): return Group.objects.all() in the main templates, base.html {% for group in All_Groups %} <li> <a href='{% url "groups:single" slug=group.slug %}' class='my-dropdown-list' style='color: white !important; background-color: inherit !important;'> {{group.name}} </a> </li> {% endfor %} I expect it to iterate to all the available groups that inherit from the Group class, but it only does that when I am at the directory of Groups. -
How to update a field on it's own in few days?
I am working on a project where I am accepting payments from users. The due date is 30 days from the payment date . Initially the is_due field is false but I want it to change to true without updating manually when due date is just seven days away. I have got no solution even after looking up everywhere. I am stuck with this problem. Please Help me and tell me a way to do this. Thanks. models class Payment(models.Model): username = models.ForeignKey(UserProfile,on_delete = models.CASCADE, related_name='name') amount = models.IntegerField() date = models.DateField(blank=False, default = datetime.datetime.now()) due_date = models.DateField() payment_mode = models.CharField(max_length=50, choices=PaymentModes,null=True,blank=True) collected_by = models.ForeignKey(UserProfile,on_delete = None, related_name='collected_by') is_due = models.BooleanField(default = False) def __str__(self): return self.username.user.username def save(self, *args, **kwargs): self.due_date = self.date + monthdelta(1) dt = self.due_date-datetime.date.today() if dt.days <=7: self.is_due = True else: self.is_due = False super(Payment, self).save(*args, **kwargs) -
Error during changing quantity of goods in the shopping cart
I want to add goods changing quantity functionality to my project. But I have a problem with it. It's possible to change the just only the first item in the cart. How can I make it possible to change quantity of the all goods? I think I need to get info about specific cart-item on clicking on appropriate number-plus or number-minus button? Any help or tip please. I'm a newbie Here is my template {% for item in cart.items.all %} <td class="text-center cart-table-info"> <form method="GET"> <div class="number-style"> <span class="number-minus disabled"></span> <input class="cart-item-quantity" type="number" name="quantity" value="{{ item.quantity }}" min="1" data-id="{{ item.id }}"> <span class="number-plus"></span> </div> </form> </td> {% endfor %} <script> $('.number-minus, .number-plus').on('click', function(){ quantity = $('.cart-item-quantity').val() item_id = $('.cart-item-quantity').attr('data-id') data = { quantity: quantity, item_id: item_id, } $.ajax({ type: "GET", url: '{% url "ecomapp:change_item_quantity" %}', data: data, success: function(data){ $('#cart-item-total-'+item_id).html(parseFloat(data.all_items_cost).toLocaleString(undefined, {'minimumFractionDigits':2,'maximumFractionDigits':2}) + ' руб.' ) $('#cart-total-price').children('strong').html( parseFloat(data.cart_total_price).toLocaleString(undefined, {'minimumFractionDigits':2,'maximumFractionDigits':2}) + ' руб.' ) } }) }) </script> Here is my view def change_item_quantity_view(request): cart = getting_or_creating_cart(request) quantity = request.GET.get('quantity') item_id = request.GET.get('item_id') cart_item = CartItem.objects.get(id=int(item_id)) cart_item.quantity = int(quantity) cart_item.all_items_cost = int(quantity) * Decimal(cart_item.item_cost) cart_item.save() new_cart_total = 0.00 for item in cart.items.all(): new_cart_total += float(item.all_items_cost) cart.cart_total_cost = new_cart_total cart.save() return JsonResponse({ 'cart_total': … -
Convert a function view to a Class Based View Django
I am trying to write a a Function-based View (FBV) as a Class-based View (CBV), specifically a CreateView. So far I have the Class based view created but the FBV I use takes a request and an ID so not sure how to handle that. The FBV works fine but as a CBV I think its more complicated as I need to change the data being passed to the HTML I think I shouldn't be using context but I don't know how to do it without Thanks for any help FBV def pages(request, id): obj = programas.objects.get(id=id) script = obj.script script_eng = obj.script_eng zip_scripts = zip(script , script_eng) zip_scripts_eng = zip(script_eng , script) random_zip = list(zip(script , script_eng)) random_ten = random.choices(random_zip) context = {'title': obj.title, 'show_date': obj.show_date, 'script' : obj.script, 'script_eng': obj.script_eng, 'description': obj.description, 'description_eng': obj.description_eng, 'show_id':obj.show_id, 'url': obj.url, 'random_ten': random_ten, 'zip_scripts' : zip_scripts, 'zip_scripts_eng ' : zip_scripts_eng , } return render(request, 'rtves/pages.html', context) CBV class PagesContentView(ListView): model = programas context_object_name = "show_info" template_name = 'pages/index.html' def pages(request, id): obj = programas.objects.get(id=id) script = obj.script script_eng = obj.script_eng zip_scripts = zip(script , script_eng) zip_scripts_eng = zip(script_eng , script) random_zip = list(zip(script , script_eng)) random_ten = random.choices(random_zip) context = {'title': obj.title, … -
Is there a way to query over a range based key cached object in django redis cache?
I'm working on a game server matchmaking and I have a room object which has a range that has two field and other extra fields : min_score = IntegerField (help = 'minimum score that user should have to join this room.') max_score = IntegerField (help = 'maximum score that a user can have to join this room.') I'm going to cache this object and then if a user request to join a room with a range that user can join. Is there a way that I can do something like this query on redis-cache: Room.objects.get( room__min < user.score < room__max) ? I already have some algorithms that should do .get('key') n times. But I wonder if there's a better solution. -
Deploying django application on apache server
I m trying to Deploy my django application on apache server (Xampp) Present Versions :- Python 3.7.3 Xampp :- 3.2.4 Apache :- 2.4 windows 10 Note:- i am using virtual environment Was searching how to do that and encountered this Tutorial However, After making the changes which are same as django Documentation. my apache server is not running Its throwing the error Error: Apache shutdown unexpectedly. This may be due to a blocked port, missing dependencies, improper privileges, a crash, or a shutdown by another method. Press the Logs button to view error logs and check the Windows Event Viewer for more clues If you need more help, copy and post this entire log window on the forums i did changed my port in httpd.conf to some other which was not used by another application, I am not able to figure out what is the issue. Added to httpd.conf LoadModule wsgi_module "c:/users/xxxx/appdata/local/programs/python/python37-32/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win32.pyd" WSGIScriptAlias / "K:/Work/DevNet/first_project/first_project/wsgi.py" WSGIPythonHome "C:/Users/xxxx/AppData/Local/Programs/Python/Python37-32" WSGIPythonPath "K:/Work/Net/first_project" <Directory "K:/Work/Net/first_project"> <Files wsgi.py> Require all granted </Files> </Directory> Thnaku those willing to help. :-) -
Why django-rest-framework stores token in database?
Is token supposed to be stored only in client-side not in server-side? from rest_framework.authtoken.models import Token Django-rest have a model for token, that means token is stored in database. So why Django-rest store token in database? -
how to custom image field in django
i have a form that have a imageField : models : class Image(models.Model): avatar_image = models.ImageField(default=..., upload_to=...,) and forms : class Avatar(forms.Form): avatar_image = forms.ImageField(widget=forms.FileInput,required=False) class Meta: model = Image fields = ['avatar_image'] and when i use this form in html template i see thing like this : form field but i need something like this : field 2 how i can do this ? -
Type Error No exception message supplied in django
my code showing type error No exception message supplied. anyone Help me in this. How to add exception to this code or is there any other way to solve this problem. views.py def get_Loc_Uom(request): print("1st Step") if request.method == 'POST': print("2nd Step") item_id = request.POST.get('item_id1') print(item_id) return_str = "" result = Product_storage_info_master.objects.all().filter(item_id=item_id).values() print(result) print(result['def_loc']) return_str = '<td>"'+ result['def_loc'] +'"</td><td>"'+ result['pur_uom'] +'"</td><td>"'+ result['dal_uom'] +'"' return HttpResponse(return_str) return HttpResponse("Return") Here i'm using cors header. -
How to find conversation by participants ManyToManyField?
How can I retrieve a single conversation which is between some specific users? I have a table like this: | userprofile_id | chat_id | |----------------|-----------------| | 1______________| 1_______________| | 2______________| 1_______________| I tried to get the object by participiants__in=[id1,id2] but it returns multiple objects, I just need the Chat object by the two users id. class Chat(models.Model): participiants = models.ManyToManyField(UserProfile, related_name="chats") messages = models.ManyToManyField(Message, blank=True, related_name="messages") -
how to remain the same data after changed or deleted the primary key (an instance)from model
i want to remain the same data as i saved before , after changing , or deleted the model which provide the foreign key , i tried to on_delete=models.SET_NULL but still removes the instance which i've saved before class Product(models.Model): product_name = models.CharField(unique=True, max_length=50 , blank=False,null=False) price = models.PositiveIntegerField() active = models.BooleanField(default=True) def __str__(self): return self.product_name class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') date_time = models.DateTimeField(default=datetime.now()) @property def total(self): return self.productorder_set.aggregate( price_sum=Sum(F('quantity') * F('product__price'), output_field=IntegerField()) )['price_sum'] class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL , null=True) ordering = models.ForeignKey(Order, on_delete=models.SET_NULL,blank=True,null=True ,default='') quantity = models.PositiveIntegerField(default=1) def __str__(self): return f"{self.product} : {self.quantity}" and how save the total price in variable , if the the price in Product updated , it remains as the first time ? and how to prevent losing data from Order model after removing a product from Product model thanks for advice -
How to use Django Models in template sent through AJAX
I am trying to undertake the following steps: submit a form with AJAX catch the form fields in my views.py use the form fields to create a filter and obtain a queryset: queryset = Movielensrecommendation.objects.all().filter(**q) serialize my queryset: serialized_obj = serializers.serialize('python', queryset) put serialized object in a dictionary response_data['table'] = serialized_obj return a JSON response return JsonResponse(response_data) catch the JSON response in my AJAX function success: function (json) { return the models to my template Steps 1-3 I've got down. Steps 4-7 are solely because, from what I understand, that this is the way to go. Step 8 is the Horcrux. my Model objects are serialized, but I do not understand: How to send the models to the template from my JS where I catch them (step 7) How to iterate through these Model objects in my template (or in JS?) NOTE: In Django I can return a render with the models in the context using context = {'table': queryset} return render(request, 'journal/index.html', context} This way in my template I can access both the original model fields AND the joined models using Foreignkeys. It is important that I am also able to do so after the JSON response: {% for … -
Django e-commerce approach reccomendation?
I am creating a website with e-commerce functionalty I have set up the product page and have a form with a hidden input field that contains the id of the product. I just wanted to ask what would be the best method to add to basket bearing in mind that I don't need to store any of the information in DB table (I will only be storing data once an order is complete), I have thought of storing it in a session then retreving the session, I will attach the code below. I am a bit reluctent to use that method as I believe that there is a more common way of doing this and a better practice if request.method == 'POST': itemID = request.POST['productId'] getItemFromPost = Menu.objects.get(itemid=itemID) if getItemFromPost is None: return HttpResponse("Error there is no data") cartSession = request.session['cart'] for item in cartSession: if item['Itemname'] == Menu.itemname: item['Qty'] += 1 break else: cartSession.append({ 'Itemname': Menu.itemname, 'Itemprice': int(Menu.itemprice), 'Qty': 1 }) request.session['cart'] = cartSession return render(request, "OsbourneSpiceWebsite/cart.html", context) -
Difference between my droplet's postgres database and a newly created managed database
What's the difference between my droplet's postgres database and a newly created managed database? I currently have a running web app that I made via django that's hosted on digital-ocean cloud service. My project involves sending of temperature data from an IoT micro-controller via wifi to a temporary 'free' phpmyadmin database and I pull the data with the 'urllib' command in my python script. Obviously, this process is unnecessarily long and sometimes takes my website lengthy time to load (sometimes I get a 502 Gateway Error). I will like my ESP32 sensors to send data directly to a database on the same digital-ocean server. Is the "managed database cluster" what I need or I can still send the data to the current postgres database I had setup during the initial droplet creation process? Thank you. -
Can't dismiss message from SuccessMessageMixin in UpdateView
I have an UpdateView where I am using the SuccessMessageMixin to display an "updated" message. This works fine, but I can't seem to dismiss the message - clicking the 'x' does nothing. views.py class LocationChangeView(LoginRequiredMixin, SuccessMessageMixin, UpdateView): model = Location template_name = "adventures/location.html" form_class = LocationChangeForm success_message = _("Location successfully updated") From the template [...] <!-- Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <!-- Awesome fonts --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous"> [...] <div class="container-fluid"> {% if messages %} {% for message in messages %} <!-- <div class="alert {{ message.tags }} alert-dismissable" role="alert"> --> <div class="alert alert-info alert-dismissable" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times</span> </button> {{ message }} </div> {% endfor %} {% endif %} </div> [...] As I understand it, the close method is defined in the bootstrap.js (closer examination seems to verify this - I find the close, data-dismiss etc.) though I confess, I'm not a JS expert (that's kind of next on the list ...) My understanding was that this setup for displaying and dismissing messages should pretty much work "out of the box", so what am I missing? -
TemplateDoesNotExist even though i have fixed template directory
i been facing TemplateDoesNotExist even though i have already changed my directory to TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], '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', ], }, }, ] And keep getting TemplateDoesNotExist at /todo/ todo.html Request Method: GET Request URL: http://127.0.0.1:8000/todo/ Django Version: 2.2.1 Exception Type: TemplateDoesNotExist Exception Value: todo.html Exception Location: D:\Anaconda3\lib\site-packages\django\template\loader.py in get_template, line 19 Python Executable: D:\Anaconda3\python.exe Python Version: 3.7.1 Python Path: ['C:\\Users\\Potato\\Desktop\\HoneyLemon', 'D:\\Anaconda3\\python37.zip', 'D:\\Anaconda3\\DLLs', 'D:\\Anaconda3\\lib', 'D:\\Anaconda3', 'D:\\Anaconda3\\lib\\site-packages', 'D:\\Anaconda3\\lib\\site-packages\\win32', 'D:\\Anaconda3\\lib\\site-packages\\win32\\lib', 'D:\\Anaconda3\\lib\\site-packages\\Pythonwin'] Server time: Sat, 10 Aug 2019 09:13:16 +0000 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\Potato\Desktop\HoneyLemon\Honeylemon\templates\todo.html (Source does not exist) django.template.loaders.app_directories.Loader: D:\Anaconda3\lib\site-packages\django\contrib\admin\templates\todo.html (Source does not exist) django.template.loaders.app_directories.Loader: D:\Anaconda3\lib\site-packages\django\contrib\auth\templates\todo.html (Source does not exist) This is my app, and need to request render for todo.html in template from django.shortcuts import render from django.http import HttpResponse def todoView(request): return render (request, 'todo.html') i have the todo.html in templates folder, but it just doesn't load Not sure if it is because of im using anaconda to run python or any other possible reason. Appreciate if anyone could help. -
Not getting an output in website even after I have passed objects in views.py coming from models.py
Not getting an output in website even after I have passed objects in views.py coming from models.py … views.py from django.shortcuts import render from travello.models import destination def index(request): mumbai = destination() mumbai.name = 'Mumbai' return render(request, 'index.html', {'mumbai': mumbai}) models.py from django.db import models class destination: id: int image: str name: str desc: str price: float index.html <div class="destination_title"><a href="destinations.html">{{mumbai.name}}</a></div> it must have to render the output .. but it cant !! -
how to connect django to MS sql server
i have a django project that must use Sql Server database in order to stored and retrieve data. i changed the engine in the settings.py and perform the migration. the database was successfully migrate into the sql server. the problem is when i tried to create a model in django and try to insert data to the model it seams that as there is no connection between the model and the sql server. i tried to open django shell and try to connect to sql server using this command : import pyodbc connection = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};' 'Server=localhost;' 'Database=testDB;') it display the below error : Traceback (most recent call last): File "", line 1, in pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Named Pipes Provider: Could not open a connection to SQL Server [2]. (2) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books … -
Limit number of related objects
I have Parent and Child models related with FK. Is there a way to limit maximum number of children for Parent with sql constraint? For example Parent can have 4 children maximum. I was trying to find an answer but solutions I have found did not base on sql constraint. Code: class Parent(models.Model): name = models.CharField() class Child(models.Model): name = models.CharField() domain = models.ForeignKey("Parent") -
How to get a ManyToManyField object with user IDs in Django?
I have a little built-in Chat with Django Channels and I created a Chat model where I can store the messages (it is like a CHAT ROOM with ID) and I want to get the single object by the 2 users ID. I tried something like Chat.objects.filter(participiants__in=[ID1,ID2]) but it just returns every single chat they are in. def post(self,request): sender = UserProfile.objects.get(user_id=request.user.id) message = request.data.get('message') post_id = request.data.get('post_id') recipient_id = request.data.get('recipient_id') chat_room = Chat.objects.filter(participiants__in=[sender, recipient_id]) class Chat(models.Model): participiants = models.ManyToManyField(UserProfile, related_name="chats") messages = models.ManyToManyField(Message, blank=True, related_name="messages") def get_room_messages(self): messages = self.messages.order_by('-timestamp').all() return [[i.text,i.sender_id,i.link,i.post_id] for i in messages] -
How can I sum over a specific range (id=x to id=y) in Django ORM or SQLAlchemy?
I'm trying to obtain a moving average in my django application. I'm using both Django ORM and SqlAlchemy however I'm struggling to find a function that allows me to sum over a specific interval. Currently I'm only using django for user details(log in and register etc.) The user needs to be able to input their desired amount of data points for the moving average to be established. I've tried using the func.avg() method within SqlAlchemy and deleting records once the number of rows was equal to the desired data points. I would be open to migrating the calculations from SqlAlchemy to Django Models. This is the table defined with SqlAlchemy: class metrics(Base): # class obj for the Metrics table, had to be lowercase to work properly __tablename__ = 'metrics' # Here we define columns for the table Metrics # Notice that each column is also a normal Python instance attribute. id = Column(Integer, primary_key=True, autoincrement=True) symbol = Column(String(6), nullable=False) # crypto currency symbol last = Column(mysql.REAL, nullable=False) # value of the last trade from exchange volume = Column(mysql.DOUBLE, nullable=False) # volume of stock in the market timestamp = Column(mysql.DATETIME, nullable=False) # time of trade ( currently from PC) This is … -
Blank page when using VueJS and Django
I recently added VueJS to my Django project, following this guide. I'm trying to run this template, to check if everything is alright: {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link rel="icon" href="<%= BASE_URL %>favicon.ico"> <title>Django Vue Integration</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Material+Icons"> </head> <body> <noscript> <strong>We're sorry but frontend doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"> <app></app> </div> {% render_bundle 'app' %} <!-- built files will be auto injected --> </body> </html> It should just render the default VueJS page. The problem is that when i run Django using manage.py runserver, i will only see a blank page on http://127.0.0.1:8000/. I'm not receveing any error in my cmd console, but in my dev tools i found this error: GET http://127.0.0.1:8000/app.js net::ERR_ABORTED 404 (Not Found) <script type="text/javascript" src="http://127.0.0.1:8000/app.js" ></script> Any advice on how to fix this issue? Thanks in advance -
Django views for retreiving data from database and operating on that data
Currently, I am working on a project in Django and using PostgreSQL as a database. So now database contains student information like id, name, gender, login time and logout time. Now if I want to get login and logout time of every student so I need to iterate through all the id's present on that specific date, how should I iterate the id's in views? -
is there an config for Upload Big file in Django with Process bar
hi i use django version 2.2 and IIS (Fastcgi) for create a web page for upload big file with process bar i used follow likes : https://djangosnippets.org/snippets/678/ https://djangosnippets.org/snippets/679/ my application work perfect on development environment but in product environment when i watch console'browser it's return always 'null' value and process bar not showing but file uploaded on server and return '200' . Why ? it is another config i should do on iis or on my web ?? follow code return Null in console ''' def upload_progress(request): """ Return JSON object with information about the progress of an upload. """ progress_id = '' if 'X-Progress-ID' in request.GET: progress_id = request.GET['X-Progress-ID'] elif 'X-Progress-ID' in request.META: progress_id = request.META['X-Progress-ID'] if progress_id: cache_key = "%s_%s" % (request.META['REMOTE_ADDR'], progress_id) data = cache.get(cache_key) return HttpResponse(json.dumps(data)) else: return HttpResponseServerError('Server Error: You must provide X-Progress-ID header or query param.') ''' ''' view.py :''' from django.shortcuts import render from django.http import HttpResponse, HttpResponseServerError from django.core.cache import cache from .forms import UploadFile from upbar.UploadProgressbar import UploadProgressCachedHandler from django.views.decorators.csrf import csrf_exempt, csrf_protect import json @csrf_exempt def upload_file(request): request.upload_handlers.insert(0, UploadProgressCachedHandler(request)) return _upload_file(request) # Create your views here. def _upload_file(request): if request.method == 'POST': form = UploadFile(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return …