Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot set [MODEL] SpatialProxy (POLYGON) with value of type: <class 'django.contrib.gis.geos.polygon.Polygon'>
This is the same error than here but not the same problem. I've made my model this way: from django.contrib.gis.db.models import PolygonField from django.db import models class MyWay(models.Model): way = PolygonField(default=None) I'm reading a text file consisting of binary (valid + tested) values, example: '0106000020E610000001000000010300000001000000040000001F477364E5C71540C233A14962C34540419DF2E846C815404ACFF41263C34540A7E7DD5850C815408448861C5BC345401F477364E5C71540C233A14962C34540' When I try to do zone = GEOSGeometry(str('...(big text above)...')) MyWay.objects.create(way=zone,) I get this error. How can I make this work? -
Django model custom field
I'm trying to implement custom field in my model following the docs, My model is as follow: class User(AbstractUser): uid = models.CharField( "uid", max_length=255, null=True, blank=True) phone_number = models.CharField( "Phone number", max_length=255, null=True, blank=True) nickname = models.CharField( "Nickname", max_length=255, null=True, blank=True) eth_address = models.CharField("Eth address", max_length=255, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) # deleted class eth_address_decrypted(models.Field): description = 'eth_address_decrypted' def __init__(self, *args, **kwargs): return decrypt_string(self.eth_address) class Meta: db_table = "users" pass I have a eth_address field that it's value are encrypted, i need to display the decrypted value on the frontend, so i wrote custom field model as the docs and call it on my front end through query: User.objects.get(eth_address_decrypted=value) But it returning the following error: Cannot resolve keyword 'eth_address_decrypted' into field. Choices are: created, date_joined, email, eth_address, What am i doing wrong ? -
Django form params contain brackets
I want to use Django form to validate the POST Parameters of a request I get from a third party. The post params names are like this: 'a[b]' (as a string) So, I want to set a form that will look something like this: class MyValidationForm(forms.Form): a[b] = forms.CharField() But obviously this results in an error. Is there a way to set a form that accepts field names with brackets? -
Django transaction roll back while updating record
I have CSV file which updates records in bulk. CSV format: id amount 4 100 5 200 6 five --> error 7 400 I want to roll back to the previous state of data if there is an error in CSV data. Like in above CSV id 6 has a string and my column in the database is an integer so it will throw an exception. views.py from django.db import transaction lines = csv.reader(my_csv.csv) for line in lines: try: MyModel.objects.filter(id=line[0]).update(amount=line[1]) except: transaction.rollback() break We my code goes in exception for id 6 new data is getting update . -
Django: phone verification for inactive account
I'd like to implement phone verification with pyotp in my view class-based Django (2.5) project. After new users sign up (specifying name, phone, e-mail and password) in RegisterView, they should be redirected to GetAccessCodeView with an input field for verification code and a hidden field with a secure token. For generating and sending the code and the token I have to pass there a newly created user instanse from RegisterView to GetAccessCodeView. How can I do that? Currently newly created users have is_active field set to False (it should become True after code succesful verification), thus cannot be authorized by default, so without changing login procedure, it is impossible to use request.user directly. But if I let inactive users to log in, then all the login_required views will let unconfirmed users to open corresponding pages. Should I write is_active check for each view manually or maybe Django has some ready stuff like 'login_and_active_required'? Or maybe there is some different solution? -
Django page loading time too slow due to long TTFB time
One of the pages in my Django app is loading very slowly. It contains a formset table with 30 items. The TTFB fime (time to first byte) is 14 seconds. If I have more rows, for example 50 rows, the TTFB time is about 30 seconds. The performance test in Chrome developer tools shows a large part where my page is idle. What can I do to find out how to improve performance? -
Error module 'tablib.formats._xls' has no attribute 'title'
I have an issue in django, after click in import button in django admin site. This is my code code in admin.py from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(ImportExportModelAdmin): pass in models.py from django.db import models from django.conf import settings from import_export.admin import ImportMixin class Person(models.Model): name = models.CharField(max_length=30) email = models.EmailField(blank=True) birth_date = models.DateField() location = models.CharField(max_length=100, blank=True) Error Image -
Django Calculate Mean Of 2 Fields Inside Multiple Objects
I'm trying to do a very simple math problem but I don't know how to convert it into python. Basically I need to calculate the mean entry price for a trade based on multiple entries. To do that all one needs to do is calculate ∑ (entry.amount * entry.price) / ∑ (entry.amount) This should be the variable "total_entry_price2" in the end. Where am I going wrong with the calculation? How Can I add all the ∑'s together? Is this the best way to do it? models.py class Trade(models.Model): ... class Entry(models.Model): ... trade = models.ForeignKey(Trade, on_delete=models.CASCADE) amount = models.FloatField() price = models.FloatField() entry_type = models.CharField(max_length=3, choices=ENTRY_TYPE_CHOICES, default=BUY) views.py @login_required def trade_detail_view(request, pk): logger.info('trade detail view') if request.method == 'GET': trade = get_object_or_404(Trade, pk=pk) entries = Entry.objects.filter(trade=trade) entries_buy = Entry.objects.filter(trade=trade, entry_type="buy") patterns = Pattern.objects.filter(trade=trade) for entry in entries_buy: total_entry_price = Sum(entry.amount * entry.price) total_entry_price2 = total_entry_price / entries_buy.aggregate(Sum('amount')) print(total_entry_price2) context = { 'trade': trade, 'entries': entries, 'patterns': patterns, 'max_amount': entries_buy.aggregate(Sum('amount')), 'total_fees': entries.aggregate(Sum('fee')), 'entry_price': entries_buy.aggregate(Avg('price')) } Current Terminal print: Sum(Value(60.0)) / Value({'amount__sum': 40.0}) Sum(Value(10.0)) / Value({'amount__sum': 40.0}) Example data -
In Python, how to use TTS in my web template
On my website I've got a "Description" and I want to use gTTS(using pip install gTTS) to make it speak. How do I achieve this? I now know how to use gTTS on the command shell but how can I use that in my template/myhomepage.html? Any help will be much appreciated. -
How can i create custom validation in django model forms
I want to create a custom form validation in Django forms. I am able to do it normal Django forms but unable to do it in model forms. my Django form code is class Post_Article(forms.Form): title = forms.CharField(label = 'Title',max_length = 100) abstract = forms.CharField(widget = forms.Textarea, max_length = 300) body = forms.CharField(widget = forms.Textarea) image = forms.ImageField(required = False) hash_tags = forms.CharField(max_length = 50,required = False) def no_of_hash_tags(self): cleaned_data = super().no_of_hash_tags() tags = cleaned_data.get('hash_tags') if tags: tags = split(str(tags)) if len(tags) > 5: raise forms.ValiadationError('Maximum 5 tags are allowed') the Django model is class PostsArticle(models.Model): title = models.CharField(max_length=255) pub_date = models.DateTimeField(default= timezone.now) abstract = models.TextField() body = models.TextField() image = models.ImageField(upload_to=('images/'),blank=True) user = models.ForeignKey(User , on_delete = models.CASCADE) hash_tags = models.CharField(max_length = 50,blank= True) def _str_(self): return self.title def get_absolute_url(self): return reverse('home') def summary(self): return self.absract[:200] def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') def link_tags(self): cleaned_data = super().link_tags tags = cleaned_data.get['hash_tags'] for tag in tags: hashing(tag,"PostsArticle") kindly help how can I add form validation to my model -
Override class attribute for pkl model file processed in celery
I have model that is used for prediction of topic in text that works with external class. Given that process is implemented on Django platform it goes through celery wrapped task. So there is problem with imports of that class. This is celery task, some of code is removed due non-disclosure and its not mandatory for solution from <Full path> import TopicModel def process_prediction(data, field, model): predict_data = [] for doc in data: predict_data.append(doc.get(field, doc['content'])) prediction = model.predict(predict_data) for pred, doc in zip(prediction, data): logger.info("This was predicted {}".format(pred)) if "tags" not in doc: doc["tags"] = [] doc["tags"].append({"name": pred, "type": "topic"}) return zip(prediction, data) import and this function is later called through task and some other functions: @app.task(name='<path>', bind=True, base=DatabaseTask) def top_mod(self, inputf, outputf, extra=None): self.update_state(state="PROGRESS", meta={'progress': 0}) try: if extra and extra.get('search_query', ''): inputf['query'] = extra['search_query'] self.file_asset = FileAssets.get_asset() self.file_asset.get_file(extra.get('model_filename')) with open(<PATH.), extra.get('model_filename')), 'rb') as model_filename: model = pickle.load(model_filename) loop = asyncio.get_event_loop() task = loop.create_task(process(inputf, outputf, extra.get('field', 'content'), model, extra.get('threads', 2), extra.get('job_id', ''))) loop.run_until_complete(task) return True except Exception as e: logger.error("Exception occured in run topic. Message: {}".format(str(e))) job_status = JobStatus(extra.get('job_id'), top_mod.session) current_state = job_status.read_state() current_state['status'] = 'error' current_state['message'] = "Error occured in creating task" job_status.write_state(current_state) return False pkl model uses … -
Best practice for API design using Django and PostGIS
I'd like to move an existing GIS web app embedding both the web application and the PostGIS database to separated GIS API and Web app. The underlying idea is to differenciate data provider (postgis layers) from the end-user application. I'm thinking about this because of infrastructure issues (put the computation intensive part elsewhere from the web server), data reuse and evolutivity (adding new layers in the future). For now on, I focus on the API design. My data is related to multiple indicators (mostly polygons) on a delimited geographical area. Do you think it is a good idea to design such API ? And is there any good practice (database model, API routes, etc.) for doing so with Django Rest Framework, GeoDjango, and PostGIS ? Like, for example, should I think of one Django model (postgis table) per layer (indicator) with a dedicated route for each ? If some of you have already worked on similar projects, I'd love to hear your feedback ! (Maybe it is not the best place to ask so feel free to point me some appropriate channels) -
Cannot request data using fetch (JS) from Django REST Framework API
I am trying to send a POST request to my Django REST Framework API at localhost:8000. I receive the Django response when Postman sends the request, but I receive a console error on my React.js application using the fetch() function. I see that, for the React.js app's request, an OPTIONS request is sent to the Django backend. This is the error I receive on the React app. Access to fetch at 'http://localhost:8000/api/admin/login/' from origin 'http://ucla.localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. Here is my JavaScript code. fetch(authenticateUrl, { method: "POST", credentials: "include", headers: { Accept: "application/json", 'Content-Type': "application/json", 'Access-Control-Allow-Origin': '*',//"http://localhost:8000", }, body: JSON.stringify({ username, password }), signal: abortLoginController.signal }) Here is my Django settings.py MIDDLEWARE = [ 'django_hosts.middleware.HostsRequestMiddleware', #'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_hosts.middleware.HostsResponseMiddleware', ] ... CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True # CORS_ORIGIN_WHITELIST = ( # 'http://sub.localhost:3000', # 'http://localhost:3000' # ) SESSION_COOKIE_SAMESITE = None -
validation in django templates
I have a django template in which I wanna show the user only if it's name is emp for which I am using the following code: HTML {% if warehouse.warehouse.owner == emp %} <td class="align-middle">{{ warehouse.warehouse.owner }}</td> {% endif %} It's not working but when I use this without the if condition it shows emp in the template. How do I equate both of them in the template ? -
how to save 3 forms of one model in django?
models.py class Campaign(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # this is many to one relationship, on_deleting user, profile will also be deleted funds_for = models.CharField(max_length=200) campaign_title = models.CharField(max_length=200, blank=True) amount_required = models.IntegerField(null=True, blank=True) campaign_image = models.ImageField(default="default_campaign.png",upload_to="campaign_pictures") forms.py class RaiseFundsFrom1(forms.ModelForm): class Meta: model = Campaign fields = ['funds_for'] class RaiseFundsFrom2(forms.ModelForm): class Meta: model = Campaign fields = ['campaign_image'] class RaiseFundsFrom3(forms.ModelForm): class Meta: model = Campaign fields = ['campaign_title','amount_required'] views.py @login_required def raise_funds_medical_1(request): if request.method == 'POST': form = RaiseFundsFrom1(request.POST) if form.is_valid(): request.session['funds_for'] = form.cleaned_data.get('funds_for') return redirect('funds:raise_funds_medical_2') else: form = RaiseFundsFrom1(instance=request.user) return render(request,'funds/raise_funds_medical_1.html',{'form':form}) @login_required def raise_funds_medical_2(request): if request.method == 'POST': form = RaiseFundsFrom2(request.POST, request.FILES or None) if form.is_valid(): f = request.FILES['campaign_image'] request.session['campaign_image'] = f.name return redirect('funds:raise_funds_medical_3') else: form = RaiseFundsFrom2(instance=request.user) return render(request,'funds/raise_funds_medical_2.html',{'form':form}) @login_required def raise_funds_medical_3(request): if request.method == 'POST': form = RaiseFundsFrom3(request.POST) if form.is_valid(): request.session['campaign_title '] = form.cleaned_data.get('campaign_title') request.session['amount_required '] = form.cleaned_data.get('amount_required') c = Campaign() c.funds_for = request.session['funds_for'] c.campaign_image = request.session['campaign_image'] c.campaign_title = request.session['campaign_title'] c.amount_required = request.session['amount_required'] c.save() return redirect('core:landing_page') else: form = RaiseFundsFrom3(instance=request.user) return render(request,'funds/raise_funds_medical_3.html',{'form':form}) I need to get details for campaign model in 3 parts. I need to do in a specific order, with the second form requiring to be only an image upload. My plan is to capture the required … -
creating order from orderitem drf
i am trying to create order from orderitem. problem is how can i pass orderitem object to order.item field: models.py: class OrderItem(models.Model): image_number = models.CharField(max_length=20) title = models.CharField(max_length=20) image_size = models.CharField(max_length=50) file_type = models.CharField(max_length=20) price = models.CharField(max_length=50) def __str__(self): return self.title class Order(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True,null=True) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateField(auto_now_add=False,blank=True,null=True) ordered = models.BooleanField(default=False) def __str__(self): return str(self.user) serializers.py: class AddtocartSerializers(serializers.ModelSerializer): class Meta: model = OrderItem fields = ['image_number','title','image_size','file_type','price'] class CartSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all()) items = serializers.ListField(child=serializers.PrimaryKeyRelatedField(queryset=OrderItem.objects.all(), required=True), required=True) ordered_date = serializers.DateField() class Meta: model = Order fields = ['user', 'items', 'ordered_date'] views.py: class AddtocartView(generics.CreateAPIView): authentication_classes = [] permission_classes = [IsAuthenticated] pagination_class = None queryset = OrderItem.objects.all() serializer_class = AddtocartSerializers def create(self,queryset): data = { 'items': queryset, #'user': user.email } Order.objects.create(**data) class CartView(generics.ListAPIView): authentication_classes = [] permission_classes = [] pagination_class = None queryset=Order.objects.all() serializer_class = CartSerializer urls.py: path('addtocart/',views.AddtocartView.as_view(),name='addtocart'), path('cart/',views.CartView.as_view(),name='cart'), error: Direct assignment to the forward side of a many-to-many set is prohibited. Use items.set() instead. Is there any better way to create order please suggest........................................................................ -
many to many Relationship Data fetching
I have two models(columns) with many to many relations. class ClinicHospital(models.Model): name = models.CharField(max_length = 256) address = models.TextField() contact = models.CharField(max_length = 15) lat = models.FloatField() lon = models.FloatField() def get_absolute_url(self): return reverse("clinichospital_list") def __str__(self): return self.name class Doctor(models.Model): name = models.CharField(max_length = 256) speciality = models.CharField(max_length = 256) contact = models.CharField(max_length = 12) clinic_hospital = models.ManyToManyField(ClinicHospital) def __str__(self): return self.name I want to fetch all ClinicHospital which is associated with a specific Doctor. here is my view.py class DoctorDetailView(generic.DetailView): model = Doctor def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context[ClinicHospital] = ClinicHospital.objects.all() return context and it is my HTML page {% for clinic in doctor_detail %} <tr> <td class="text-center">{{clinic.name}}</td> </tr> {% endfor %} -
Django template not receiving value from URL
Good day Django experts and enthusiasts! I have the following situation (source code is at the end of this post): I have one template that is used by DetailView for post model (i.e. show detail of particular instance of post). In this template, I have context_object_name post in the template - that object has an ID. In this DetailView, there is an URL link to another CreateView template. That create view is for comment model. There is foreign key relationship between post and comment - one post can have 0 - more comments. When I click on DetailView for post, I have a link for CreateView for comment. When user is writing a comment for post and hits save button, I need to have post.id available in the template in the template for CreateView (I would like to send it as hidden field in form for comment so that comment model has post.id available in save() method - that would cover the need for foreign key when saving comment). Now to the merit of my problem: I would like to send a post.id from DetailView template to CreateView template (so I can use it as hidden form). Problem is, post.id … -
Gunicorn workers restarted after waiting for a long time
I serve 3 deep learning models with PyTorch, django, gunicorn and Nginx (as reverse proxy). The latency of HTTP request is just 200ms. CUDA_VISIBLE_DEVICES=3 gunicorn MyAPP.wsgi -b MY_IP:8008 -w 4 However, if the service receives no HTTP requests for a long time (e.g. 12h), and you suddenly call the API. The waiting workers will exit and restart, which results in overtime of this request (Since the initialization of deep learning models need few seconds). [2020-01-15 16:26:12 +0800] [573948] [CRITICAL] WORKER TIMEOUT (pid:977770) [2020-01-15 08:26:12 +0000] [977770] [INFO] Worker exiting (pid: 977770) [2020-01-15 16:26:13 +0800] [978149] [INFO] Booting worker with pid: 978149 [2020-01-15 16:26:38 +0800] [573948] [CRITICAL] WORKER TIMEOUT (pid:573958) [2020-01-15 08:26:38 +0000] [573958] [INFO] Worker exiting (pid: 573958) [2020-01-15 16:26:39 +0800] [978295] [INFO] Booting worker with pid: 978295 So is there a way to config gunicorn to keep the started workers alive despite there is no HTTP request at present? -
url does not match in form action (python django)
views def Editprograme1(request,addprogrammodel_id): try: username1 = request.session.get("ChooseUserName") except AddProgramModel.DoesNotExist: raise Http404('<h1>page not exist</h1>') return render(request, 'addprograme1.html', {'member_data': member_data}) URL: url(r'^Editprograme1/(?P<addprogrammodel_id>[0-9]+)/$', views.Editprograme1, name='Editprograme1'), html form: form method="post" action="{% url 'nwe1:Editprograme1' %}" enctype="multipart/form-data" Error: NoReverseMatch at /Editprograme1/1/ Reverse for 'Editprograme1' with no arguments not found. 1 pattern(s) tried: ['Editprograme1/(?P[0-9]+)/$'] -
How to create UpdateView Form that include both main model and its ForeignKey in same html?
I have a model that i would like to include Update using UpdateView form using Main model and its related ForeignKey , so desired resault would include both main model object and all its related ForeignKey objects My model and view shown below as follows Please advice Thanks Model class MainTask(models.Model): task_title = models.CharField(max_length=200) global_task_info = models.TextField(max_length=500,default=None) complete = models.BooleanField(default=False) overall_precent_complete = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(default=datetime.datetime.now()) updated_at = models.DateTimeField(default=datetime.datetime.now()) due_date = models.DateTimeField(default=datetime.datetime.now()) task_location = models.CharField(max_length=400, blank=True, null=True) global_task_assign = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="global_task_assign",default=1) TASK_STATUS_CHOICES = [ ('ST', 'STARTED'), ('NS', 'NOT STARTED'), ('IP', 'IN PROGRESS'), ('PA', 'PAUSED'), ('CO', 'COMPLETED'), ] task_status = models.CharField(max_length=2,choices=TASK_STATUS_CHOICES,default='NOT STARTED') def __str__(self): return self.task_title class ChildTask(models.Model): # Relationship Fields item_main = models.ForeignKey('MainTask',on_delete=models.CASCADE, related_name="item_main", ) task_description = models.CharField(max_length=200) task_info = models.TextField(blank = True) task_complete = models.BooleanField(default=False) sub_task = models.CharField(max_length=200) task_precent_complete = models.PositiveIntegerField(default=0) task_created = models.DateTimeField(default=datetime.datetime.now()) task_updated_at = models.DateTimeField(default=datetime.datetime.now()) task_due_date = models.DateTimeField(default=datetime.datetime.now()) task_assign = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="task_assign",default=1) def __str__(self): return self.task_description View class TaskIdUpdateView(UpdateView): model = MainTask template_name = "taskid_update.html" form_class = TaskUpdateForm fields = '__all__' -
Django Template - use same block twice with different variables
I have a block called car_table and two kind of cars: blue and red. I want a template with two tables, one for the red cars and one for the blue cars, but I want to use just the 'general' block car_table. in base_template.html I define the headers and general stuff <!DOCTYPE html> blablabla... {% block content %}{% endblock %} </html> here is cars_table.html {% extends base_template.html %} {% block content %} blablabla... {% block table %} ... {% for car in cars %} <tr> <td>{{ car.name }}</td> </tr> {% endfor %} {% endblock %} {% endblock %} Now, I want a page with two tables: blue cars and red cars, using just the code in cars_table -
Calling view from multiple pages in Django
My url pattern, shown below is being called via ajax. When called from homepage, it's okay, the url looks like http://10.165.12.167:3333/13/devices/ when calling from another page it gives 404 as it cannot find the given url pattern. How can i make it dynamic and take in mind the url slag, in order to be called from multiple pages? E.g. /dashboard/13/devices Url Pattern: path('<int:application_id>/devices/', views.ApplicationDetail, name='application-detail') -
Django show page of user favorites cards
This is my first project with Django and I searched everywhere but didn't find a solution. In my website, I have cards and I want the user to be able to add to favorites the cards he wants. This function works, but then I want to create a page where he can see his favorites cards. Here's my problem : I only manage to display all favorites cards, from all users. When I just want the authenticated user's favorites cards. Here's my code : This is the .html file : {% if user.is_authenticated %} {% for carte in carte_list %} {% if carte.favori.exists %} //code for my card {% endif %} {% endfor %} {% endif %} This is my views.py file : class FavoriListView(generic.ListView): model = Carte template_name = '../templates/appli/favori_list.html' def get_context_data(self, *args, **kwargs): context = super(FavoriListView, self).get_context_data(*args, **kwargs) context['carte_list'] = Carte.objects.all() return context class CarteDetailView(generic.DetailView): model = Carte template_name = '../templates/appli/carte_detail.html' def get_context_data(self, *args, **kwargs): context = super(CarteDetailView, self).get_context_data(*args, **kwargs) context['carte_list'] = Carte.objects.all() return context def get(self, request, *args, **kwargs): id = self.kwargs['pk'] carte = get_object_or_404(Carte, id=id) est_favori = False if carte.favori.filter(id=request.user.profil.id).exists(): est_favori = True else: est_favori = False context = { 'carte': carte, 'est_favori': est_favori } context['carte_list'] … -
How to store data globally for a single request in Django?
I want to prepare my Django webservice for distributed requests using cloud computing (stateless!). Therefore I need to make my requests completely modular and take care that no data from a previous request are used. Since I need a lot of data and functions for some requests, it is not reasonable to pass these data to each and every function. Question: Which possibilities are there to store data "globally" for a single request? As far as I see there are two possibilities, but both of them do not seem to meet my needs: 1. Django Session Store data in request.session (using the middleware 'django.contrib.sessions.middleware.SessionMiddleware'). When I understood it properly, the data are still kept after the request for the next requests of the same user until the user logs out. Is this correct? In my tests the data are empty for each new request. But I don't understand why. And still I don't have a handle to the request in all of my functions. For more info about Django sessions see: https://docs.djangoproject.com/en/3.0/topics/http/sessions/ https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Sessions clear session data after multi-page form submit in Django Django/Auth: logout clears the session data? 2. Python Global Keyword Store data in python global variables. These data …