Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz
I have seen many answers that say we must add procfile and requirements.txt and manage.py in same directory, I have all these files including .git in same folder (directory) here is my procfile and requirements.txt, you can see my file structure as well on left procfile requirements.txt snap 1 requirements.txt snap 2 my branch is main so I am using git push heroku main: git status showing branch but still I receive this error enter image description here -
Iterating the values in a list of dictionary
Hi I have a queryset like (order_list.values('user_id'))and its result is <QuerySet [{'user_id': 2}, {'user_id': 2}, {'user_id': 4}]>. How can I get only the values from this. I'm expecting to iterate like 2 , 2 , 4. -
Getting Django - MySQLdb._exceptions.OperationalError: (1025, 'Error on rename of )
I am trying to connect my Django project to mariaDB but I am getting error MySQLdb._exceptions.OperationalError: (1025, 'Error on rename of \'./mydb/auth_permission\' to \'./mydb/#sql-backup-13c39-4a\' (errno: 168 "Unknown (generic) error from engine")') I tried removing the foreign keys and dropping the table but it still does not work. Tried this solution as well https://confluence.atlassian.com/confkb/mysql-error-1025-thrown-when-attempting-to-change-table-collation-and-character-set-785332187.html but had no effect at all. -
Hijack for profile model
I need to add hijack feature to my profile model I got this for now @admin.register(Profile) class ProfileAdmin(MPTTModelAdmin, HijackUserAdminMixin): change_list_template = 'admin/profile/profiles/change_list.html' admin.autodiscover() def get_hijack(self, obj): if obj.user: return f'<a class="button" href="/hijack/{obj.id}">{obj.email}</a>' get_hijack.allow_tags = True but when I try to follow the link, it gives me 404. I also overrided change_list template from admin, what else should I do? -
How do I upload files to the server using the drf-chunked-upload library?
I have tried many ways to upload a file to the server, but I always get the response {"detail": "No chunk file was submitted"}. How to use this library correctly? One of my attempts: import requests url = 'http://127.0.0.1:8000/chunked_upload/' in_file = open("testfile.txt", "rb") data = in_file.read() response = requests.put( url, headers={ "Content-Range": f"bytes {0}-{9}/{10}" }, data={"filename": "testfile"}, files={'file': data}, ) -
Testing in Django with authentication
I'm trying to test a couple of endpoints that require a user to be authorised in Django: def test_one(self) -> None: client = Client() user = client.post('/create', { 'username': 'bob.smith', 'email': 'bob@gmail.com', 'password': 'password', }) token = client.post('/gettoken', { 'identity': 'bob.smith', 'password': 'password', }) x = token.json() resp = client.get('/changepassword', headers={"Authorization": f"Bearer {x['access']}"}) self.assertEqual(resp.status_code, 200) However, it keeps returning a 403: {"detail":"Authentication credentials were not provided."} The content of x is: {'refresh': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzUxMiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYzMTI0MTIwNSwianRpIjoiNDdjNzM5NThkNmYyNGJiMzkxMzRlM2Y2NThhZWI1MjEiLCJ1c2VyX2lkIjoxLCJuYW1lIjoiYm9iYnkuc21pdGgiLCJlbWFpbCI6ImJvYkBzZWNkaW0uY29tIiwiZ3VpZCI6NjA2NzU1ODI4NX0.lqdU5EfSA3DRbfxqum6XyvBc28t-vam8GVDq4W-NOsz7j9VTcg-i9AYQO0V-PLF7Lo89i6Pq50u0tZop7X5PMUryc3sCWPPnEsPyTm7Fi_cVV054E8chd-BP9fzykwW7ef7ufLTjzzPJfQdniq48jlRmce8Yjv_SspwoAhU2uYO54jtn2NNMRk80NckKyzxy9TwU9tItlPMCtoeK1SCucVsv-PfTJscxEXcaC347AZ0Dytqm2DVyDzQbt8RE9MKOXbHkhijeaftNBuiOMqJXE7NWQQ37iyF8bF2iPsc0M-T7ECFwsfFgPK_TD93ETCl9k_o6_6yxOHvx83dk6vGyzONJgl0MJ_W_y_B1UibQttBMoDfMwCxkM7akQ1OhL3ccb7GW-nGgqlOVREfxxW5xCN6h7O9cPMVk74jQ4xv2N6SlkEWIqb5UhQ4ZIJvFVrw-BOHLY_AqvnMadD9gYn7MaDPGXlpCX2EqOvOmKinASuSTJ94kXZ9pwMzuo_b-j5DnQWKgShZydpMZTt77TZ8_MZUtBBf7W-E_z71auQrgopgq82hHEpDfq3FoY4NXUq1IOEaJxJVpFcboXKep4WXQmRliRyqfIbwEAg7DOOiQ6cKrvbScPUKCpfYfzrt2f9fQbgtwwZYxHgW3-sLRP8r10UQzMaa8yR8ot-oQIq4xy5U', 'access': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzUxMiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjMxMTU2NjA1LCJqdGkiOiJkZDliMWI3Yjc0N2E0YjcxYjJhZjg3ZGM0ZjUzODdmZiIsInVzZXJfaWQiOjEsIm5hbWUiOiJib2JieS5zbWl0aCIsImVtYWlsIjoiYm9iQHNlY2RpbS5jb20iLCJndWlkIjo2MDY3NTU4Mjg1fQ.dnlYgqfTvrQPBmAsZgJ5N39dtMANbBYE0kW3ZPCkAX8KWEsQrJwPQRbMYW_AetjowEkiSaWEQs8T4Hs553guW8lpdzg4_SiKjIXXodJJkfGNq9rDC9bpmLSJigVvpCM-AkgXsNUbZKrzP97fk5CZrVvyGszNlT1Oe66OSQrNQuaIqXSQ20XjuwzpSfEB3qJeC45LMgvHRBbEG0V2jOD5ReBxGJGoOPXVYS7vwfy7dLCq2iT-Kkpny4fALKjfM4bpux6UG5kJWrCLp2ybtCLTgJ9y4pvAhzEzmb1IeqtRV-gHQtaqTbMQl5cIhHdvmtMbBSQrzdG3yYqObKoyMW4oQLu8txKE4huptaInJcnXo4j2PFMPD-x3TtJOqOPYbfgb9Vu1-FCT0um5ZPnr9jv6j0ll92CuuHa7rBRatmzvLIJblpJ-ta6IkIZC6XkeEg3Sfg-dbnpSYaJ5fNxQm7r35oGj2j7r8fnvxlnYGPhmXJEdyas798Z001_TXrnHKsv2a1zNNJHQuK8sTmgAC4R1Fs0JQF4yBmIJ4TverKdiGOUHqYAYoEjNX69hdXeu_4AsAdUiRRzSYNbmuZFTEd-iREz0VgMs7QBIecVBzz33kFfgdYTy64qq9NDz3HIkzPbvw4xdGEFp8UTJlCfCFfdkzAT8pb_czC4xufdm9bSvK5E'} Any ideas why it's saying that authentication details were not provided? -
How do I render human-readable value in HTML of a choice list?
Using the following model to select a day of the week: class Schedule(models.Model): DAYS_OF_WEEK = [ (0, 'Monday'), (1, 'Tuesday'), (2, 'Wednesday'), (3, 'Thursday'), (4, 'Friday'), (5, 'Saturday'), (6, 'Sunday') ] day_of_week = models.IntegerField(choices=DAYS_OF_WEEK, default=0) Rendering the models in HTML via {{ schedule.day_of_week }} renders the integer value of 0-6 rather than the human-readable "Monday-Sunday" values. When I view the model in the admin panel, I see the human readable values. How do I render the human readable values in HTML? -
Add days to a given date in Django
I'd like to add 14 days to return date but I get the error below. return_date = models.DateField(issue_date + datetime.timedelta(days=14)) TypeError: unsupported operand type(s) for +: 'DateField' and 'datetime.timedelta' Here is my model class Issue(SafeDeleteModel): _safedelete_policy = SOFT_DELETE borrower_id = models.ForeignKey(Student,on_delete=models.CASCADE) book_id = models.ForeignKey(Books,on_delete=models.CASCADE) issue_date = models.DateField(default=datetime.date.today) return_date = models.DateField(issue_date + datetime.timedelta(days=14)) issuer = models.ForeignKey(CustomUser,on_delete=models.CASCADE) How would I get it to work?? -
django signal post_save not created return two times
when i try to update the post in signal this error happens from django.db.models.signals import post_save @receiver(post_save, sender=Post) def post_save_receiver(sender, instance, created, *args, **kwargs): if created: print(instance.author, " Created") else: print(instance.author, " was just saved") output: root was just saved root was just saved this is when i update the post, its running two times why? -
Error abot failed (13: Permission denied) while connecting to upstream with Nginx and uWSGI
enter code hereI am trying to build a django page with Nginx and uWSGI, nginx does not show any configuration error of the .nginx and the uWSGI either, that is, it has created the .socket with what I specify. But this error keeps appearing in nginx giving me 502 BAD GETWAY: [crit] 16466 # 16466: * 8 connect () to unix: /home/ubuntu/my_app/my_app.sock failed (13: Permission denied) while connecting to upstream, client: IP server: my_app, request: "GET / favicon .ico HTTP / 1.1 ", upstream:" uwsgi: // unix: /home/ubuntu/my_app/my_app.sock: ", host:" my_app ", referrer:" http: // my_app / " any help regarding the error or what may be causing it? theres my .nginx server { # the port your site will be served on listen 80; # the only path #root /home/django/my_app.com; # the domain name it will serve for server_name my_app; #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 { #your Django project's media files - amend as required alias /home/ubuntu/my_app/media; } location /static { #your Django project's static files - amend as required alias /home/ubuntu/my_app/static; } location /static2 { #your Django project's static files … -
Using jQuery locally with Bootstrap for Django wont respond
I have this in my base.html file included {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} And I'm using navbar navbar-expand-lg navbar-light from Bootstrap for my navbar. This is working. When I'm using a small display (like smartphone) it shrinks the menu to dropdown element with a button to expand. But the {% bootstrap_javascript jquery='full' %} part is taking too long to fully load the jquery source from network: Around 400ms without cache. I would like to lose this waiting time as much as possible. So I downloaded latest jquery 3.6.0 from official site, saved it locally in my static files like static/main_app/scripts/jQuery.js loaded it locally with <script type="text/javascript" src="{% static 'main_app/scripts/jQuery.js' %}"></script> in my base.html. This works and jQuery is working fine. But the Bootstrap's nav-bar buttons are not responding. There is also not error message in browser's console. So I though: Maybe the jQuery version is wrong? So I tried to implement again working version to my site {% bootstrap_javascript jquery='full' %} , look for source of the file above in dev-tools of my browser, copy & pasted the source code to my jQuery.js file and loaded the site again. Nothing changed and the navbar … -
Django Serializer Passing a arguments into model function
New to Django and DRF, I have a method in the model properties which accept arguments. I have managed to call it successful though a serializer class with default paramenters and getting a JSON response. My problem is I can't pass argument to that function named balance. I have successful pass my argument from view to serializer class but from serializer to model that where I have failed. I thought will be appreciated. model.py class Item(models.Model): entered_by = models.ForeignKey(User, on_delete=models.PROTECT) name = models.CharField(max_length=50, blank=True) @property def balance(self, stock_type='Retail'): stock = Stock.objects.filter(item=self, type=stock_type, status='InStock').aggregate(models.Sum('quantity')).get('quantity__sum') return stock or 0 views.py def getItemInfo(request): if request.is_ajax and request.method == "GET": id = request.GET.get("item_id", None) sell_type = request.GET.get("sell_type", None) item = Item.objects.get(id=id) if item: serializer = ItemSerializer(item, context={'sell_type':sell_type}) return JsonResponse(serializer.data, status = 200, safe=False) else: return JsonResponse({"data":False}, status = 400) serializer.py from rest_framework import serializers from .models import Item class ItemSerializer(serializers.ModelSerializer): balance = serializers.SerializerMethodField() class Meta: model = Item fields = ('entered_by', 'name', 'balance', 'sell_mode') def get_balance(self, object): sell_type = self.context.get("sell_type") if sell_type: return object.balance(sell_type) return object.balance The error I'm getting 'int' object is not callable -
Cant create object with foreign key
I think i am making some silly mistake, but actually it took me already too much time so i will ask here I have two classes isActive.py active = models.BooleanField() human_readable = models.CharField(max_length=20) User.py type = models.CharField(max_length=127) is_active = models.ForeignKey(IsActive, on_delete=models.PROTECT) and in my migration i am using this function to populate: User = apps.get_model("project", "User") db_alias = schema_editor.connection.alias default_active = IsActive.objects.get(pk=1) # its active status A = User(name='Saaa', is_active=default_active) Adserver.objects.using(db_alias).bulk_create([ A ]) Now i get this error : ValueError: Cannot assign "<IsActive: Aktywny>": "User.is_active" must be a "IsActive" instance. And i think i am actually passing the IsActive instance, because it should link it to my user table? -
Django Error Template Tags type error at /
I want to try to create template tags in django, but there is an error when trying it code in my views : from django.shortcuts import render def index(request): context = { 'judul' : 'Home', 'nav': [ ['/','Home'], ['/blog','Blog'] ['/about','About'] ] } return render(request, 'index.html', context) code in my html: <ul> {% for link,name in nav %} <li> <a href="{{link}}">{{name}}</a> </li> {% endfor %} </ul> -
Django drf-social-oauth2 Social Signup fallback login
I am trying to create a SPA, and want enable to Google Sign In/Sign Up. Is there a way to click Sign In with Google and: First try to Sign Up If the user already exists, login and return access token else create the user and then return the access token I also use drf-social-oauth2 -
Django VsCode not showing code if open project
I am encountering something really strange. If I open my app with VS code it looks like this(well the part im interested in): Which displays everything i wrote. But if I open the entire project, and then go to the app and views.py I get this instead: Which essentially isnt showing this part of the code: if request.method == 'POST': data = request.POST print(data) correct_associate_action = data['correct_associate_action'] Associate_Key_Driver = data['Associate_Key_Driver'] Defect_Area_Associate = data['Defect_Area_Associate'] Sub_Key_Driver = data['Sub_Key_driver'] Metric_name = data['Metric_name'] auditor.correct_associate_action = correct_associate_action auditor.Associate_Key_Driver = Associate_Key_Driver auditor.Defect_Area_Associate = Defect_Area_Associate auditor.Metric_name = Metric_name auditor.Sub_Key_driver = Sub_Key_Driver auditor.save() return redirect(f'http://127.0.0.1:8000/{pk}/') except auditsModel.DoesNotExist: print('hello') context = { "items": model, "form": form } return render(request, "main/auditform.html", context) But everything is running like normal.... Would anyone know what the reason for this is? what could I be doing wrong? -
I've been learning how to use Django, and I'm triying to create objects in python shell but the command "python manage.py shell" isn't working for me
Rozinas-MacBook-Air:website Benoni$ python manage.py shell File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax -
Migration Error on PostgreSQL: Relation does not exist
I'm trying to migrate changes from a SQL database to a PostgreSQL database on Heroku, but I'm facing the following error: Exception Type:ProgramingError Exception Value: relation "wortweise_post" does not exist LINE 1: SELECT COUNT(*) AS "_count" FROM wortweise_post" Screenshots: https://imgur.com/a/QU3Lpga The settings file is below: """ Django settings for myblog project. Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['wortweise.herokuapp.com', '127.0.0.1', 'www.wortweise.online', 'wortweise.online'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'wortweise', 'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myblog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'myblog.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } import … -
How can I tie user behavior on Django website to a specific user?
Note: I would prefer to avoid JavaScript and 3rd party services. I am implementing my own logging and would like to track user actions so I can better understand why exceptions are being thrown. I was initially using a session variable in middleware to later pull a request.session.session_key to identify a user. def CreateSessionMiddleware(get_response): def middleware(request): request.session['sentinel'] = 'value' return middleware However, when the user logs out, the entire session is flushed, including my sentinel key and I lose track of this user. I have also seen the concept of "fingerprinting" a browser, but I'm not sure if enough detailed information about the user is available through request.headers. I'm currently in development and don't have any experience with tracking users in a production environment. Are there any pure Django solutions to following users' journeys through a website? Thanks! -
How to avoid repeated code in views in Django?
I have several function based views in a django project, and I noticed that they have some repeated code, in fact, they all do the same thing: def my_view(request): form = MyForm(request.POST or None) if requqest.POST: if form.is_valid(): do_somethin() and_something_else() return redirect('another:page') return render(request, 'my/tempalate.html', {'form': form}) The only thing that is different is the url where the user is redirected to in case of a succcesful form validation, the template, and maybe the form in the future. Is it a good idea to use something like this to avoid that repetition?: def a_view(request, success_redirect_url, template): form = MyForm(request.POST or None) if request.POST: if form.is_valid(): do_something() and_something_else() return redirect(success_redirect_url) return render(request, template, {'form': form}) and then reuse it in other views that have the repeated code? like: def my_view1(request, url='another_page', template='my/template.html'): return a_view(request, url, template) -
Simplest way to add a view to my Django admin UI?
What is the simplest way to add a view to my Django admin UI? That is, add a URL mysite.com/admin/my-view so that visiting that URL acts like the rest of admin (in particular, requires similar permissions). There is a whole page on this, but it's not obvious to me how to piece it together. https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#adding-views-to-admin-sites says you can add a get_urls to your AdminSite class. Okay, so I need my own AdminSite class. And I need to register it in apps, maybe? I did this: class MyAdminSite(admin.AdminSite): def get_urls(self): urls = super().get_urls() my_urls = [ path('my-view', self.my_view, name='my-view') ] return my_urls + urls def my_view(self, request): # do something .. admin_site = MyAdminSite(name='my_admin') and this in urls.py: from .admin import admin_site urlpatterns = [ path('admin/', admin_site.urls), and this in unchanged in INSTALLED_APPS in settings: 'django.contrib.admin', But, now it only shows the admin for the one app, instead of for all the apps. So how do I get it to auto-discover all the apps like it used to? Or is there a simpler way? P.S. There is also a question on this, but the answer didn't have enough detail for me to use it. -
Permissions in React and Django
I have a web application built with HTML/CSS/JS/Django which is now being converted to a React.js/DRF project. I would like to slowly integrate React.js so I will be converting one page at a time. This is a SaaS LMS platform. There will be different levels of permissions for each page (e.g. can_edit_video, can_view_video, etc) which I have already implemented in Django but have not ever coded in React.js. Where should the permissions be handled on the front-end? What I mean is, I could make this a MPA and have Django fully handle permissions at the view level (seems easiest) when serving the template or I could make it a SPA and handle permissions on the backend, then pass the user permissions to React to display the appropriate content/components. What should be the deciding factor on approach to take? -
supervisor: couldn't exec start_daphne.bash: ENOENT supervisor: child process was not spawned (daphne )
I'm trying to make the supervisor call a script to run daphne, here's what' i get in the log file (daphne.access.log) when i start the supervisor (sudo supervisorctl restart daphne): supervisor: couldn't exec /home/mfatfouti/Apps/Tunnel/start_daphne.bash: ENOENT supervisor: child process was not spawned and here's the script i'm calling (start_daphne.bash): #!/bin/bach NAME="Tunnel-daphne" DJANGODIR=/home/mfatfouti/Apps/Tunnel DJANGOENVDIR=/home/mfatfouti/Apps/venv echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /home/mfatfouti/Apps/venv/bin/activate source /home/mfatfouti/Apps/venv export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Start daphne exec ${DJANGOENVDIR}/bin/daphne -p 8001 Tunnel.asgi:application and this is the supervisor (daphne.conf): [program:daphne] command=/home/mfatfouti/Apps/Tunnel/start_daphne.bash user=mfatfouti numprocs=1 autostart=true autorestart=true redirect_stderr=true stdout_logfile=/var/log/daphne.access.log stderr_logfile=/var/log/daphne.error.log stdout_logfile_maxbytes=50MB stderr_logfile_maxbytes=50MB stdout_logfile_backups=10 stderr_logfile_backups=10 environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8 any idea what i'm doing wrong ?? -
How to set a custom value for model field in django RetrieveUpdateDestroyAPIView?
I have this RetrieveUpdateDestroyAPIView class in my api views and on update it doesn't automatically update a data field named as published. I want to manually update when the PUT request is sent. How can I do that. Here is the code models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Post(models.Model): class PostObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') options = ( ('published', 'Published'), ('draft', 'Draft') ) category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1) title = models.CharField(max_length=100) excerpt = models.TextField(null=True) content = models.TextField() slug = models.SlugField(max_length=250, unique_for_date=True) published = models.DateField(null=True, default=timezone.now) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blog_posts', default=1) status = models.CharField( max_length=10, choices=options, default='published') objects = models.Manager() postobjects = PostObjects() class Meta: ordering = ('-published',) def __str__(self): return self.title view.py from rest_framework import generics from blog.models import Post from .serializers import PostSerializer class PostList(generics.ListCreateAPIView): queryset = Post.postobjects.all() serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Post.objects.all() serializer_class = PostSerializer -
Run Python function from within CherryPy webpage with djgano
My project is a client/server model project with Python, CherryPy and Django. The Python program has various server like functions (adding/removing/editing stuff from/to the database, running commands, etc). It's a SQLite database so I would want the server to be the one solely charge of writing to the database and the client WebApp is just a portal into what the database has as far as values and telling the server what to do. When the python program starts one of its tasks is to initializes a CherryPy server that hosts a Django website as sort of a GUI to the server app. I use the following thread to start the CherryPy Web server: class ClientThread(object): HOST = get_setting_val('BindIP') # Function to read "BindIP" from an ini file. PORT = int(get_setting_val('Port')) # Function to read setting from ini file DIR = get_setting_val('InstallDir') # function to read setting from ini file. STATIC_ROOT = DIR + '/static/' def mount_static(self, url, root): """ :param url: Relative url :param root: Path to static files root """ config = { 'tools.staticdir.on': True, 'tools.staticdir.dir': root, 'tools.expires.on': True, 'tools.expires.secs': 86400 } cherrypy.tree.mount(None, url, {'/': config}) def run(self): cherrypy.config.update({ 'server.socket_host': self.HOST, 'server.socket_port': self.PORT, 'engine.autoreload_on': False, 'log.screen': True, }) self.mount_static(settings.STATIC_URL, …