Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why is my Django hosted on Heroku is so slow?
Recently I have deployed my Django web app to Heroku. while testing and running the app on local, the performance is OK. but as soon as I deployed on Heroku, and even up scaling to 2x dynos, it is still slow. like, login in and loading each page takes up-to 10 seconds. also, loading of static pages are fast on Heroku. while interacting with DB and s3 becket, it get so slow. DB and storage is on AWS. Your feedback and comments are most welcomed as I am new to hosting and staff like cloud computing. here is the link to my app and it is not complete yet. https://dear-hr.herokuapp.com -
Can't import braces library
I use braces for my project. But when I import it to my views.py, it shows yellow error that there is no such a library. But it exists on libraries of the project. What should I do? -
get the value of a specific key from Django queryset json data and pass to javascript dictionary value
I have used Django2 to develop a web app. In the view function, I have rendered some json data to frontend. But in the frontend, I am not sure how to pass the value of a specific key in the Json data to a JavaScript dictionary value. I have tried to use query_results_book_json.XXX, but failed to get the data in my case. It shows undefined. View.py: def Browse_and_adopt(request): query_results_book = Title.objects.all() query_results_book_json = serializers.serialize('json', query_results_book) return render(request, 'main.html', {"query_results_book_json": query_results_book_json}) main.html: <script> var query_results_book = {{ query_results_book_json|safe}}; var book = {title: query_results_book_json.title, author: query_results_book_json.author}; </script> How could I get the the key of title and author in this json data in JS? -
How to convert this complex query to Django ORM equivalent
Models: Items(models.Model): name = models.CharField(max_length=250, verbose_name="Item Name") created_date = models.DateTimeField(auto_now_add=True) Accounts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) url_tag = models.CharField(max_length=200) item = models.ForeignKey(Items, on_delete=models.CASCADE) Comments(models.Model): item = models.ForeignKey(Items, on_delete=models.CASCADE, null=True) comment = models.TextField(null=True) url_tag = models.URLField(null=True) is_flagged = models.BooleanField(default=False, null=True) response_required = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) Responses(models.Model): response = models.TextField() comment = models.ForeignKey(Comments, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) Sql Query: select c.id as comment_id, c.created_date, c.is_flagged, c.response_required from comments as c left join responses as r on c.id = r.comment_id inner join items as i on i.id = c.item_id and r.comment_id is null left join accounts as a on (a.item_id = c.item_id and lower(a.url_tag) = lower(c.url_tag) where c.id in (12, 32, 42, 54) ORDER BY c.created_date desc, comment_id desc; What I tried: filters = { 'id__in': [12, 32, 42, 54] } Comment.objects.filter(**filters) .select_related('responses', 'item') .order_by('-created_date', '-id') I want to get list of comment objects after joining and applying filters. Maybe we can use serializers here i don't know since I don't have much experience with django -
Django Middleware: Creating Middleware for a Specific Case
I just want to provide access to my website when an api http://www.example.com/api/token=exampletoken (any link) returns a success message. The above link returns two type of json type: {"error":"invalid_token","error_description":"The access token provided has expired"} OR {"success":true,"message":"You accessed my APIs!"} if the first part is "success":true , I want the user to access my website. How to design a middleware for this to give access in this case? What I've tried: import requests class NeedtoLoginMiddleware(MiddlewareMixin): def process_request(self,request): exampletoken = some_token # token is generated somewheree r = requests.get("http://www.example.com/api/token="+exampletoken) -
Why webSocket is connecting with "BACKEND": "channels.layers.InMemoryChannelLayer", But not connecting with Redis
I am working on my django chat app, using websocket and channels. for production purpose I tried to change channel_layers to redis. for that, I changed my channel layers in settings.py to CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } terminal shows the following error. Exception inside application: [Errno 111] Connect call failed ('127.0.0.1', 6379) File "/usr/lib/python3.8/asyncio/selector_events.py", line 528, in _sock_connect_cb raise OSError(err, f'Connect call failed {address}') ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 6379) WebSocket DISCONNECT /ws/chat/2febff41-3dd8-4344-a072-b7a0a36f1f6f/ [127.0.0.1:37950] the program was working when I used following channel layer CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", }, } -
Effective way to return a list of ManyToMany related items from a queryset of another model class related to same items
I have the following two model classes: class Property(models.Model): """Represents property class model""" serial_no = models.CharField(unique=True,max_length=255,blank=True,null=True) map_no = models.CharField(max_length=255,blank=True,null=True) lr_no = models.CharField(max_length=255,blank=True,null=True) locality = models.CharField(max_length=255,blank=True,null=True) class PropertyObjection(models.Model): """Represents property objection class. This has properties that have been objected""" objector_name = models.CharField(max_length=255,null=True, blank=True) objection_no = models.CharField(max_length=255,null=True, blank=True) properties = models.ManyToManyField(Property,blank=True) ratable_owner = models.BooleanField(null=True,blank=True) ratable_relation = models.CharField(max_length=50,null=True, blank=True) Which is the most effective way to get all properties that have been objected using the PropertyObjection class. One other thing to note is that each property should have values for objection_no, ratable_owner and ratable_relation values. The expected result should look something like this: [ { 'objector_name': "Angela Rudolf", 'serial_no': "5603883", 'map_no': "238", 'lr_no': "234/R", 'locality': "Nairobi", 'objection_no': "pv876646", 'ratable_owner': True, 'ratable_relation': "N/A" } ] I attempted this implementation but its not the most effective way to do so considering when data eventually grows (I tried this when I have more than 5000 records and the request takes long to return a response. I'd like to use the ORM methods to effectively populate the required queryset. class ObjectUsvAPIView(generics.ListAPIView): permission_classes = (permissions.IsAuthenticated,) queryset = PropertyObjection.objects.all() pagination_class = PageNumberPagination def get_queryset(self): """ This view should return a list of all the properties objected. """ qs = … -
Safely patch additional attributes to Django HttpRequest
Background In certain middleware, I want to add some additional attributes to it, like so: def process_request(self, request: HttpRequest): request._additional_info = {} and then I can access it in the view function: def update_information(request: HttpRequest) -> HttpResponse: if hasattr(request, "_additional_info"): request._additional_info["updated"] = True It works just fine. However, since _additional_info only presents in runtime, there is no way for mypy to know that it exists, and thus making the hasattr check necessary. Question My question is: is it possible to create a class called CustomHttpRequest that behaves exactly the same as HttpRequest except that it explicitly has additional attributes like _additional_info? Expected Result With that, I should able to convert HttpRequest to CustomHttpRequest in the middleware, and change the type hints for request in the view functions to CustomHttpRequest. class ConvertRequests(MiddlewareMixin): def __call__(self, request: HttpRequest) -> HttpResponse: converted_request = CustomHttpRequest(request) return self.get_response(converted_request) No more hasattr will be needed, and now mypy and autocomplete should know that request may have the attribute _additional_info. def update_information(request: CustomHttpRequest) -> HttpResponse: assert request._additional_info is not None: request._additional_info["updated"] = True -
Django, What does it mean to cache an endpoint?
with DRF or with plain view, I use something like this. @method_decorator(cache_page(60)) def list(self, request, *args, **kwargs): How does cache works? When a user-a requests it, it caches for 60 seconds. When a user-b requests the same endpoint, it returns the cached response After 60 seconds, cache expires purely because time has passed. (it doesn't matter what happened during the 60 seconds) And the 60-seconds cycle begins when another user requests the same end point? -
Django form save every dynamic inputs / rows into database
I am beginner at Django. I am developing a project where a model is FileAccess and there has a field named files_link. I have created multiple dynamic inputs/added rows (of this field) using jquery at the Django form. When we submit the form, only the last dynamic input is saved into the database (using PostgreSQL database for saving data). Example: Suppose for input 1, input 2, input 3 if there values are link1, link2, link3 and there only last value link3 has been saved into the database. But expected output for files_link is all the input data link1, link2, link3 dynamic inputs image of files_link Now I want to save every input value/ rows data (of files_link) into the database. I need help to solve this out. Thank You in advance. Django 3.1.7 PostgreSQL models.py class FileAccess(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) files_link = models.CharField(max_length=230) revoke_access_name = models.TextField(null=True, blank=True) date_posted = models.DateTimeField(auto_now_add=timezone.now) forms.py class FileAccessForm(forms.ModelForm): class Meta: model = FileAccess fields = ['files_link', 'revoke_access_name'] fileaccess_form.html {% extends "blog/basep.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">File Server Access Activation Form</legend> <div class="input-wrapper"> <div>Files link : <br/> <input type="text" … -
Define searchFilter URL in django rest framework
Currently I am working on a shop management project. The project is building with django, django-rest-framework and react. I want to filter the models data. So I have installed django-filter. I need to define the url like "http://localhost:8000/api/search-products/?category=oil&product=mustard oil". How can I do this? My product search views is- class SearchProduct(generics.ListAPIView): serializer_class = ProductSerializer filter_backends = [filters.SearchFilter] search_fields = ["category", "name"] My url is- path("api/search-product/?<str:category>&<str:name>", SearchProduct.as_view()) Its showing page not found error. How can I define the appropriate url path? -
No module named 'six.moves.urllib'; 'six.moves' is not a package
I am trying to run a Django server for a project, and I'm getting the following error. No module named 'six.moves.urllib'; 'six.moves' is not a package I've pip installed six, also I've verified it in python by importing six.moves.urllib. I've also tried reinstalling six. Nothing seems to work; kindly help. -
How to style django in bootstrap?
It is way easier to work with django forms, however they are not as good looking as a form created with bootstrap (I am using bootstrap for frontend), my question is: Is there any way I can give style to my django form to have something like this: Currently I am using a django form and including some widgets to customize, but I think I limited to control-form, here is my code: class societyForm(forms.ModelForm): class Meta: model = sociedad fields = '__all__' widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'RUC': forms.TextInput(attrs={'class': 'form-control'}), 'NIT': forms.TextInput(attrs={'class': 'form-control'}), 'resident_agent': forms.TextInput(attrs={'class': 'form-control'}), 'president': forms.TextInput(attrs={'class': 'form-control'}), 'vicepresident': forms.TextInput(attrs={'class': 'form-control'}), 'secretary': forms.TextInput(attrs={'class': 'form-control'}), 'incorporation_date': forms.TextInput(attrs={'class': 'form-control'}), 'expiration': forms.TextInput(attrs={'class': 'form-control'}), 'contact': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.TextInput(attrs={'class': 'form-control'}), 'phone': forms.TextInput(attrs={'class': 'form-control'}), 'status': forms.TextInput(attrs={'class': 'form-control'}), 'comments': forms.TextInput(attrs={'class': 'form-control'}), } Ideas, tips and suggestions will be very appreciated. -
Clearing Postgres DB with Django and updating Swagger
I had to update some model's required fields, but Django Swagger API doesn't update the required parameters in it's UI. I've tried python manage.py flush python manage.py makemigrations python manage.py migrate Along with going to pgAdmin4 and deleting the DB then remaking it and running the above commands again. Seems like the old schemas still persist in Swagger UI. Also it keeps asking me for default values for the added columns(new required fields) in the models, even though I should have deleted and cleared the DB. How do I fix this? -
Can Someone Help Me Figure Out Why A TypeError Is Being Raised While Using Google OAuth2 With Django?
I'm currently building a program to create Chess Game that both blind and sighted people can play. I was trying to implement the following: A method in which if a user already has a Google Account, they can use that to login with Google. I have written the code needed to do so, however, when ran the Django developing Server (I'm using Python's Django Web Framework to build my website), and go to http://127.0.0.1:8000/google/get-auth-url/, I run into a TypeError and can't find the source of the issue. My code is at http://github.com/samarth466/∴ess.git. You will need to go to the Google Development screen and register this application with Google to get Client ID and Client Secret. Store these inside of secrets.json in Chess/google. You will also need the REDIRECT_URL, which is http://127.0.0.1:8000/google/callback. Your secrets.json should look somewhat like this: [ "CLIENT_SECRET": "", "CLIENT_ID": "", "REDIRECT_URI": "http://127.0.0.1:8000/google/callback" ] Now, in your command prompt/terminal, type the following command: python manage.py runserver And then, go to the vrl http://localhost:8000/google/get-auth-url/ (if you changed the port or the IP address, replace localhost with the IP address and 8000 with the correct port). It should display an error message upon reaching this website. I'd appreciate it if … -
Problem with setting auth cookie with django rest framework
I'm trying to make an auth system with django that sets http only cookies to the frontend, then the frontend sends back the cookie with an axios instance. I'm having trouble because when I try it in localhost:3000(frontend) and localhost:8000(backend) it works just fine But whenever I change the frontend's "domain" like to 127.0.0.1:3000 the cookie isn't being set I also tried with a domain I bought and it didn't worked either. I think it is because of the samesite attribute of the cookie, but I can't find anything about the topic. Here is the code I'm using with the backend to set the cookie... -
Django form field different clean logic based on UpdateView or CreateView
I have a form in Django that is used in both a CreateView and an UpdateView. One of the field is hours_allocated which cannot be < 0. In my model, I have declared it as: hours_allocated= models.DecimalField(max_digits=10, decimal_places=2, validators=[MinValueValidator(Decimal('0.0')), MaxValueValidator(Decimal('24.00'))]) When the record is updated (UpdateView) this is fine. However, in the CreateView, I would like to ensure that the value is > 0 (not = 0.0 as allowed in UpdateView). If I add a clean_hours_allocated() method to check if the value is > 0, it applies to both the CreateView and UpdateView. Is there a way to have different validation at the form level based on whether the form is used in an UpdateView or CreateView? Or, is there a way to properly handle validation in the view itself? -
Force http in heroku
I have a node.js app in heroku , this app uses a django api wich is http,but the heroku app is https and cant make petitions to the api , i get this error xhr.js:177 Mixed Content: The page at 'https://myapp.herokuapp.com/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint (API HTTP URL). This request has been blocked; the content must be served over HTTPS. I just want to change the https://myapp.herokuapp.com/ to http://myapp.herokuapp.com/ Thankyou in advance and sorry for my english -
Django App - allowing users to save their favorite posts to their profile for quick access
I'm working on a Django app that is essentially a database for different gym workouts. It allows users to search for workouts, and I anticipate that as scale increases, it would be annoying to keep searching for the same workout the user wants to learn about. Is there functionality in Django to let the user 'save' a certain workout so it appears on their profile page, almost like a playlist of sorts? -
How Sum columns from different tables in new table Django
I would like to create a new table, where in their columns can store the total sum of money of each project, depending certain criterias such as HR, Tools, Materials, Infrastructure. In this case the columns are named total_infraestructura, total_equipo, total_herramientas and total_ recursos Right now I'm getting struggle with getting the total values into the table. class CostoProyecto(models.Model): proyecto = models.OneToOneField(Proyecto, on_delete=models.CASCADE, primary_key=False, null=True) infra = models.OneToOneField(Infraestructura, on_delete=models.CASCADE, primary_key=False, null=True) equipo = models.OneToOneField(Equipo, on_delete=models.CASCADE, primary_key=False, null=True) herramientas = models.OneToOneField(Herramienta, on_delete=models.CASCADE, primary_key=False, null=True) materia_prima = models.OneToOneField(Recurso, on_delete=models.CASCADE, primary_key=False, null=True) def costo_infra (self): return Infraestructura.objects.aggregate(sum('Costo')) Costo_infra = property(costo_infra) The rest of the models to know context from django.db import models # Create your models here. class Proyecto(models.Model): NombreProyecto = models.CharField(max_length=64) ResponsableProyecto = models.CharField(max_length=64) EvaluadorProyecto = models.CharField(max_length=64) DescripcionProyecto = models.CharField(max_length=500) class Financiamiento(models.Model): MontoProyecto = models.IntegerField(null=True, blank=True) MontoPropio = models.IntegerField(null=True, blank=True) MontoBanca = models.IntegerField(null=True, blank=True) MontoPublico = models.IntegerField(null=True, blank=True) proyecto = models.OneToOneField(Proyecto, on_delete=models.CASCADE, primary_key=False, null=True) def financiamiento_asegurado (self): return self.MontoPropio + self.MontoBanca + self.MontoPublico FinanciamientoAsegurado = property(financiamiento_asegurado) def porcentaje_financiamiento_asegurado (self): return self.FinanciamientoAsegurado / self.MontoProyecto PorcentajeFinanciamientoAsegurado = property(porcentaje_financiamiento_asegurado) def nota (self): if self.PorcentajeFinanciamientoAsegurado <= 0.05: return 0 elif self.PorcentajeFinanciamientoAsegurado <=0.15: return 1 elif self.PorcentajeFinanciamientoAsegurado <=0.25: return 2 elif self.PorcentajeFinanciamientoAsegurado <=0.35: return 3 elif self.PorcentajeFinanciamientoAsegurado … -
Django Admin FilteredSelectMultiple Widget selection doesn't work
I am trying to use the FilteredSelectMultiple widget from the admin widgets library. I was able to get the widget displayed on the web page. However, I cannot get the buttons to move the selections to the Chosen box. Here is my code: forms.py from django.contrib.admin.widgets import FilteredSelectMultiple from .models import * from django import forms # Create your views here. class ExampleForm(forms.Form): example_selector = forms.ModelMultipleChoiceField(queryset=Example.objects.all(), widget=FilteredSelectMultiple("Example", is_stacked=False)) class Media: css = { 'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n',) class Meta: model = Example models.py from django.db import models # Create your models here. class Example(models.Model): example_id = models.AutoField(primary_key=True) example_name = models.CharField(max_length=45, blank=False, null=False) def __str__(self): return self.example_name index.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> {{example.as_p}} <script src="/static/admin/js/vendor/jquery/jquery.js"></script> <script src="/static/admin/js/jquery.init.js"></script> <script src="/static/admin/js/SelectFilter2.js"></script> {{example.media}} </body> </html> url.py from django.contrib import admin from django.urls import path, include from django import views as django_views from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), path('example/', include('example.urls')), url(r'^jsi18n/$', django_views.i18n.JavaScriptCatalog.as_view(), name='jsi18n'), ] I've checked the browser console and when I try to click on the buttons I get the following error: Uncaught TypeError: Cannot read property 'addEventListener' of null at Object.init (VM427 SelectFilter2.js:148) at VM427 SelectFilter2.js:233 at NodeList.forEach (<anonymous>) … -
Pytest assert return 401 instead of 200 when test login in DRF
I do not know what is wrong with this code when I am trying to test login, first assert passed so user created successfully but failed in second assert. Hint: I am using simple JWT Test Code: from user.models import User from rest_framework.test import APIClient from mixer.backend.django import mixer from django.urls import reverse import pytest client = APIClient() @pytest.mark.django_db class TestUser(): @pytest.fixture def setup_user(self): user = mixer.blend(User, email='a@a.com', password='1') return user def test_login(self, setup_user): assert User.objects.count() == 1 data = {'email': 'a@a.com', 'password': '1'} response = client.post(reverse('login'), data=data) assert response.status_code == 200 URL: path('api/login/', TokenObtainPairView.as_view(), name='login'), ERROR: FAILED user/tests/test_user.py::TestUser::test_login - assert 401 == 200 -
although I have correctly configured nginx and gunicorn my site does not work
I don't know where the error is but according to the status nginx and gunicorn is working fine I have checked the links by contributing to my site they are correct the error is "redirected you too many times." so according to you it's nginx and gunicorn /etc/nginx/sites-available/namesite.com server { if ($host = namesite.com) { return 301 https://$host$request_uri; } server_name namesite.com www.namesite.com; return 404; # managed by Certbot index index.html index.htm index.nginx-debian.html; location /static { alias /home/myname/nameproject/staticfiles; } location / { include proxy_params; client_max_body_size 100M; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/namesite.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/namesite.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.namesite.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = namesite.com) { return 301 https://$host$request_uri; } # managed by Certbot server_name namesite.com www.namesite.com; listen 80; return 404; # managed by Certbot } /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=myname Group=www-data WorkingDirectory=/home/myname/nameproject ExecStart=/home/myname/nameproject/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ deployement.wsgi:application [Install] WantedBy=multi-user.target -
SQLAlchemy: limit select depth for self referencing table
I have two SQLAlchemy models: Comment and User, defined as following: Comment class Comment(Base): __tablename__ = 'comment' id = Column(Integer, primary_key=True,autoincrement=True , index=True) .... owner_id = Column(String, ForeignKey("user.id"), nullable=False) item_id = Column(Integer, ForeignKey("item.id"), nullable=False) original_comment_id = Column(Integer, ForeignKey("comment.id"), nullable=True) #relationship owner = relationship("User", back_populates="comments") item = relationship("Item", back_populates="comments") replies = relationship("Comment", backref=backref('parent', remote_side=[id])) User class User(Base): __tablename__ = 'user' id = Column(String, primary_key=True, index=True ) .... comments = relationship("Comment", back_populates="owner") As shown above, each comment can be a reply to another comment. I want to get a list of all comments for a given item, and each comment should contain its immediate parent only, if it has one. To achieve that, I'm using the following code comments = db.query(Comment).filter(Comment.item_id == item_id)\ .options( joinedload(Comment.owner).options(load_only("display_name")), joinedload(Comment.parent).options(joinedload(Comment.owner).options(load_only("display_name")))\ ) But it's not giving me just the immediate parent, but grandparents too. How can I limit the depth to immediate parents only ? -
Nonetype error while saving file with dropzone js in Django
I am trying to save documents/images into my SQL database using dropzone.js ,for my web app made using Django HTML FILE: {% extends 'Main/logged_base_expert.html' %} {% block content %} {% load static %} <head> <script src="https://rawgit.com/enyo/dropzone/master/dist/dropzone.js"></script> <link rel="stylesheet" href="https://rawgit.com/enyo/dropzone/master/dist/dropzone.css"> </head> <body> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.7.5/css/bootstrap-select.min.css" media="screen"> <form action="{% url 'document_upload' %}" method = "POST" class="dropzone dz" role="form" enctype="multipart/form-data"> {% csrf_token %} <div class="fallback"> <input name="file" type="file" id="file" multiple > </div> <button type="submit" class="form-control" id="cf-submit" name="submit">Submit</button> </form> <!-- client section end --> <!-- footer section start --> {% endblock %} views.py : def document_upload(request): c = main.objects.get(username = request.session['username']) unq_id = c.unq_id print("overall") if request.method == 'POST': images = request.FILES.get('file') print("image") fs = FileSystemStorage() filename = fs.save(images.name, images) Doc1 = Doc(user_id = unq_id, upload = images) Doc1.save() return render(request, 'Main/document_upload.html') models.py: class Doc(models.Model): unq_id = models.AutoField(primary_key=True) user_id = models.BigIntegerField() upload = models.ImageField(upload_to= 'expert/images') def __str__(self): return str(self.unq_id) The issue I keep facing is that , i keep getting the error AttributeError at /document_upload/ 'NoneType' object has no attribute 'name' It occurs in the following line, in views.py: filename = fs.save(images.name, images) Additional Info : the relative path of the image seems to be storing just perfectly in the database, but since i …