Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to stop page reloading for components using react-router-dom with django
I'm trying to implement react-router-dom in a site build using react, redux and django as back end. My Problem is when we click on links created by react-router-dom, It loads right component but reloads the whole page due to which the redux state is lost. I don't want to serve all my requests to server, requests should be handled by react-router-dom without page reload. So my django urls.py looks like from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from django.conf import settings from food import views urlpatterns = [ url(r'^admin/', admin.site.urls), # url(r'^api/', include('hodapp.urls')), url(r'^api/items/', views.ItemList.as_view()), url(r'^api/categories/', views.CategoryList.as_view()), url(r'^', TemplateView.as_view(template_name='index.html')), ] Every request other than admin and api will serve index.html which looks like. {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <!-- Meta --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> {% load static %} <!-- CSS Theme --> <link id="theme" rel="stylesheet" href="{% static '/css/themes/theme-beige.min.css' %}" /> </head> <body> <div id="container"></div> {% render_bundle 'main' %} </body> </html> Webpack serves index.jsx which looks like: import React from 'react'; import { render } from 'react-dom'; import App from './components/App'; import { BrowserRouter as Router} from 'react-router-dom'; const BrowserApp = () … -
How to handle exceptions in a Django database setting?
I have a Django application which gives the operational error: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '172.16.1.38' (111)") When I am giving the wrong port number or IP address in database configuration of setting.py file. For example: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "movement", 'HOST': "172.16.1.38", 'PORT': 3306, 'USER': "adc", 'PASSWORD': "abcde", } } above is the correct configuration of the database access but if I mess with any of the value from PORT, HOST or USER, I am getting the operation error. So, I wanted to know, is there any way to show a message instead of this error? or how can I handle this exception? -
python - read file add 1 to the data and write in file using data frame
It is my input file. comma separated values. It should read the file, convert that into panda dataframe. If any of the values in a row is 1, then all other columns in the same row should be 1. Input file(filter.txt) col1 2 3 4 5 6 abc, 0 0, 0, 0, 0 def, 0, 0, 1, , abc, 0, 1, , , def, 0, 0, 0, 1, xyz, , , , , Expected output step 2 abc, 0 0, 0, 0, 0 def, 0, 0, 1, 1, 1 abc, 0, 1, 1, 1, 1 def, 0, 0, 0, 1, 1 xyz, 1, 1, 1, 1, 1 After that it should group by column 0 and sum the values. So, far my code is, import pandas as pd data = pd.read_csv('Desktop/filter.txt', sep=",", header=None) my_df = pd.DataFrame(data) #what logic i should apply here? summary = my_df.groupby([0]).sum() print summary Expected output step 2 abc, 0, 1, 1, 1, 1 def, 0, 0, 1, 2, 2 xyz, 1, 1, 1, 1, 1 Any help would be appreciated. Thanks. -
Django Rest Framework JWT - Custom Payload with Extend User
I have a Extended User with sample serializers (Profile is Extend User, not Abstract User) { "id": 3, "url": "http://localhost:8000/api/v1/users/demo/", "username": "demo", "first_name": "First", "last_name": "Demo", "profile": { "gender": null, "location": "Sa Pa", "date_of_birth": null, "job_title": null, "phone_number": null, "fax_number": "", "website": "", "intro": "", "bio": "", "interested_in": null, "languages": null, "quotes": null, "nickname": null } } How can I custom payload with all above fields and get it with axios? Now it just get payload: authUser:Object email:"test@gmail.com" exp:1509183691 user_id:1 username:"First Demo" token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImxlY29uZ3RvYW4iLCJ1c2VyX2lkIjoxLCJlbWFpbCI6ImRyYWZ0bGlnb25ncXVhbjdAZ21haWwuY29tIiwiZXhwIjoxNTA5MTgzNjkxfQ.KSEp-7g-SGDbqfspedNwkT1rABFi0UQ45yKDJDTX2zA" I followed with this link: #145 but isn't work Please help me! -
Byte Order Mark (ÿþ) preventing deployment to Heroku
I've been trying to learn Django, and I've been running into some trouble deploying to Heroku. When I try running git push heroku master, I get the following output PS E:\My\Git\Directory> git push heroku master Counting objects: 31, done. Delta compression using up to 8 threads. Compressing objects: 100% (26/26), done. Writing objects: 100% (31/31), 6.71 KiB | 0 bytes/s, done. Total 31 (delta 2), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! The latest version of Python 3 is python-3.6.2 (you are using ÿþpython-3.6.2, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.2). remote: Learn More: https://devcenter.heroku.com/articles/python- runtimes remote: -----> Installing ÿþpython-3.6.2 remote: ! Requested runtime (ÿþpython-3.6.2) is not available for this stack (heroku-16). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to intense-river-64521. remote: To https://git.heroku.com/intense-river-64521.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/intense-river- 64521.git' Running the site on localhost has no problems. My runtime.txt only contains: python-3.5.2 I assumed the issue … -
Django model save related model
I have three models, Person, Role and Student. Person is related to role with ManyToManyField and Student inherits from Person. The code: class Person(models.Model): #fields class Role(models.Model): ROLE_CHOICES = ( ('AL', 'ALUMNO'), #... more choices ) person = models.ManyToManyField(Person) role = models.CharField( 'Rol', max_length = 2, choices = ROLE_CHOICES ) class Student(Person): # fields def save(self, *args, **kwargs): super(Student, self).save(*args, **kwargs) # what code should I put here? I want to, on saving a Student, automatically save a role for him/her ('AL'). As I understand, I can override the save method, but I'm not sure how exactly do this. Thanks. -
redirect(reverse) -- pass form (field_errors) to template
I unsuccessfuly try to pass form (including the field_errors), if form.is_valid() is not true, to the template with a redirect(reverse). I use two different views (TemplateView and FormView) urls.py urlpattern = [ url(r'^(?P<slug>[0-9]+)/$', SomeView.as_view(), name='detail'), #... ] views.py class Form_View(FormView): # ... if form.is_valid(): #... else: return redirect(reverse('detail', kwargs={'slug': var})) template.html <p>Validation: {{form.non_field_errors}}</p> What i already tried: return redirect(reverse('detail', kwargs={'slug': var})) Works, but form is missing return redirect(reverse('detail', kwargs={'slug': var, 'form': form})) NoReverseMatch return redirect(reverse('detail', kwargs={'slug': var}), {'form': form}) form is empty in template / does not show anything -
Github-flavored markdown in django-markdown-deux
Has anyone figured out how to get django-markdown-deux to correctly render github flavored markdown? -
How to send to django template from dictionaries / tuples in a relational manner?
So I have an alphabet dictionary which has the letter name as the key and an integer as an id for the value. (This is used for the jump to navigation at the top of the page which is hardcoded html) Then I have many named tuples. Each one is for a state. It has the alphabet id state name and state id. Then theres many named tuples for partners. Each has a state id, image url, link, and partner name. The part which I am struggling with is how to display these in the template. I want each state to go in an alphabetical manner, to have a jumpto-nav id, and partners in that state. Greatly appreciate any feedback!!! Thanks. Note: the dictionary/tuples are located in views.py -
django.db.utils.OperationalError: (1054, "Unknown column
An interesting issue. Getting Unknown column exception -- Please find the stack trace I try to get new leads list and responded leads. I merge them. When I merge them there is an exception. After debugging its found that new_leads method has exclude of two fields collection and delivery . If we make it one exclude all is well . I mean dont check the other, if we include both the filters we have an issue. I tried using filter/ exclude etc. but it didnt work. Query Set contains following method def all_leads_related_to_user(self, user): """ User new and past leads Use this queryset for performing lead search. """ new_leads = self.new_leads_for_user(user) responded_leads = self.leads_responded_by_user(user) all_leads = (new_leads | responded_leads).distinct() <= Issue is here. return all_leads def new_leads_for_user(self, user): .... # User's location filter if user.sub_region_excluded_list: sub_region_exclude_list = [10, 12] qs = qs.exclude( Q(collection_point__sub_region_id__in=sub_region_exclude_list) | Q(delivery_point__sub_region_id__in=sub_region_exclude_list)) # <== Make it just one exclude it works. Model class Suburb(models.Model): state = models.ForeignKey(State, blank=False) sub_region = models.ForeignKey(SubRegion, blank=False) postcode = models.CharField(_('postcode'), blank=False, max_length=10) name = models.CharField(_('suburb name'), blank=False, max_length=200) class Load(models.Model): ..... collection_point = models.ForeignKey(Suburb, related_name='collection_point', on_delete=models.SET_NULL, null=True) delivery_point = models.ForeignKey(Suburb, related_name='delivery_point', on_delete=models.SET_NULL, null=True) Stack Trace:- >>> Load.objects.all_leads_related_to_user(User.objects.all()[0]) Load.objects.all_leads_related_to_user(User.objects.all()[0]) Traceback (most recent call … -
How to send message from kafka/spark to websocket?
I'm designing an Analytic platform using kafka as message queue and Django for web app. But I don't know how to build real-time dashboard with data get from kafka. So I don't know something below: 1) Could we get data from kafka and emit to websocket? ( django framework) 2) Could we use spark for this ( store to casandra and get data from kafka and emit to web socket) If you have any ideas or document please share to me. Thanks & Best Regards, jame -
Django on Google App Engine: "Instance names cannot contain the ':' character."
I am following this tutorial to run a Django project on Google AppEngine. I have reached the steps to create a Cloud SQL instance. When I follow these steps I get the following error: $ gcloud sql instances describe django-polls-184415:us-west1:polls ERROR: (gcloud.sql.instances.describe) Instance names cannot contain the ':' character. If you meant to indicate the project for [polls], use only 'polls' for the argument, and either add '--project django-polls-184415:us-west1' to the command line or first run $ gcloud config set project django-polls-184415:us-west1 When I follow the instructions in the error message, I get $ gcloud config set project django-polls-184415:us-west1 Updated property [core/project]. $ gcloud sql instances describe polls ERROR: (gcloud.sql.instances.describe) HTTPError 403: The client is not authorized to make this request. What am I doing wrong? And more importantly how do I do it correctly? -
How do you make SQL return duplicates?
When running an SQL such as the following; SELECT * FROM items WHERE item_name IN ('fish', 'frog', 'fish') I get 1 frog, and 1 fish. This is expected and normal behaviour, as the WHERE clause no doubt evaluates against each row in the database individually. However, in my current application I need a full row returned for each item in the WHERE clause. The way I'm currently doing it is fetching the full contents of the IN statement, then running a second query fetching each of those objects. In python, I am then duplicating the rows as required. But if I could get sql to do it for me, it'll mean 1 less round trip to the database. Can you force a database to return a response per entry in an IN? Example data; items id | name | price 1 | frog | 4 2 | fish | 3 objects for users id | user_id | item_name 1 | 1 | fish 1 | 1 | frog 1 | 1 | fish I'm aware that item_name should be a foreign key to item instead - but for frustrating legacy reasons, this is not currently possible. An ideal solution would … -
Django upload model - user permissions
I am creating a file upload page which has a file upload model: models.py class Upload(models.Model): file = models.FileField(blank=True, null=True, validators=[validate_file_extension]) upload_date = models.DateTimeField(auto_now_add=True) class Meta: permissions = ( ('can_upload_x', 'Can Upload X'), ('can_upload_y', 'Can Upload Y'), ('can_upload_z', 'Can Upload Z'), ) forms.py class UploadFileForm(forms.ModelForm): class Meta: model = Upload fields = ['file'] html {% if perms.app.can_upload_x %} <form action="#" method="post" enctype="multipart/form-data"> <input type='hidden' name='action' value='x'> {% csrf_token %} {{form_x}} <input type="submit" value="Upload" id="weights_btn" name="weights_btn" class="btn btn-default btn-file"/> </form> {%endif%} #etc for X, Y, Z, .... So the end goal is for the users assigned to have certain permissions from the admin like 'can_upload_x' will only be able to see the form for X etc ( I make different forms save to different locations with handle_uploaded_file in the views). What am I doing wrong? does not seem to work. It did, however work when I had a model for each form but it is unfeasible for my project since I might have to have a whole lot of different forms. Thank you! -
redirect to view from another view NoReverseMatch error django
Helo everyone, I have two views but I can't redirect to view from another view. Before asking this question I tried some solutions from stackoverflow, but they they didn't bring any result. Please help. VIEWS.py def new_room(request): new_room = None while not new_room: with transaction.atomic(): label = haikunator.haikunate() if Room.objects.filter(label=label).exists(): continue new_room = Room.objects.create(label=label) return redirect('chat', label=label) def chat(request, label): room, created = Room.objects.get_or_create(label=label) messages = reversed(room.messages.order_by('-timestamp')[:50]) return render(request, "chat/room.html", { 'room': room, 'messages': messages, }) Thanks in advance! -
every url is redirected to gitlab page
I wanted to have gitlab CI and django in digital ocean. I created a droplet and configured the gitlab with the following settings external_url = "http:/lab.###.com/" # gitlab_rails['gitlab_email_from'] = "gitlab@example.com" # gitlab_rails['gitlab_support_email'] = "support@example.com" # gitlab_rails['smtp_enable'] = true # gitlab_rails['smtp_address'] = "smtp.server" # gitlab_rails['smtp_port'] = 465 # gitlab_rails['smtp_user_name'] = "smtp user" # gitlab_rails['smtp_password'] = "smtp password" # gitlab_rails['smtp_domain'] = "example.com" # gitlab_rails['smtp_authentication'] = "login" # gitlab_rails['smtp_enable_starttls_auto'] = true # gitlab_rails['smtp_openssl_verify_mode'] = 'peer' # nginx['redirect_http_to_https'] = false # nginx['ssl_certificate'] = "/etc/gitlab/ssl/gitlab.crt" # nginx['ssl_certificate_key'] = "/etc/gitlab/ssl/gitlab.key" and here is my nginx settings server { listen 80; server_name 150.200.##.## abc.com www.abc.com; client_max_body_size 50M; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/root/eatplus-django; } location / { include proxy_params; proxy_pass http://127.0.0.1:8000/; proxy_redirect off; # proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_connect_timeout 30; proxy_read_timeout 30; } } when i enter lab.##.com, I am redirected to gitlab which is expected but when entering ip address and www.###.com I am still redirected to gitlab page which is unexpected behavior. How do i resolve this? -
How to achieve left join without where clause in Django
House.objects.filter(owner__isnull=True) will produces following SQL: SELECT "app_House"."id", "app_House"."name" FROM "app_House" LEFT OUTER JOIN "app_Owner" ON ("app_House"."id" = "app_Owner"."house_id") WHERE "app_Owner"."id" IS NULL Is there a syntax available to force Django to omit the where clause? -
How to connect Django's built-in username and password fields to user-defined html input tags
I have used a pre-defined html template for my login form and I have tried to connect the django's standard/built-in username and password fields namely {{ form.username }} and {{ form.password }} to the input fields of the html template. It works fine, but it populates the fields with None in both of the username and password fields everytime a user is redirected to the login page. When using the {{ form.username }}and{{ form.password }}` template tags, they are populated with valid user credentials. Is this normal or I am missing something here? Here is the code that I have tried to use an input field instead of Django's built-in username and password field: <!-- username input field--> <div class="group"> <label for="{{ form.username.id_for_label }}" class="label">Username</label> <input id="{{ form.username.id_for_label }}" maxlength="100" name="{{ form.username.html_name }}" value="{{ form.username.value }}" type="text" class="input"> </div> <!-- password input field--> <div class="group"> <label for="{{ form.password.id_for_label }}" class="label">Password</label> <input id="{{ form.password.id_for_label }}" maxlength="100" name="{{ form.password.html_name }}" value="{{ form.password.value }}" type="password" class="input"> </div> -
Setting up a Webpack Configured Vuejs Admin with Django REST API Backend
I need help on how to plugin an existing Vuejs Project (e.g. an Admin Dashboard) to a Django Project with Rest API, I'm having some issues with the Webpack configuration. I went through this: https://ariera.github.io/2017/09/26/django-webpack-vue-js-setting-up-a-new-project-that-s-easy-to-develop-and-deploy-part-1.html But still need help in reusing the Vuejs Admin with the Django Project. -
Show Validation Errors -- TemplateView, FormView
I have a template with multiple forms, but i can not figure out how to show the validation errors. For simplification i show only one form and how i try to update 'hostname' of the model Protocol. As soon i always raise a validation error (just for testing) in forms.py with: def clean(self): raise forms.ValidationError("Validation Error Test") I get the message: AttributeError at /add_hostname/666666/ 'str' object has no attribute 'get' If i remove clean() the update works fine -- but i want to validate some things in there. I guess i can not use the line of code in views.py when the form is not valid? return reverse('protocol-detail', kwargs={'slug': self.kwargs['protocol_id']}) What is the right way to go? models.py class Protocol(models.Model): protocol_id = models.PositiveIntegerField(unique=True) hostname = models.CharField(max_length=12, blank=True) #... views.py class Protocol_Detail_View(TemplateView): template_name = 'app_name/template.html' def get(self, request, *args, **kwargs): comment_form = Comment_Form(self.request.GET or None) hostname_form = Hostname_Form(self.request.GET or None) task_form = Task_Form(self.request.GET or None) context = self.get_context_data(**kwargs) # protocol_id = self.kwargs['slug']) context['protocol'] = Protocol.objects.filter(protocol_id=self.kwargs['slug']).get() context['comment_form'] = comment_form context['hostname_form'] = hostname_form context['task_form'] = task_form return self.render_to_response(context) class Hostname_Form_View(FormView): form_class = Hostname_Form def post(self, request, *args, **kwargs): hostname_form = self.form_class(request.POST) if hostname_form.is_valid(): Protocol.objects.filter(protocol_id=self.kwargs['protocol_id']).update(hostname=request.POST['hostname']) return super(Hostname_Form_View, self).form_valid(hostname_form) else: return reverse('protocol-detail', kwargs={'slug': self.kwargs['protocol_id']}) def … -
How to update an instance in Django rest framework?
I have a question about how I can update an instance in django rest framework. So basically I want to update my user profile through an request but I cannot get current user Id. Is there a better way to get current user and update its information? This is not working because request.user is always anonymous. @api_view(['POST']) def update_profile(request): serializer = AccountSerializer(request.user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Thank you so much! -
Django REST API Multiple Records Same Category
There is a problem with Django Rest API , i have a 2 records in my creators table. first records have category "gaming" and the second record have category "Education" all is ok for now , but when i add Thirds record with Category "Education"(same category of first record ) then i got the error when i call all records of That Category(gaming). i want the multiple records of same category model.py class Creators(models.Model): title=models.CharField(max_length=200) link = models.CharField(max_length=200) subscriber = models.PositiveIntegerField() country = models.CharField(max_length=100) email = models.CharField(max_length=100) description = models.TextField(max_length=2000) category = models.CharField(max_length=100) socialLinks = models.TextField(max_length=2000) class Meta: ordering = ('title',) serializer.py class CreatorsSerializer(serializers.ModelSerializer): class Meta: model = Creators fields = "__all__" views.py class CreatorsList(APIView): def get(self,request,category): creator = Creators.objects.get(category=category) serializer = CreatorsSerializer(creator) return Response(serializer.data) def post(self): pass urls.py url(r'^creators/(?P<category>\w+)/$', views.CreatorsList.as_view()), when i run example.com/creators/Gaming/ then it gives me perfect output(for now i just have 2 records) { "id": 1, "title": "channel1", "link": "https://www.youtube.com/channel/UCJbPGzawDH1njbqV-D5HqKw", "subscriber": 2000, "country": "PK", "email": "ishaq@gmail.com", "description": "ddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnknd", "category": "Gaming", "socialLinks": "ddkndkndkdknkdnkndddkndkndkdknkdnkndddkndkndkdknkdnknd" } but when i added third records of same category (Gaming) the error shows MultipleObjectsReturned at /creators/Education/ get() returned more than one Creators -- it returned 2! i also added many=True in views.py but … -
How to load data from Django to a variable for a D3 graph
I want to know how can I update a variable from a backend in Django, and update the graph I am building on the front end with D3, without refreshing the page, that is, do the update dynamically. I managed to update the graph, but each time I change the parameters in the form in the front-end, it renders the whole page, I just want to update the data and refresh the graph in D3. Here is my view: def growth(request): parsedData = [] if request.method == 'POST': year_input = request.POST.get('years') year_input_int = int(year_input) growth_data = requests.get('https://www.ons.gov.uk/economy/grossdomesticproductgdp/timeseries/ihyp/qna/data') # jsonList = [] # jsonList.append(json.loads(growth_data.content)) parsed_json = json.loads(growth_data.content) growthData = {} data_input = 'years' for data in parsed_json[data_input][year_input_int:]: growthData['date'] = data['date'] growthData['value'] = data['value'] growthData['year'] = data['year'] parsedData.append(growthData.copy()) return render(request, 'dashboard/growth.html', { 'growth_json': json.dumps(parsedData) }) Here is my form HTML, <form method= "post" action="/indicators/growth/"> {% csrf_token %} <br> <select type="text" name="years"> <option value="60">2009</option> <option value="61">2010</option> <option value="62">2011</option> </select> <br> <button type="botton">Get Data</button> </form> -
Send error mail to admin in Django
I am trying to send a mail to ADMIN when any exception is occurred in django. So i tried but not able to find the solution. I don't have a clear idea about how to send a error mail to admin Any help would be appreciated. Views.py def emit(self, record): try: request = record.request subject = '%s (%s IP): %s' % ( record.levelname, ('internal' if request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS else 'EXTERNAL'), record.getMessage() ) filter = get_exception_reporter_filter(request) request_repr = '\n{}'.format(force_text(filter.get_request_repr(request))) except Exception: subject = '%s: %s' % ( record.levelname, record.getMessage() ) request = None request_repr = "unavailable" subject = self.format_subject(subject) if record.exc_info: exc_info = record.exc_info else: exc_info = (None, record.getMessage(), None) message = "%s\n\nRequest repr(): %s" % (self.format(record), request_repr) reporter = ExceptionReporter(request, is_email=True, *exc_info) html_message = reporter.get_traceback_html() if self.include_html else None self.send_mail(subject, message, fail_silently=True, html_message=html_message) def send_mail(self, subject, message, *args, **kwargs): mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs) def connection(self): return get_connection(backend=self.email_backend, fail_silently=True) def format_subject(self, subject): """ Escape CR and LF characters, and limit length. RFC 2822's hard limit is 998 characters per line. So, minus "Subject: " the actual subject must be no longer than 989 characters. """ formatted_subject = subject.replace('\n', '\\n').replace('\r', '\\r') return formatted_subject[:989] def test_view(request): try: raise Exception except Exception as … -
Global variable in a module, read after multiple write
I am working on Django project, but this question could also be Python generic. Answers that utilize specific Django feature can also be accepted. I am trying to define a global variable as a dict in a module. I require that this variable can be accessed by other module. The difficult part is, this global variable can be set/update multiple times by indefinitely many other modules at build time. After all the set/update, the variable can be read to set some other global variables in a fixed number of modules. How should I make sure that all the read happen after the set/update? Demo code: I want to have a GLOB at setting.py of module m: At m/setting.py: GLOB = dict() Some other modules (indefinitely many, assume they are p, q and r) will need to update this variable: At p/config.py: from m.setting import GLOB GLOB['p'] = 1 At q/config.py: from m.setting import GLOB GLOB['q'] = 2 At r/config.py: from m.setting import GLOB GLOB['r'] = 3 Two modules (fixed many, assume they are a and z) will need to read from this variable and do other stuff: At a/config.py: from m.setting import GLOB A_GLOB = [k for k in GLOB …