Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django All Columns Are Distinc
Given that I have a data. id, street, city 1, Main Street, Hull 2, Other Street, Hull 3, Bibble Way, Leicester 4, Bibble Way, Leicester 5, High Street, Londidium 6, High Street, Londidium I want to distinct so that it would only delete Bibble Way, Leicester and High Street, Londidium because it is the only entry where all columns have a duplicate. I already tried .distinct('street','city') but it deletes if either street or city has a duplicate. I want to only delete if all columns match. Whats the right query to get result of id, street, city 1, Main Street, Hull 2, Other Street, Hull 3, Bibble Way, Leicester 5, High Street, Londidium -
What would cause the same Django template include block to behave differently twice on the same page?
I'm including a simple pagination template into a template that lists blog posts. It gets output without getting interpreted, as in, I see the double curly brace enclosed tag as text in the resultant webpage. But, when debugging, I pasted same block higher in the page, and it gets interpreted fine. Between the two, I iterate over the same object that gets passed to the pagination template, so this is probably something that I don't understand about the state of that object? Or Django's rendering process. {% extends "blog/base.html" %} {% block title %}My blog site thing{% endblock %} {% block content %} <h1>Blog site</h1> **{% include 'pagination.html' with page_object=posts %}** {% for post in posts %} <h2><a href="{{post.get_absolute_url}}">{{ post.title }}</a></h2> <p class="date">Published {{post.publish}} by {{post.author}}</p> {{post.body|truncatewords:5|linebreaks}} {% endfor %} **{% include 'pagination.html' with page_object=posts %}** {% endblock %} Pagination.html <div class="pagination"> <span class="step-links"> {% if page_object.has_previous %} <a href="?page={{ page_object.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ page_object.number }} of {{ page_object.paginator.num_pages }}. </span> {% if page_object.has_next %} <a href="?page={{ page_object.next_page_number }}">Next</a> {% endif %} </span> </div> views.py for this app from django.shortcuts import render, get_object_or_404 from .models import Post from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def post_list(request): … -
Need to link the Loggin User with the User model created by me in django framework
User Model class User(models.Model): BLOOD_GROUP_CHOICES = ( ('a+','A+'), ('a-','A-'), ('b+','B+'), ('b-','B-'), ('ab+','AB+'), ('ab-','AB-'), ('o+','O+'), ('o-','O-') ) BILLABLE_and_NON_BILLABLE_CHOICES=( ('Billable','Billable'), ('Non-Billable','Non-Billable') ) employee_name = models.CharField(max_length=50) dob=models.DateField(max_length=8) email=models.EmailField(max_length=254,default=None) pancard=models.CharField(max_length=25,default=None) aadhar=models.CharField(max_length=20,default=None) personal_email_id=models.EmailField(max_length=254,default=None) phone = PhoneNumberField() emergency_contact_no=models.IntegerField(default=None) emergency_contact_name=models.CharField(max_length=100,null=True) relation=models.CharField(max_length=25,default=None) blood_group=models.CharField(max_length=25,choices=BLOOD_GROUP_CHOICES,null=True) designation=models.ForeignKey(Designation,on_delete=CASCADE,related_name="designation") billable_and_non_billable=models.CharField(max_length=25,choices=BILLABLE_and_NON_BILLABLE_CHOICES,default='Billable') joining_date=models.DateField(max_length=15,null=True) relieving_date=models.DateField(max_length=15,null=True) class Meta: db_table ='User' def __str__(self): return self.employee_name serializers class UserSerializers(serializers.ModelSerializer): #Email Notification def create(self, validate_data): subject = 'Your account was activated' plain_message = 'SAMPLE TEXT' from_email = 'demomaster147@gmail.com' to_email = validate_data['email'] EmailThread(subject, plain_message, from_email, to_email).start() return User.objects.create(**validate_data) dob=DateField(input_formats=DATE_INPUT_FORMATS) class Meta: model= User fields ='__all__' password = serializers.CharField(max_length=128, write_only=True, required=True) admin class StaffAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) #job = qs.filter(job_name='test job').first() #print(f"\nQUERY : {job}\n") #print(f"\nQUERY USER : {job.user}\n") print(f"\nrequest.user : {request.user}\n") if request.user.is_superuser: return qs return qs.filter(user__id=request.user.id) #Admin SuperUser @admin.register(User) class UserAdmin(ImportExportModelAdmin): list_display = ('id','employee_name','email','billable_and_non_billable','designation') search_fields = ['employee_name'] pass Actually with the above code I couldn't able to get the details of logged in user details or user inputted data alone. I have a User model created to add the details of the user in my project and that is not connected with the logged in user. for example (if i register a user as "vinoth" with username and email, and i entered a user with the same details … -
I create a One to One realtionship in django Multitable-Inheritance but it not show Book-id in my child class Table and also show Integrity Error Why?
This is my models.py : class Book(models.Model): Book_Name = models.CharField(max_length=100, default="Don Quixote") Author_Name = models.CharField(max_length=100, blank=True, default="Miguel de Cervantes") Price = models.FloatField(default=175.00) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now=True) def __str__(self): return self.Book_Name class ISBN(models.Model): book = models.OneToOneField(Book, on_delete=models.CASCADE, parent_link=True, primary_key=True) Isbn = models.CharField(max_length=100) def __str__(self): return self.Book_Name in according to my code every Book has one isbn number but in admin panel ISBN table don't show book attributes or don't show any book-id. it show only Isbn column and after i give input in this column it show me error "IntegrityError at /admin/inheritance/isbn/add/" and "NOT NULL constraint failed: inheritance_isbn.book_id" This is my admin.py : @admin.register(Book) class PostAdmin(admin.ModelAdmin): list_display = ['Book_Name', 'Author_Name', 'Price'] @admin.register(ISBN) class PostAdmin(admin.ModelAdmin): list_display = ['book', 'Isbn'] I'm a noob to python and Django so any help would be greatly appreciated. -
Does live travel tracking of user possible in django website
I am working on Django website and I want to implement user live travel tracking.Is it possible to implement live tracking of user in the Django website.If Yes, How it is possible. -
Plotly chart not showing in django web app
I've been trying to do this for hours and I still can't figure it out. This is my code for the plot in 'functions.py' def candles(): symbol = 'AAPL' stock = yfinance.Ticker(symbol) hist = stock.history(period='1y', interval='1d') figure = go.Figure(data = [go.Candlestick(x =hist.index, open = hist['Open'], high = hist['High'], low = hist['Low'], close = hist['Close'])]) x_axis = figure.update_xaxes( title_text = 'Date', rangeslider_visible = True, rangeselector = dict( buttons = list([ dict(count = 1, label = '1M', step = 'month', stepmode = 'backward'), dict(count = 6, label = '6M', step = 'month', stepmode = 'backward'), dict(count = 1, label = 'YTD', step = 'year', stepmode = 'todate'), dict(count = 1, label = '1Y', step = 'year', stepmode = 'backward'), dict(step = 'all')]))) layout = figure.update_layout( title = { 'text': 'AAPL', 'y':0.9, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'}) y_axis = figure.update_yaxes( title_text = 'AAPL Close Price', tickprefix = '$') chart = plot(figure, x_axis, layout, y_axis, output_type = 'div') return chart My 'views.py' def chartView(request): candlestick = candles() context={ 'candlestick' : candlestick } return render(request, 'portfolio.html', context) In portfolio.html I'm using {{candlestick | safe}} -
why is the url in django not reading the primary key and just reading it like a string?
def lead_update(request,pk) : lead = Lead.objects.get(id=pk) form = LeadForm() if request.method == "POST" : form = LeadForm(request.POST) if form.is_valid() : first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] age = form.cleaned_data['age'] lead.first_name = first_name lead.last_name = last_name lead.age = age lead.save() return redirect("/leads/{{ lead.pk }}/") # the problem context = { "form" : form, "lead" : lead } return render(request,"leads/lead_update.html",context) on debug : it is showing The current path, leads/{{ lead.pk }}/, didn't match any of these. -
How to refresh image with new random one from list in Django
I have a working function that loads a random image from a collection of images in firebase and displays it in template. However the image doesn't seem to reload on page refresh and that is exactly what I want. How can I achieve this? Working Function. def fetchsliderimages(): big_list = [] ref = dbs.reference('cartoons/sliderimages') snapshot = ref.order_by_child("timestamp").limit_to_last(100).get() if snapshot: for value in snapshot.values(): big_list.append(value['image']) image = random.choice(big_list) return image How I Load The Image <img width="100%" height="110%" src="{{ summary.sliderimages }}"> -
How to keep django rest API server running automatically on AWS?
So I uploaded my Django API with Rest framework on AWS EC2 instance. However, I have to manually go to Putty and connect to my EC2 instance and turn API on whenever I want to use it. When I turn off my PC, putty closes and API cannot be accessed anymore on the ip address. How do I keep my API on forever? Does turning it into https help? Or what can be done? -
Why this python returned value is changing type after assignment
I'm puzzled by this piece of code. The code below is a copy of renderer.py module from django rest framework. Than led me to study a lot of Python inner workings but I still can't understand what is going on with the return / assignment behavior of self.get_template_context function. def render(self, data, accepted_media_type=None, renderer_context=None): (...) print('1', id(data), data) context = self.get_template_context(data, renderer_context) print('4', id(context), context) (...) def get_template_context(self, data, renderer_context): print('2', id(data), data) response = renderer_context['response'] if response.exception: data['status_code'] = response.status_code print('3', id(data), data) return data So the render function calls get_template_context passing two variables, data and renderer_context. The function then includes the status_code on data dictionary before returning it (if exception). I put some print statements to see what is going on with this small piece of code: 1 1730745664704 <class 'rest_framework.utils.serializer_helpers.ReturnDict'> {'date': '', 'memo': ''} 2 1730745664704 <class 'rest_framework.utils.serializer_helpers.ReturnDict'> {'date': '', 'memo': ''} 3 1730745664704 <class 'rest_framework.utils.serializer_helpers.ReturnDict'> {'date': '', 'memo': ''} 4 1730745396352 <class 'dict'> {'data': {'date': '', 'memo': ''}, 'serializer': TransactionSerializer(context={'request': <rest_framework.request.Request: POST '/ledger/ledgers/1/transactions/'>, 'format': None, 'view': <ledger.views.TransactionViewSet object>}): url = NestedHyperlinkedIdentityField(parent_lookup_kwargs={'ledger_pk': 'ledger__pk'}, view_name='transaction-detail') date = DateTimeField() memo = CharField(allow_blank=True, required=False, style={'base_template': 'textarea.html'}) entries = EntrySerializer(many=True, required=True): url = NestedHyperlinkedIdentityField(parent_lookup_kwargs={'transaction_pk': 'transaction__pk', 'ledger_pk': 'transaction__ledger__pk'}, view_name='entry-detail') value = DecimalField(decimal_places=5, … -
Django Model - special characters in field name
I'm creating model for my app. Unfortunately I'm working with measurements units like km/h, kg CO2/ton, heat content (HHV) - 30 different units at all. I don't know how to save it properly in django model or maybe in serializer to make it display proper unit name, including "/", " ", "(" in REST Responses. Also I will be importing data through django-import-export module so it should recognize excel columns which will be named like actual unit name. For example: class Units(models.Model): km_h = models.FloatField(default=-1, null=True) kg_co2ton = models.FloatField(default=-1, null=True) and I would like to have this data available in the following form: class Units(models.Model): km/h = models.FloatField(default=-1, null=True) kg co2/ton = models.FloatField(default=-1, null=True) How to write model and/or serializer to make it work and look good? -
How to deploy a Django and React project on the same Ubuntu 18.04 server using gunicorn and nginx?
I have a Django project that I have already successfully deployed on my Ubuntu 18.04 server via gunicorn and nginx using this tutorial. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 The project uses Django Rest Framework and I'm able to access it's endpoints via a web browser. However, I would also like to deploy a separate react project on the same server, so that it can send http requests to the Django app and display data received from the REST API. How can I go about doing this? Here is my current gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/my_project/coffeebrewer ExecStart=/home/ubuntu/my_project/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/my_project/coffeebrewer/coffeebrewer.sock coffeebrewer.wsgi:application [Install] WantedBy=multi-user.target And here are my current nginx configurations server { listen 80; listen [::]:80; server_name my_ipv6_address; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root root /home/ubuntu/my_project/coffeebrewer; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
Maintaining current URL after incorrect password entry -- Django
def login_view(request): if request.method == "POST": form = AuthenticationForm(data=request.POST) if form.is_valid(): user= form.get_user() login(request, user) if "next" in request.POST: return redirect(request.POST.get('next')) else: print('failed to redirect after login') return redirect('articles:list') <form class="site-form" action='.' method="post"> {% csrf_token %} {{ form }} {% if request.GET.next %} <input type="hidden" name="next" value="{{ request.GET.next }}"> {% endif %} <input type="submit" value="Login"> </form> So the issue I am having is that when I use the @login_required parameter on a specific view function in Django. Things work fine initially. The URL contains ?next=/original/url and the form is correctly able to collect the request.POST.next value of the dictionary it returns and send it back to the login function. Then if you put the password in correctly, it redirects you back to the page you were originally trying to get to via the value of the request.POST.next value THE ISSUE: This only works if you get the password right on the first try. If you enter the password incorrectly, it loses the ?next= part of the url tag and just goes to the default log in page. Thus, when you get the password right the second time, it does not redirect you back to the page you were trying to … -
Unable to login if I register the user using post man or with API in django
unable to login the user if the register the user with postman or with API, but if the register the same user in django admin i can able to login and generating the token. Please help me on this. my serializer code: class UserSerializerWithToken(UserSerializer): token = serializers.SerializerMethodField(read_only=True) class Meta: model = NewUser fields = ['_id','token'] def get_token(self,obj): token = RefreshToken.for_user(obj) return str(token.access_token) my token generation code: class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) # data['username'] = self.user.username serializer = UserSerializerWithToken(self.user).data for k, v in serializer.items(): data[k] = v return data class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer I have created the custom model I think i have problem with the register one but once I register the token is generating but if i am logging in its is saying in valid credentials @api_view(['POST']) def registerUser(request): data = request.data try: user = NewUser.objects.create_user( email=data['email'], first_name=data['first_name'], last_name=data['last_name'], password=make_password(data['password']), ) serializer = UserSerializerWithToken(user, many=False) return Response(serializer.data) except: message = {'detail': f'User with email: {data["email"]} already exists'} return Response(message, status=status.HTTP_400_BAD_REQUEST) -
wagtail django.core.exceptions.FieldError: Unknown field(s); Fields doesn't exist anywhere
my python manage.py makemigrations return error with message File "/usr/local/lib/python3.6/site-packages/django/forms/models.py", line 268, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (seo_title_fr, title_fr, search_description_en, slug_en, seo_title_en, slug_fr, search_description_fr, title_en) specified for PostPage I did serch everywhere in the code where are this fields I didn't find theme at all I did search in database wagtailcore_page I didn't find that fields id | path | depth | numchild | title | slug | live | has_unpublished_changes | url_path | seo_title | show_in_menus | search_description | go_live_at | expire_at | expired | content_type_id | owner_id | locked | latest_revision_created_at | first_published_at | live_revision_id | last_published_at | draft_title | locked_at | locked_by_id | translation_key | locale_id | alias_of_id | url_path_en | url_path_fr I did search in all the code including migrations but not found anything I did try : python manage.py update_translation_fields but no luck my model is : import json from django.db import models from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import slugify from django.utils.timezone import now from django.shortcuts import render from django.http import HttpResponse, JsonResponse,HttpResponseRedirect, Http404 from django.template.response import TemplateResponse from django.forms import FileField from django.core.serializers.json import DjangoJSONEncoder from wagtail.core.models import Page from wagtail.core.fields … -
How to know when heroku rotate my heroku postgres credentials?
Heroku rotate the credentials on heroku postgres, how can i prevent this issue in production apps? -
how to request and post an object to a foreignkey field
When I do this exactly as provided below, a shipping address object is created without the customer assigned in the shipping address foreignkey field, I can add it from the admin panel manually but I'm not able to make it work through code, idk what I'm doing wrong, please help! **models.py** class Customer(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, blank=True, null=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=150) class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) address_one = models.CharField(max_length=200) address_two = models.CharField(max_length=200) ... **views.py** def checkout(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total': 0, 'get_cart_items': 0} if request.method == 'POST': form = ShippingForm(request.POST) if form.is_valid(): #how do I get the customer to get added in the foreignkey field for the shipping address model form.save() return redirect('store:checkout_shipping') else: form = ShippingForm() else: form = ShippingForm() context = {"items": items, "order": order, "form": form} return render(request, 'store/checkout.html', context) -
Error in Postgresql: connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "TheGecko"
Im trying to use PostgreSQL with django and I get that error when running python3 manage.py migrate: connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "TheGecko" I was following this guide:https://djangocentral.com/using-postgresql-with-django/ Here is my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'websitedb', 'USER':'TheGecko', 'PASSWORD':'xx', 'HOST':'localhost', 'PORT':5432, } } Also, even though I entered that line: GRANT ALL PRIVILEGES ON DATABASE websitedb TO TheGecko;, when I do \l, I get this output. Shouldn't the owner be TheGecko? I've looked over the web and nothing I could read worked for me. Please help. -
Python Django Rest framework
What are the contents of args and kwargs in this create method? def create(self, request, *args, **kwargs) -
Django's Image Field and Google app engine
I have a django app deployed on google cloud platform. I also have the same app deployed on heroku(It works fine). I have a model in my code that looks like this : class Notification(models.Model): ## other fields qrcode = models.ImageField(null=True, blank=True, default=None) When I pass this model to the serializer, I got a status code 500. I googled it and find some answers reffering to PIL library or some needed configuration in the Google Cloud App Engine in order to support ImageField. Does anyone know what to do in this case? Thnx in advance -
What other softares/libraries should I look to import to base Django if I'm looking to make a banking application?
I'm a relatively new full stack developer that recently picked up a project to create a banking application that handles users' banking information and allows them to purchase bonds. I'm familiar with Django, templating, and APIs, but I was wondering if someone could recommend some of the best software to combine with Django to make this app possible. -
Specifying Django widget attribute in ModelForm rather than as HTML <style>
I have a Django input slider defined as follows: #widgets.py from django.forms.widgets import NumberInput class RangeInput(NumberInput): input_type = 'range' #forms.py from polls.widgets import RangeInput class VoteForm(forms.ModelForm): class Meta: #model = CC_Responses model = CC_Resp_NoFK fields = ['Person_ID', 'Test_date', 'Response_value'] # following added from SliderModelForm widgets ={ 'Response_value':RangeInput } which is “processed” by the view def p2vote(request,q_id): CC_question = get_object_or_404(CC_Questions, pk=q_id) # if request.method == 'POST': form = VoteForm(request.POST) if form.is_valid(): item = form.save(commit=False) item.Q_ID = q_id item.save() return redirect('/polls/p2') else: formV = VoteForm() return render(request, 'pollapp2/vote.html', {'var_name':CC_question,'form' : VoteForm()}) and in the template I have the inline CSS <style> /* Following CSS is used by the input slider (range) since Django assigns id value of id_Response_value */ /*See: https://stackoverflow.com/questions/110378/change-the-width-of-form-elements-created-with-modelform-in-django */ #id_Response_value{width:300px;} </style> which is associated with the slider/range <label for="Response_value">Response value</label> {% render_field form.Response_value rows="1" class="form-control" %} I obtained id_Response_value by looking at the source of the rendered HTML in the browser – I guess I could explicitly set an ID. All the above works exactly as I want. I can control the width of the range slider using CSS. Now, I believe, inline CSS is a “bad thing”, so as a step to improve my code I’m trying to … -
I want to display the images and user can select one of them
I am new at Django I want some helps. Basically,I want from users that they can select multiple images and save it, but I got like this and I don't know how to do it. I want to display the images and user can select one of them. please help. models.py class Images(models.Model): product_image=models.ImageField(upload_to='media',null=True, blank=True) def __str__(self): return "{}".format (self.product_image) class user_select(models.Model): name = models.CharField(max_length=200, null=True, blank=True) product_image=models.ForeignKey(Images, on_delete=models.CASCADE) def __str__(self): return "{}".format (self.name) forms.py class UserForm(forms.ModelForm): class Meta: model = user_select fields = '__all__' views.py def home(request): form = UserForm() if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form.save() context = {'form':form} return render(request, 'home.html', {'form':form}) home.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container mt-5"> <div class="row mt-5 mr-5"> <div class="col-md-8 mt-5"> <div class="card border border-secondary mt-5"> <div class="col-md-8 mt-5" align='center'> <form method="POST" action="" > {% csrf_token %} <div class="col-md-8"> {{ form|crispy }} </div> </form> <button type="submit" class="btn btn-success mt-5 mb-5">Place Order</button> </div> </div> </div> </div> </div> {% endblock %} enter image description here -
Dehydrate the same field django
I have a model Student: class Student(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30, verbose_name='Name') lastname = models.CharField(max_length=100, verbose_name='Lastname') history = HistoricalRecords() Also I have a model: class Class(models.Model): id = models.AutoField(primary_key=True) student = models.models.ForeignKey(Student,on_delete = models.CASCADE, related_name='+') my admin.py class ClassResource(resources.ModelResource): class Meta: model = Class fields = ('student',) def dehydrate_student(self, Class): student= getattr(Class.student, "name") return '%s' % (student) class ClassExportAdmin(ImportExportModelAdmin, ClassAdmin): resource_class = ClassResource admin.site.register(Class, ClassExportAdmin) Now I am executing only name, is that possible to dehydrate the same field student one more time. I need past into my 2 column the surname of the student. -
Django : Rename a file with the username and the the timestamp before uploading
I am newbee in Django. I have an app where I can upload multiple files. I would like to rename the file by including the username that is authenticated and the timestamp : "bild.png" should become "bild_John_Bown_202204055.png" I use the Microsoft Graph tutorial on Django to the authentication process (https://docs.microsoft.com/en-us/graph/tutorials/python). Anyone can help me to include that in my code. Thank you models.py from django.db import models class UploadFiles(models.Model): documents = models.FileField(upload_to='document/', blank=True, null=True) uploaded_at = models.DateTimeField(auto_now_add=True) forms.py from django import forms from django.forms import ClearableFileInput from .models import UploadFiles class FilesForm(forms.ModelForm): class Meta: model = UploadFiles fields = ['documents'] widgets = {'documents': ClearableFileInput(attrs={'multiple': True}),} views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from base.auth_helper import get_sign_in_flow, get_token_from_code, store_user, remove_user_and_token, get_token from base.login_helper import * from django.core.files.storage import FileSystemStorage from os import listdir from os.path import isfile, join, getmtime from django.conf import settings from base.forms import FilesForm from base.models import UploadFiles def home(request): context = initialize_context(request) return render(request, 'home.html', context) def initialize_context(request): context = {} # Check for any errors in the session error = request.session.pop('flash_error', None) if error != None: context['errors'] = [] context['errors'].append(error) # Check for user in the session context['user'] = …