Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
router registration order influences output
I am facing a strange issue trying to implement a webservice using django rest frameworks. I have this two APIs - one for getting the list of news based on category(provided as URL parameter) and another to get the details of a news provided the news ID(provided as url parameter). Following is my app's urls.py code: from django.urls import path from rest_framework import routers ... router = routers.DefaultRouter() router.register('news_contents', NewsContentViewSet) router.register('news_infos', NewsInfoViewSet) router.register('categories', CategoryViewSet) router.register(r'^articles/(?P<category_name>[-\w]+)', NewsItemViewSet, base_name="NewsInfo") router.register(r'^articles/(?P<news_id>\d+)/details', NewsDetailViewSet, base_name="NewsInfo") urlpatterns = router.urls The above code on calling: http://localhost:8000/rest/articles/categoryname returns the correct output, but calling: http://localhost:8000/rest/articles/4057/details/ returns the following: {"detail":"Not found."} But when I change the order in which these two APIs are registered, both APIs start to work as expected. Working urls.py: from django.urls import path from rest_framework import routers ... router = routers.DefaultRouter() router.register('news_contents', NewsContentViewSet) router.register('news_infos', NewsInfoViewSet) router.register('categories', CategoryViewSet) router.register(r'^articles/(?P<news_id>\d+)/details', NewsDetailViewSet, base_name="NewsInfo") #brought to above the listing API router.register(r'^articles/(?P<category_name>[-\w]+)', NewsItemViewSet, base_name="NewsInfo") urlpatterns = router.urls Why is this happening? I am getting a feeling that as I add more APIs, whatever the reason behind this is going to get me stuck. Another thing I noticed while debugging this was that, there are plenty of other endpoints which I don't … -
Waiting for celery result in Java Script
There is external API and internal database. User type "python book" in search input on the website User click search button and make POST request In Django view we try to get this item Item.objects.filter(name=""python book") If object exists we just return json with object detail If object doesn't exists we run celery task to get this object from extarnal database via API and save it in our internal database How to deal with it from frontend side? I need to display progress bar when celery task is running. So should I wait for status celry_running and then make the same POST request again after ~5s (setTimeout)? class ItemView(): def get(self, request): item_name = self.request.POST.get('name') results = Item.objects.filter(name=item_name) if results.count() == 0: get_from_external_api.delay(item_name) return {'status': 'celery_running'} return results Any better solution? -
Django inclusion tag works with the dev server but fails tests
I'm trying to implement JSON-LD metadata for my blog site based using a template tag: @register.inclusion_tag('common_content/json-ld.html', takes_context=True) def page_json_ld(context): """ Renders JSON-LD for a page :param context: parent template context :type context: dict :return: context for json-ld template :rtype: dict """ site_url = '{}://{}'.format( context['request'].scheme, context['request'].get_host() ) json_ld = { '@context': 'http://schema.org', '@type': 'WebPage', 'name': context['menu_link'].page.title, 'url': site_url + context['request'].path, 'description': context['menu_link'].page.meta_description, 'image': { '@type': 'imageObject', 'url': site_url + context['menu_link'].page.featured_image.url, 'height': context['menu_link'].page.featured_image.height, 'width': context['menu_link'].page.featured_image.width }, } return {'json_ld': json.dumps(json_ld, indent=2)} json-ld.html template: <script type="application/ld+json"> {{ json_ld|safe }} </script> Here are models.py for my pages app that I'm trying to implement JSON-LD for: from django.db import models from django.utils.translation import ugettext as _ from django.core.urlresolvers import reverse from tinymce import models as tinymce from filebrowser.fields import FileBrowseField class Page(models.Model): """ Represents a rich-text page that is not a blog post, e.g 'About me' """ title = models.CharField(verbose_name=_('Page Title'), max_length=200) keywords = models.CharField(verbose_name=_('Keywords'), max_length=200, blank=True) content = tinymce.HTMLField(verbose_name=_('Page Content')) last_updated = models.DateTimeField(verbose_name=_('Last Updated'), auto_now=True) featured_image = FileBrowseField(verbose_name=_('Featured Image'), max_length=1024, extensions=['.jpg', '.jpeg', '.png'], blank=True) meta_description = models.TextField(verbose_name=_('Description'), max_length=160, blank=True) def __str__(self): return self.title class Meta: verbose_name = _('Page') #Translators: General plural without a number verbose_name_plural = _('Pages') ordering = ('title',) class MenuLinkQuerySet(models.QuerySet): """Custom … -
Django & WSGI - permission denied
I have a config like this : CentOS 7 - Varnish ( cache server ) / Nginx ( reverse proxy ) / Apache And it's my Django configuration : WSGISocketPrefix /var/run/wsgi <VirtualHost ip:8181> ServerName domain.ir ServerAlias www.domain.ir ServerAdmin info@domain.ir DocumentRoot /var/www/DjangoProject UseCanonicalName On ScriptAlias /cgi-bin/ /var/www/DjangoProject/cgi-bin/ <Directory /var/www/DjangoProject/DjangoProject> <Files wsgi.py> Require all granted </Files> </Directory> Alias /statics/ "/var/www/DjangoProject/statics/" <Directory "/var/www/DjangoProject/statics"> Require all granted </Directory> WSGIDaemonProcess DjangoProject python-path=/usr/lib/python3.4/site-packages python-home=/var/www/DjangoProject user=djangouser socket-user=djangouser WSGIProcessGroup DjangoProject WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias / /var/www/DjangoProject/DjangoProject/wsgi.py ErrorLog /var/log/apache/django-error.log </VirtualHost> When i want to open my website there is a permission denied error in apache log : [wsgi:error] [pid 2131:tid 140344565954304] (13)Permission denied: [client 77.104.92.126:38982] mod_wsgi (pid=2131): Unable to connect to WSGI daemon process 'TiTar_API' on '/var/run/wsgi.2128.0.1.sock' as user with uid=99. I know that uid=99 is nobody user. What's going on here? Why this user want to connect WSGI socket? What is the purpose of user and socket-user attributes in WSGIDaemonProcess? Edit : I saw other questions too, but i think there is another problem ( nobody user ) Django-WSGI setup causing permission denied issues on CentOS 7 Django + Apache + mod_wsgi permission denied https://serverfault.com/questions/357804/apache2-mod-wsgi-django-named-virtual-servers -
Why does Django throw 'invalid literal for int() with base 10' error when I use a foreign key?
I need to build a user model in django that will have specific properties especially a profile picture. Each user belongs to a particular group and each user has their individual conversation history. Below is the conversation model and the group (Contexts) model class Conversation(models.Model): timestamp = models.DateTimeField(auto_now=True) context_name = models.CharField(null=False,max_length=100) user = models.CharField(max_length=255, null=False) data = models.TextField(null=False) class Contexts(models.Model): context_name = models.CharField(max_length=50) context_description = models.TextField() users = models.CharField(max_length=255, null=False) def getUserImagePath(instance,filename): return "/kriktona/static/%s_%s"% (str(time()).replace('.','_'),filename) class UserProperty(models.Model): username = models.CharField(max_length=255, null=False) pic = models.ImageField(upload_to=getUserImagePath, default="/kriktona/static/images/user.png" ,null=True) org = models.CharField(max_length=255, null=False) As you can see, in Conversation model, user was just a field which I would use to filter the conversation based on the particular user and in Contexts model, users is just the field where I pass in the user and filter by that.So I get the group (Contexts) for which the user is part of. This setup works just fine but now I need to declare a seperate user model which will have its own name and picture. For Conversation model, I don't need to do anything since I just need to filter the conversation by the user's name. So I do something like Conversation.objects.filter( user=user_request.get("user")).filter(context_name=user_request.get("context_name")) However for the … -
Unable to display Images from Django Imagefield
I am able to load images to the specific path using Imagefield but not able to display those images in my html templates. enter image description here my settings.py : STATIC_ROOT = "/app/static/" STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join( BASE_DIR,'app','static'), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') files are loading successfully @ ./media/ here is my urlpattern setting: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) {% for service in services %} <div class="col-md-4 animate-box"> <div class="feature-left"> <span class="icon"> <img src="{{ service.icon.url }}" alt=""/> </span> <div class="feature-copy"> <h3>{{service.name}}</h3> <p>{{ service.text }}</p> <p><a href="#">Learn More <i class="icon-arrow-right22"></i></a></p> </div> </div> </div> {% endfor %} Not Found: /icon/6.png Not Found: /icon/blog-1.jpg Not Found: /media/6_qjtYB6t.png Not Found: /blog/blog-3.jpg -
Return as JSON string array instead of Key-Value array
I am writing a web service using Django and is trying to create an API that returns all distinct categories in a table which I have in MySQL database. The table schema is provided below: +---------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | news_id | int(11) | YES | MUL | NULL | | | news_category | varchar(50) | YES | | NULL | | | publish_date | varchar(50) | YES | | NULL | | | news_link | varchar(255) | NO | | NULL | | +---------------+--------------+------+-----+---------+----------------+ The news_category field here is not unique. I want the API to list all distinct categories in the following JSON format: { "count": 22, "next": null, "previous": null, "results": ["apple", "google", "microsoft", "apps", "photography", "virtual-reality", "business"] } Following is my models.py: from django.db import models ... class NewsInfo(models.Model): news = models.ForeignKey(NewsContent, models.DO_NOTHING, blank=True, null=True) news_category = models.CharField(max_length=50, blank=True, null=True) publish_date = models.CharField(max_length=50, blank=True, null=True) news_link = models.CharField(max_length=255) def __str__(self): return self.news.news_title class Meta: managed = False db_table = 'news_info' serializers.py: from .models import NewsInfo from rest_framework import serializers ... class NewsInfoSerializer(serializers.ModelSerializer): … -
Best frame work for web development in FYP project
I am not sure if its right platform for me to ask no technical question or not but anyway I am a bit confused in choosing a framework, as I have the plan to do my FYP, in web development. My target market is PAKISTAN, and I am interested in React, Django, and Node. -
openstack horizon dashboard ipaddress column customize
How do i remove Network info from horizon dashboard section in instance tab, as you can see in following screenshot in RED box, i want to remove that field, openstack add them when you add dual nic, reason i want to remove that because it looks ugly when you have 100 VMs on dashboard, ipaddress is enough to identify instance network info is unnecessary. I am not programmer so thought may ask here if someone did customization work on openstack dashboard Here is the Github link of codes: https://github.com/openstack/horizon -
configuring django with nginx on AWS EC2 Instance
I'm currently configuring a django application to run in a prod environment using nginx. I've really been struggling with this and feel as if I've scoured all of stack overflow. Here is my application's nginx config file # the upstream component nginx needs to connect to upstream django { server unix:/tmp/uwsgi.sock; # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name 54.172.211.18 172.31.38.120 unclique.io; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /path/to/your/mysite/media; # your Django project's media files - amend as required } location /static { alias /home/ec2-user/UnClique/UnClique/static/; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass unix://tmp/uwsgi.sock; include /home/ec2-user/UnClique/config/uwsgi_params; # the uwsgi_params file you installed } } The landing page appears just fine (it seems). But when I click on links that should take me to other pages on the site, I … -
Django experiment for tracking specific users
I'm using an open source called Askbot to create a website, and I want to see how users from different countries/levels react to the change in design over time. I'm currently playing with Django-experients to do some AB testing, but it doesn't seem to link the activities to the users. Is there any other tools that's better suited for my goals? -
Calculate expanded_price using Django ORM
The raw SQL will perform mathematical calculations using calculated field, for example: The item_price column contains the per unit price for each item in an order. To expand the item price (item price multiplied by quantity ordered), could do the following: MySQL [distributor]> select prod_id, -> quantity, -> item_price, -> quantity*item_price as expanded_price -> from orderitems -> where order_num = 20008; +---------+----------+------------+----------------+ | prod_id | quantity | item_price | expanded_price | +---------+----------+------------+----------------+ | RGAN01 | 5 | 4.99 | 24.95 | | BR03 | 5 | 11.99 | 59.95 | | BNBG01 | 10 | 3.49 | 34.90 | | BNBG02 | 10 | 3.49 | 34.90 | | BNBG03 | 10 | 3.49 | 34.90 | +---------+----------+------------+----------------+ 5 rows in set (0.027 sec) How could I accomplish this with Django ORM? -
Django : django.urls.exceptions.NoReverseMatch: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name
I am making a simple blog , I have used the project name as Blogger_Vip and app name as blog I have the following code: In project level module Blogger_Vip : urls.py contains: from django.contrib import admin from django.urls import path from django.conf.urls import url , include from django.conf import settings from django.conf.urls.static import static from .views import home_page , contact_page , about_page , register_page , login_page urlpatterns = [ path('admin/', admin.site.urls), url('^blog/', include('enc_vip_blog.urls',namespace='enc_vip_blog')), url(r'^$',home_page,name='home'), url(r'^login/$',login_page,name='login'), url(r'^register/$',register_page,name='register'), url(r'^about/$',about_page,name='about'), url(r'^contact/$',contact_page,name='contact'), ] views.py contains: from django.shortcuts import render , redirect from django.http import HttpResponse from .forms import ContactForm,LoginForm,RegisterForm from django.contrib.auth import authenticate,login from django.contrib.auth import get_user_model def home_page(r): context = { 'title':'Hello World!', 'content':'Welcome to the Home Page!' } if r.user.is_authenticated: context['premium_content']='Yeahhhh!' return render(r,'home_page.html',context) def about_page(r): context = { 'title': 'ABOUT PAGE', 'content': 'Welcome to the About Page!' } return render(r,'about_page.html',context) def contact_page(r): contact_form = ContactForm(r.POST or None) context = { 'title': 'CONTACT PAGE', 'content': 'Welcome to the Contact Page!', 'form':contact_form, 'brand':'new brand', } if contact_form.is_valid(): print(contact_form.cleaned_data) return render(r,'contacts/view.html',context) User = get_user_model() #This captures the default fields of User Model def register_page(r): register_form = RegisterForm(r.POST or None) context = { 'register_form':register_form } if register_form.is_valid(): username = register_form.cleaned_data.get('username') email = register_form.cleaned_data.get('email') password = … -
How can I make (almost) all fields in all forms disabled for unauthorized users?
I have several complex class-based views for modelforms with inline formsets, new forms being displayed fetched by AJAX and other such stuff. I want to allow unauthorized users to view everything, but only edit one field in a specific form. What I'm currently thinking of is to disable fields on the frontend via JS, then clean out disallowed fields during form cleaning for the one editable form and disallow POSTing everything else, but this seems somewhat clunky. Are there any other viable approaches for doing this without involvement of Javascript? -
Django where to store translation table
According to Django documents, we need to have {% trans myvar %} to show a proper text represented by "myvar". So where should a list of myvars be stored? Something like 'translation.py?' Thanks -
How can I format the output field when using Trunc in Django?
Let's say you want to group your objects by day, month or year and then use annotate to perform some action you want. But you also want to format the output field of Trunc. I tried the following for month and year group_by = "month" grouped_queryset = queryset.annotate(group_by=Trunc("timestamp", group_by, output_field=DateField(input_formats=["%b-%Y"]))) .values("group_by") .annotate(total_value=Sum("profit")) .order_by("group_by") .values_list("group_by", "total_value") I get the following error: __init__() got an unexpected keyword argument 'input_formats' I suppose input_formats is not a valid for DateField in this specific situation. -
Python Django - {% request.user.is_authenticated %} in template tag not working with JS
I am working on a comment/reply system in a blog. If there is any reply to the comment, it is shown as 1 reply etc. and clicking on the link will open the replies. <a class="comment-reply-btn" href="#" > Reply </a> clicking on reply toggles a div containing the replies, which otherwise is hidden using css. The div is:- <div class="comment-reply ml-5 mt-1"> {% for child_comment in comment.children %} <img class="rounded-circle" alt="{{child_comment.user.get_full_name }}" src="{{child_comment.user.userprofile.get_user_image}}" height="18px" width="18px"> <h6 class="d-inline ml-3">{{ child_comment.user.get_full_name }}: </h6> <span>{{ child_comment.content }}</span> <footer>{{ child_comment.timestamp|timesince }} ago</footer> {% endfor %} {% if request.user.is_authenticated %} <form method="POST" action="."> {% csrf_token %} {{ comment_form|crispy }} <input type='hidden' name='parent_pk' value='{{ comment.pk }}'> <input type='submit' value='Reply' class='btn btn-default'> </form> {% else %} <p>You must login to reply</p> {% endif %} </div> I am using the following css setting to hide the div from showing on page load :- .comment-reply{ display: none; } And the following js to open it up on clicking the reply button $(".comment-reply-btn").click(function(event){ event.preventDefault(); $(this).parent().next(".comment-reply").fadeToggle(); }) My problem is if I am logged in it opens up the replies and the form to write a new reply. But if I am not logged in, clicking the reply button doesn't open … -
Django allauth Social application extra data
so i have set up django allauth on my django project and connected to instagram, when doing so i have now on my admin site Social accounts category with my account registers, all good so far on the lower page i can see a field called extra data, how can i put it inside the normal Users data base so i can use it to take how many followers i got out of the extra data? here is what my Social Account Data base looks like -
DRF get_permissions doesn't appear to work correctly
I'm trying to configure permissions for my custom User model and I'm using a Viewset to run CRUD operations for the model. Depending on the operation, I need to set different permission requirements such that: anyone can create a new User instance only owners or admins can retrieve or update users For some reason, when I define the get_permissions method inside my class, like so: def get_permissions(self): if self.action == 'create': return [AllowAny(),] elif self.action == 'me': return [IsAuthenticated(),] return [IsAuthenticated(), IsOwnerOrAdmin()] but when I navigate to /api/v1/users/, the DRF explorer doesn't show the form to create a new User and gives me a 403 error. On the flipside, when I comment this function out, I can see form properly, but obviously can't use it that way. For reference, my custom IsOwnerOrAdmin permissions class looks like: class IsOwnerOrAdmin(permissions.BasePermission): @staticmethod def _is_admin(request): return request.user.is_superuser def has_permission(self, request, view): try: is_owner = str(request.user.id) == view.kwargs.get('pk') return is_owner or self._is_admin(request) # if request.user.uuid is not there (i.e. AnonymousUser) except AttributeError: return False What might be the issue here? -
Creating POST context processor
I have a follow button that I'd like to have on some pages. This follow button follows the same logic on all pages. User clicks follow button -> user follows user -> user is redirected to the same page I have this logic on one page (ProfileView), but I'd like to extend it on other pages (Followers page, following page, etc) ProfileView in views.py def post(self, request, slug): follower = self.request.user self.object = self.get_object() follow_unfollow(follower, self.object.id) //Function that follows/unfollows self.object = self.get_object() context = self.get_context_data(object=self.object) return render(request, self.template_name, context=context) This works correctly. However, I'd like to make this post function outside of ProfileView and have it in something like a context processor. If the user is on another user's followers page and clicks the follow button there should be a post method that handles that request (This post method should be the same post method if we were on another page like the profile page.) Is there a way I can make my post method reusable that way I can handle the request from whatever page using 1 post method? -
directing url path to appropriate nginx server operation
The homepage directs to the index.html properly, the www.website.com/admin connects properly to django, but after adding an app with python manage.py startapp app1, I don't know how to direct nginx to the app, do you? www.website.com works and displays www.website.com/admin works and displays www.website.com/app1 does not work (404 or 500 errors as I play around): upstream website1_server { server unix:/home/Josh/venvironment/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name website.com www.website.com; return 301 https://$host$request_uri; } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name website.com www.website.com; ssl_certificate /etc/letsencrypt/live/website.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/website.com/privkey.pem; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers 'XXXX'; root /usr/share/nginx/html; index index.html index.htm; client_max_body_size 4G; access_log /home/Josh/website1/logs/nginx-access.log; error_log /home/Josh/website1/logs/nginx-error.log; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://website1_server; break; } } location /app1/ { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app1/; } # Error pages error_page 500 502 503 504 /500.html; location = /500.html { root /home/Josh/website1/static/; } } -
Django: How to query for child, granchildren, etc. records in a non-horrible way
I am trying to return a list/filter of users in my Employees table that have a nested relationship to the user. For example, I have employees tied to their manager, and I want to be able to query for all the employees under that manager (this includes any employees under any other managers that are under the main manager). So, if user Bob has 2 direct reports, Sally and Brian. And Brian has 2 direct reports, and Sally has 3 direct reports. I want Bob to be able to see all 7 employees. Right now, the only way I could get it to work was through a horrible sequence, as displayed below..I'm hoping their is an easier/more efficient way. manager = Employees.objects.filter(manager_id=request.user.id).values('manager') employee_ids = list(Employees.objects.filter(manager=manager.first()['manager']).values_list('employee', flat=True)) employees = [User.objects.get(id=i).username for i in employee_ids] grandchildren = [] for i in employees: user_id = User.objects.get(username=i).id child = list(Employees.objects.filter(manager=user_id).values_list('employee', flat=True)) grandchildren.append(child) children = list(chain.from_iterable(grandchildren)) for i in children: user_id = User.objects.get(id=i).id child = list(Employees.objects.filter(manager=user_id).values_list('employee', flat=True)) grandchildren.append(child) grandchildren = list(chain.from_iterable(grandchildren)) for i in grandchildren: employees.append(User.objects.get(id=i).username) employees = list(set(employees)) -
Installing mod_wsgi for Python 3.7 virtualenv
Trying to install mod_wsgi for Python 3.7 to complete setup of Django. But it fails with following error message Command "/home/user/project_env/bin/python3.7 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-f7e23m_p/mod-wsgi/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-b7uqh3g4/install-record.txt --single-version-externally-managed --compile --install-headers /home/user/project_env/include/site/python3.7/mod-wsgi" failed with error code 1 in /tmp/pip-install-f7e23m_p/mod-ws Here is the version information: Apache 2.4.6 CentOS 7 mod_wsgi 3.4 Python 3.7.0 Django 2.0.5 -
Can't install library into virtual enviroment
I created virtual environment for Django procject using Pycharm and Anaconda. The problem is that I can not install django-haystack library into virtual envionment. I tried installing it with anaconda, pycharm itself and tried using pip install django-haystack. Using pip install I can see that library is installed, but I can not find it in virtual environment directory. I saw post earlier which had similar problem where libraries were installed in python "[Python packages not installing in virtualenv using pip " but here the solution was not to use sudo installing library, but I am not using it. Does anybody know how can I install this library into virtual environment ? I run everything on windows -
Unable to connect DJONGO to Replica Set
I am trying to connect DJONGO to an existing MongoDB hosted on mongodb.com. I have tried every iteration I can think of the DATABASES object in settings.py but with no luck. I can connect via MongoClient via shell # >>> from pymongo import MongoClient # >>> client = MongoClient(host='****.mongodb.net:27017',username='****',password='****') But the following connection in settings.py fails. DATABASES = { 'default': { 'ENGINE': 'djongo', 'ENFORCE_SCHEMA': False, 'NAME': '****', 'HOST': '****.mongodb.net', 'PORT': 27017, 'USER': '****', 'PASSWORD': '****', 'AUTH_SOURCE': 'admin', 'AUTH_MECHANISM': 'SCRAM-SHA-1', 'REPLICASET': 'shard-0', } } After 30 seconds ./manage.py runserver returns a timeout error. pymongo.errors.ServerSelectionTimeoutError: connection closed Any direction on properly defining DATABASES in settings.py would be greatly appreciate.