Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Appsheet saving to S3
We have a single database we are using with PostgreSQL and when appsheets saves the data it only provides I believe what is called the file path from the work load. However its saving from the default settings of appsheet/data/{appname}/{folder}/. That works fine for appsheets but us developers using boto3 with django can't find the images. Working with the Appsheets member and doing research we found a field called default app folder and every time we try make that field empty it results back to the main setting path. Now we can't change the main setting path for the profile because they have tons of other apps in appsheets that use that path. However for this one app we need to make it empty so it will save correctly into s3 and have the right path in postgreSQL. I hope this explains the issue and be happy to answer any additional questions. -
I don't know why my views on django is not displaying on the browser
I don't know why my views on django is not displaying on the browser, I'm new to django and I'm just trying to create a very basic new user view but for some weird reason is not working and I can't understand what is the problem. Please help me to at the code: project urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('logapp.urls')), path('admin/', admin.site.urls), ] app url.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home") ] views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse("<h1>Hello world</h1>") setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'logapp', ] Those are the only things I did after creating virtualenv. The project is running and displaying only the default django rocket. -
Attempting to set related model fields via parent function call(s)
I am writing a Compact Disk Library editing routine. The application allows you to enter a CD Artist Name, and CD Title and the total time of the CD. User can then enter track information. While entering track information I want the application to display Current run time including this track, and time remaining based on length of the CD. The models and functions are below class Cd(models.Model): artist_name = models.CharField(max_length=155) cd_title = models.CharField(max_length=155) cd_total_time = models.TimeField(default="00:00:00") cd_total_time_delta = models.DurationField(default=timedelta) cd_run_time = models.TimeField(default="00:00:00",blank=True) cd_run_time_delta = models.DurationField(default=timedelta) cd_remaining_time = models.TimeField(default="00:00:00",blank=True) cd_remaining_time_delta = models.DurationField(default=timedelta) def convert_to_delta(self,time_in): hold_time = time_in.strftime("%H:%M:%S") t = datetime.strptime(hold_time,"%H:%M:%S") return(timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)) def calculate_time(self): cd_total_time_delta = self.convert_to_delta(self.cd_total_time) cd_total_run_time_delta = timedelta(minutes=0) for track in self.cd_tracks.all(): cd_total_run_time_delta += track.trk_length_time_delta track.trk_run_time_delta += cd_total_run_time_delta track.trk_run_time = f"{track.trk_run_time_delta}" track.trk_remaining_time_delta = cd_total_time_delta - cd_total_run_time_delta track.trk_remaining_time = f"{track.trk_remaining_time_delta}" self.cd_run_time_delta = cd_total_run_time_delta self.cd_run_time = f"{self.cd_run_time_delta}" self.cd_remaining_time_delta = self.cd_total_time_delta - cd_total_run_time_delta self.cd_remaining_time = f"{abs(self.cd_remaining_time_delta)}" def save(self, *args, **kwargs): self.calculate_time() super().save(*args,**kwargs) def __str__(self): return f"{self.artist_name} : {self.cd_title}" class Track(models.Model): cd_id = models.ForeignKey(Cd, on_delete=models.CASCADE, related_name='cd_tracks', ) track_title = models.CharField(max_length=50) track_number = models.IntegerField() trk_length_time = models.TimeField(null=True,default=None, blank=True) trk_length_time_delta = models.DurationField(default=timedelta) trk_run_time = models.TimeField(default="00:00:00",blank=True) trk_run_time_delta = models.DurationField(default=timedelta) trk_remaining_time = models.TimeField(default="00:00:00",blank=True) trk_remaining_time_delta = models.DurationField(default=timedelta) def calculate_track_delta(self): self.trk_length_time_delta = self.cd_id.convert_to_delta(self.trk_length_time) def save(self, *args, **kwargs): … -
Django ListView how to zip context data with another context
I'm trying to add some context to my ListView context and access them in one for loop with zip like this class WeatherListView(ListView): """ List view of Weather data """ template_name = "frontend/weather_list.html" model = Weather def get_context_data(self, **kwargs): weather_query = Weather.objects.all() temp_list = list(weather_query.values_list('temperature', flat=True)) humidity_list = list(weather_query.values_list('humidity', flat=True)) temp_list_compared = compare_item_to_previous(temp_list) humidity_list_compared = compare_item_to_previous(humidity_list) data = super().get_context_data(**kwargs) context = { "object_list": zip(data, temp_list_compared, humidity_list_compared) } return context Then I want to get my data in the template for loop {% for i in object_list %} {{ i.0.some_field_in_original_context }} {{ i.1 }} {{ i.2 }} {% endfor %} But what I end up having for my original context {{ i.0 }} is this paginator page_obj is_paginated How can I still access my original ListView data after putting it in a zip. -
Downloaded pdf file trimmed from django
I am trying to create a site in django (version 1.11) that will download a file resides on the host. I have used the following code: views.py: def download_file(request,fl_path): data = subject.objects.all() sub = { "subject_id": data } fl_path = data.values('submissions')[0]['submissions'] filename = fl_path.split('/')[1] fl = open(fl_path, 'r') response = HttpResponse(fl, content_type='application/pdf') response['Content-Disposition'] = "attachment; filename=%s" % filename return response models.py: class subject(models.Model): nameSubject = models.CharField(max_length=200, primary_key=True) songs = models.CharField(max_length=2000) selfTasks = models.CharField(max_length=2000) submissions = models.FileField(upload_to='submissionsTasks') def __str__(self): return self.nameSubject The file is downloading successfully, with file name and all. The point is that the file is trimmed at 2KB of size. The downloaded file contains an identical copy of the first 2KB of the original file. Do we have any setting that should allow >2KB file download? Any other solutions / ideas? Thanks in advanced, Michal -
In Django no other function getting called except one rest showing error 403
This is our code for url from django.conf.urls import url,include from django.urls import path,re_path from . import views app_name = 'challengeide' urlpatterns = [ url('challengeide', views.qtn,name='test'), url('challenge/', views.challengeide, name='challengeide'), url('challenge/', views.dataentry, name='dataentry'), #url('challengeide', views.dataentry,name='dataentry'), path('challenge/challengeide/', views.send_challenge_request, name='send_challenge_request'), ] this is code for views from django.shortcuts import render from django.http import JsonResponse, HttpResponseForbidden import requests from challengeide.models import Challenge_Detail from challengeide.models import ChallengeDemo import json from django.utils.datastructures import MultiValueDictKeyError from users.models import Profile from django.shortcuts import redirect, get_object_or_404 from django.http.response import HttpResponseRedirect from django.contrib.auth import get_user_model def qtn(request): try: #print("If loop") data = request.POST['opponent'] data1 = request.POST['qts'] opponent_row = Profile.objects.get(slug = data) global to_id to_id = opponent_row.user_id print(data,data1) global a a = int(data1) question_desc = Challenge_Detail.objects.get(id = a) #print(a) #dataentry(request) return render(request,"challengeide.html",{'ChallengeDetails':question_desc}) except MultiValueDictKeyError : #print("in else") question_desc = Challenge_Detail.objects.get(id = a) e1 = question_desc.expout e2 = question_desc.expout2 e3 = question_desc.expout3 e4 = question_desc.expout4 e5 = question_desc.expout5 i1 = question_desc.expin i2 = question_desc.expin2 i3 = question_desc.expin3 i4 = question_desc.expin4 i5 = question_desc.expin5 for i in range(1,6): if (i==1): if request.is_ajax(): source = request.POST['source'] lang = request.POST['lang'] data = { 'client_secret': 'a4b7d06f4c25bf97ed19ebe68eadaaff39faf493' , 'async': 0, 'source': source, 'lang': lang, 'time_limit': 5, 'memory_limit': 262144, } x = str(i1) i1 = x.replace("qwe","\n") data['input'] = … -
Wagtail admin: How to customize layout of select/checkbox options?
I have a wagtail admin form where I want to customize the layout of a series of checkbox options used to populate a ManyToMany Field. The model I'm editing is called "Product"; the field is "displays_on_pages", and that links to a separate "GenericPage" model. The problem is, I have so many of these pages available as options that it makes displaying them as a regular list of checkboxes a bit unwieldy. I'd like to display them nested instead, so that I can indent the subpages under their parent pages. Something like this: □ Parent Page 1 □ Subpage 1.1 □ Subpage 1.1.1 □ Subpage 1.2 □ Parent Page 2 □ Subpage 2.1 (etc.) I've figured out how to create a custom form widget by subclassing forms.widgets.CheckboxSelectMultiple, how to pass in my own query logic so that the pages available as choices for the checkbox widget appear sorted as a tree, and how to set up a template for the output. The problem is that the choices I'm passing into the template don't appear to be actual "Page" objects. As I loop through the queryset, I can get the value (id) and label (title) for each option, but I can't seem … -
how to use validate_password function with user on user register in django rest framework?
I want to use validate_password() function to check if user data like(name, username, last_name) is similar to password or not. this is my code in serializers.py class RegisterSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())]) password1 = serializers.CharField( write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField( write_only=True, required=True, validators=[validate_password]) class Meta: model = User fields = ( 'username', 'password1', 'password2', 'email', 'first_name', 'last_name') extra_kwargs = { 'first_name': {'required': False}, 'last_name': {'required': False}, } def validate(self, attrs): if attrs['password1'] != attrs['password2']: raise serializers.ValidationError( {'password1': "password field dont match !"}) return attrs def create(self, validated_data): user = User.objects.create( username=validated_data['username'], email=validated_data['email'], ) if 'first_name' not in validated_data: user.first_name = "" else: user.first_name = validated_data['first_name'] if 'last_name' not in validated_data: user.last_name = "" else: user.last_name = validated_data['last_name'] user.is_active = False user.set_password(validated_data['password1']) profile = Profile.objects.create(user=user) profile.save() user.is_active = True user.save() return user I need to validate like: validate_password(password, user=user) but how can I have access to user variable contain user object in create() ? -
Django won't recognize {% static %} tag inside an href or image src in html file
The {% load static %} tag at the top of my html file seems to work When I try to link my css file from static folder using this code : {% load static %} <link href="{% static 'static/style.css' %}" rel="stylesheet"> it tries to create a file called {% static 'static/style.css' %}, which means the static keyword isn't being recognized. Any help in figuring out why would be highly appreciated Here's my relevant settings.py to link static files INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", '/Google_Solutions/static/', ] My static and templates are in the main directory and here's my home.html file head where i'm trying to include files {% extends 'layout.html' %} {% load static %} {% block head %} <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <title> Homepage </title> <!-- Vendor CSS Files --> <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet"> <link href="assets/vendor/glightbox/css/glightbox.min.css" rel="stylesheet"> <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet"> <link href="assets/vendor/swiper/swiper-bundle.min.css" rel="stylesheet"> <!-- Template Main CSS File --> {% load static %} <link href="{% static 'css/style.css' %}" rel="stylesheet"> {% endblock %} here's my layout.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="icon" type="image/png" sizes="16x16" href="{% static '/favicon-16x16.png'%}"> <link rel="manifest" href='{%static … -
how variable passed in context convert in html if use {{}}
variable passed using render when we write variable inside in html file using {{}} does it convert from queryset(complex object) to html St=Student.object.filter(id=1) return render(request,'stur.html',{'st':st}) or when passed python object St=[1,2,3] return render(request,'stur.html',{'st':st}) -
How to customize django-allauth urls
I want to change the default django-allauth urls with my custom one, for example: Instead of accessing /accounts/login I want to acces login page: /mylogin. I tried to modify urls.py but it doesn't have a complete result. from django.contrib import admin from django.urls import path, include from allauth.account.views import LoginView, SignupView urlpatterns = [ path('admin/', admin.site.urls), path('', include('users.urls')), path('accounts/', include('allauth.urls')), path('mylogin/', LoginView.as_view(), name='custom_login'), path('myregister/', SignupView.as_view(), name='custom_reg'), ] -
Djongo ArrayReferenceField in Django Admin Panel Error
Whenever I try to go to the product details page I encounter this error - 'list' object has no attribute '_meta' How to solve it? My models class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=255, blank=False, null=False) price = models.IntegerField(blank=True, null=True, default=0) category = models.ArrayReferenceField( to=Category, blank=True, related_name="products" ) def get_categories(self): return "\n".join([p.name for p in self.category.all()]) admin @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ('name','price', 'in_stock','get_categories',) I'm using Django - 3.1.7 , djongo - 1.3.4 -
A WP form sending data through API to Web App in Azure?
Our team has been working this Django based Web App for handling customer data. This customer data is being gathered in a json Rest Api and the form the API connects to is made with WordPress. The database is parked in Azure and is working very well, but now our concern is that we need some kind of Azure token to get the data from the form and API to the database in Azure. Azure also has some restrictions what it lets through as only the customer's organization can access the Web app/database in azure as it is behind MS login. So my question is: is there something we are missing? We know we need a token for the post as that way it cannot be anything other than a "legit" form that was filled out on the public web page. But the way we are trying to get that token hasn't worked. The Form gets the info that needs to be filled form the API and it is done by the marketing agency that creates the Customer's web page. So is this something they need to add to the form or Us for the API side? Also sorry for … -
can't check username and email and password using UserCreationForm - Django
when i add style to UserCreationForm in forms.py and pass it to signup html page and test it , it don't work fine i mean it don't check username and email if it exist or not and password don't check if it good or no singup.html : <form method="post"> {% csrf_token %} {% for field in form %} <fieldset class="control-group"> <label class="control-label" for="id_{{ field.name }}">{{ field.label }}</label> <div class="controls"> {{ field }} <p class="help-text">{{ field.help_text }} </p> </div> </fieldset> {% endfor %} <input type="submit" class="fadeIn fourth" style="background-color:#7952b3" value=" sign up "> </form> forms.py : from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm # Sign Up Form class SignUpForm(UserCreationForm): first_name = forms.CharField(required=True,label=' First Name : ',widget=forms.TextInput(attrs={'class': 'form-control'}) ) last_name = forms.CharField(required=True,label=' Last Name : ',widget=forms.TextInput(attrs={'class': 'form-control'}) ) email = forms.EmailField(required=True,label=' Email ',widget=forms.EmailInput(attrs={'class': 'form-control center container','style': 'width:85%;text-align: center;background-color:#f6f6f6'}) ) # constructor of the UserForm, not Meta def __init__(self, *args, **kwargs): super().__init__(*args,**kwargs) self.fields['username'].widget.attrs.update({'class':'form-control','placeholder':' add username ','style': 'font-size:19px;text-align: center;'}) self.fields['password1'].widget.attrs.update({'class':'form-control','placeholder':' enter pass ','style': 'font-size:19px;text-align: center;'}) self.fields['password2'].widget.attrs.update({'class':'form-control','placeholder':' re-type pass ','style': 'font-size:19px;text-align: center;'}) class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', ] how i can fix check username and email and password -
Database performance in Django/Postgres
In one of my views for the staff, I show the last 10 registrars on my site and some of their activity like so: recentlyjoined = User.objects.order_by('-date_joined').annotate(post_count=Count('post', distinct=True), text_count=Count('text', distinct=True), pdf_count=Count('pdf', distinct=True), discussion_count=Count('discussion', distinct=True))[0:10] And in my template I do {% for applicant in recentlyjoined %} {{ applicant.post_count }} {% endfor %} for all the annotations above. When I call this site, it takes VERY long to load, sometimes I even get a timeout error. I narrowed it down to this annotations. Whats wrong? Why does this improve so bad? And how can I fix it? (And in case it matters: In my sandbox database I have only 15 users, but one of them has like 5000 posts. So its not exactly big data to handle.) -
How to make multiple types of models and refer them with same name in Django?
I am new to Django. I want the functionality of Accounts and Transactions. Account can have three types of transactions. Income, Expense and Transfer. All of them have some common fields among them. But also have some additional fields. I want to know can I make such models so that I can access all the transactions of account. And I also want to use them in rest framework. Is it possible to do so? -
Can I build a serializer that validates username and email existence on is_valid call?
guys! I have this serializer class for the user model class UserSerializer(serializers.ModelSerializer): username = serializers.RegexField("^(?=.{6,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$") full_name = serializers.RegexField("^([a-zA-Z]{2,}\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\s?([a-zA-Z]{1,})?)") email = serializers.EmailField() phone = serializers.RegexField("^(\+\d{1,2}\s?)?1?\-?\.?\s?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$") class Meta: model = User fields = ['username', 'full_name', 'email', 'password', 'phone'] This is my serializer class for the moment. I want to validate that the username and email does not exist before saving an user. Can I do it without manually writing the validations? And I also need to validate the regex for the username and the email field for the email Thank you! -
Create custom filter in popup of inlines. DjangoAdmin
Is it possible to create filter for one field in object creating in django admin. For example, i need to add Video when creating Collection object, so i create class VideoInline(admin.TabularInline): fields = ('video', ) model = Collection.videos.through But i need to filter videos in this popup by some fields, like created_at and so on. Is it possible to do it? Models: class Collection(CreatedByModel, UpdatedByModel): name = models.CharField( max_length=150, verbose_name='Название подборки', unique=True, ) videos = models.ManyToManyField( Video, through=CollectionVideoLink, verbose_name='Видео подборки', related_name='collection', ) class Video( # noqa: WPS215 SoftDeleteModelMixin, ReversionModelMixin, DirtyFieldsMixin, CreatedByModel, ): uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True, ) class CollectionVideoLink( CreatedByModel, UpdatedByModel, ): video = models.ForeignKey( Video, on_delete=models.deletion.CASCADE, verbose_name='Video', ) collection = models.ForeignKey( 'Collection', on_delete=models.deletion.CASCADE, verbose_name='Collection', ) -
My django project isn't logging out, giving weird error
I'm getting a weird error when I try to log out a user on my django project: This is my logout view: from django.contrib.auth import logout def logout_now(request): logout(request) What is the problem? -
Azure webapp module not found
my webapp is giving me error module not found "dateutil" every 10minutes. When I go into SSH and install it manually with pip install python-dateutil it works for that 10minutes. But after a while it just writes same error. When I put it into requirements.txt it won´t let me put application up. Any reason why is azure app doing this or what to check? Thanks in advance. -
Socket Programming between Django REST API, VUE and Scrapy
Write now my code is able to successfully send a post request to the Django REST API which in result triggers the spider respectively and stores its output to the database successfully. For this cause I am using scrapyd API as you can see in the below code snippet @api_view(['POST']) @permission_classes((permissions.AllowAny,)) def crawlRottenTomatoes(request): print("in crawl tottentomatoes method") url = request.data["url"] if not url: return JsonResponse({'error': 'Missing args'}) if not is_valid_url(url): return JsonResponse({'error': 'URL is invalid'}) domain = urlparse(url).netloc msg_dic = {} try: scrapyd.schedule(project="movie_spider", spider="rottentomatoes", url=url, domain=domain) msg_dic['msg'] = "Spider RottenTomatoes for given url is up and running" except Exception as e: print("exception") msg_dic['error'] = "Error running spider for RottenTomatoes" return JsonResponse(msg_dic, safe=False) But now what I want. Is to have some kind of response back from the scrapyd when it's done crawling and parsing the website/channel for that I came across the WebSockets. I tried to use WebSockets but the problem is scrapyd is a demon itself. I am not really able to send a message to the WebSocket client from the scrappy. Does anyone have any idea of how do to do or can share some resources which can help me with this? -
django Inserting textbox for a debateapp
So I am building this debate app where a question is posted and the user chooses the option to agree,disagree or have a neutral opinion. When the user chooses the option I want them to type the reason in textbox after choosing the option and then submit. After submitting they get to see other users choice. I have build until choosing the options in the vote page and displaying the result but I could not get the textbox. here is my code: models.py from django.db import models from django.conf import settings from django.contrib.auth.models import User class Poll(models.Model): question = models.TextField() option_one = models.CharField(max_length=30) option_two = models.CharField(max_length=30) option_three = models.CharField(max_length=30) option_one_count = models.IntegerField(default=0) option_two_count = models.IntegerField(default=0) option_three_count = models.IntegerField(default=0) #point = models.TextField() def total(self): return self.option_one_count + self.option_two_count + self.option_three_count class textbox_model(models.Model): Poll = models.ForeignKey(Poll,on_delete=models.CASCADE) body = models.TextField(max_length = 5000 , null=False,blank=False) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.body forms.py from django.forms import ModelForm from .models import Poll,textbox_model from django import forms class CreatePollForm(ModelForm): class Meta: model = Poll fields = ['question', 'option_one', 'option_two', 'option_three'] class EditTextbox(forms.ModelForm): class Meta: model = textbox_model fields = ('body',) widgets = { 'body': forms.Textarea(attrs={'class':'form-control'}), } views.py def vote(request, poll_id): poll = Poll.objects.get(pk=poll_id) if request.method == … -
Missing dependencies error trying to install Postgis on Python docker container
I'm trying to add the next libraries to add support for geospatial data to my Django project: binutils libproj-dev gdal-bin postgresql-postgis So I updated my Dockefile with the next line: FROM python:alpine RUN apk update && apk add --no-cache \ binutils \ libproj-dev \ gdal-bin \ postgresql-postgis I know the missing dependencies error is due to I'm using the Linux alpine python image, but I don´t know how to add the corresponding repositories or what are those. -
Django Imagefield not saved
Although I select images in the form, image changes do not saved. Other inputs are saving. Help me pls. HTML: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{settingform}} <button type="submit">Save</button> </form> models.py: from django.db import models class SiteSetting(models.Model): logo = models.ImageField(blank=True, verbose_name="Logo") @property def logo_url(self): if self.logo and hasattr(self.logo, 'url'): return self.logo.url views.py: def SiteSettingsView(request): settings = SiteSetting.objects.all() settingform = SiteSettingForm(instance=settings[0]) if request.method == 'POST': settingform = SiteSettingForm(request.POST, instance=settings[0]) if settingform.is_valid(): settingform.save() return redirect('home') context = { 'settings': settings[0], 'settingform': settingform } return render(request, 'x.html', context) forms.py: from site_setting.models import SiteSetting class SiteSettingForm(forms.ModelForm): class Meta: model = SiteSetting fields = '__all__' -
Import Django settings from app into project settings?
I've got a few projects that all use a 'shared_app'. In that shared_app I have a module named default_settings.py that contains the settings that are used by all projects that have that shared_app. Folder structure is the usual Django structure: project_dir | - project_dir | - settings.py - urls.py - wsgi.py - shared_app | - default_settings.py - ... all other app files ... - other_app - some_other_app - ...other project files.... In my project_dir/settings.py I have these lines: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) exec( open(os.path.join(BASE_DIR, "shared_app", "default_settings.py")).read() ) in globals() # Below this line - I can use any settings from default_settings.py if DEBUG: SESSION_EXPIRE_AT_BROWSER_CLOSE = False The default_settings.py files contains things like: DEBUG = is_debug(os.environ.get("DJANGO_DEBUG")) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY") SESSION_EXPIRE_AT_BROWSER_CLOSE = True There are simply too many settings in default_settings.py to have something like from share_app import THIS, THAT, OTHER There are around 20-30 settings. Is there a better way to do this? Or am I stuck with that slightly confusing, ugly exec() command? Is there anything more 'pythonic'?