Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why I cannot see a error message from ValidationError Django?
I have done what is written on Django Documentation and I have tried several Youtube tutorials, including Stackoverflow's advice. However, I could not make the message "Validation Error" appear on the template. When I click the button to create a post whit bad_word, I redirect to the same page, the post isn't saved but the form doesn't show me the message. I tried to save in a print({{ form.errors }}) in the view and the terminal showed the message that I want to see in the template: contentError So I don't know what I'm doing wrong... #view.py if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['content'] username = User.objects.get(username=f"{request.user}") new_post = Post(user=username, title=title, content=content, datetime=timezone.now()) new_post.writeOnChain() cache.expire("cache", timeout=0) return HttpResponseRedirect("/") else: form = PostForm() return render(request, "api/homepage.html", {'form': form, 'postList': postList}) > #forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'content',) def clean_title(self): title = self.cleaned_data['title'] if "bad_word" in title: raise forms.ValidationError("Error") return title def clean_content(self): content = self.cleaned_data['content'] if "bad_word" in content: raise forms.ValidationError("Error") return content #template <div class="p-3 forms m-3"> <form class="crispy" action="{% url 'homepage' %}" method="post"> {% csrf_token %} {{ form|crispy }} <input type="submit" class="btn buttons" value="Create Post"> … -
Cannot import name 'Context" from 'django.template.base' when using django-social-widgets
When trying to include django-social-widget on Django 3.2.4, I encountered an error: File "C:\Python39\lib\site-packages\django\template\backends\django.py", line 123, in get_package_libraries raise InvalidTemplateLibrary( django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'social_widgets.templatetags.social_widget s': cannot import name 'Context' from 'django.template.base' (C:\Python39\lib\site-packages\django\template\base.py) How can I solve this problem? -
'ListBlogPost' object has no attribute 'get_object' django
I am using forms in my list view for review post before it publish. If I select publish then it will be show in my template otherwise not. It's seems to me everything okay. But why I am getting this error 'ListBlogPost' object has no attribute 'get_object'. Here is my code: views.py class ListBlogPost(ListView,FormView): model = Blog template_name = 'approval-blog-post.html' form_class = AdminBlogFrom def get_success_url(self): return reverse('approval-blog') def get_context_data(self, **kwargs): data = super(ListBlogPost, self).get_context_data(**kwargs) data['blog_admin_form'] = AdminBlogFrom() return data def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): messages.add_message(self.request, messages.INFO, 'Your Comment pending for admin approval') return self.form_valid(form) else: messages.add_message(self.request, messages.INFO, 'Somethings Wrong. Please try again') return self.form_invalid(form) def form_valid(self, form): form.save() return super(ListBlogPost, self).form_valid(form) froms.py class AdminBlogFrom(ModelForm): class Meta: model = Blog fields = ['is_published','author','slug'] models.py author = models.ForeignKey(User,on_delete=models.CASCADE,max_length=100) title = models.CharField(max_length=300,unique=True) body = RichTextUploadingField() slug = models.SlugField(max_length=255,unique=True) created_at = models.DateTimeField(auto_now_add= True,blank=True,null=True) updated_at = models.DateTimeField(auto_now= True,blank=True,null=True) CHOICES = ( ('published', 'published',), ('pending', 'pending',), ('rejected', 'rejected',), ) is_published = models.CharField( max_length=10, choices=CHOICES,default='pending' ) #approve-post.html <form method="POST"> {% csrf_token %} {{form}} <button class="btn btn-info">Publish</button> </form> When I am clicking on publish button I am getting this errror ListBlogPost' object has no attribute 'object_list' -
On running django app gives error django.template.library.InvalidTemplateLibrary: Invalid template library specified
I am getting this error across all my django projects. Some settings have been changed. Whats the problem? I get the following error on python manage.py runserver django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'pinax.templatetags.templatetags.shorttimesince_tag': No module named 'django.utils.tzinfo' -
Creating a dropdown menu in python django and adjust website values according to the selection
I have a django framework with a template that has different versions in terms of content. As a User I would like to be able to select the version I want in a dropdown menu and adjust the contents of the website accordingly. Is there a way to create a dropdown menu like that if the content only changes in terms of certain values displayed on the website (e.g. if "3" is selected in the menu, change all the according placeholders to "3") without requiring the use of backend logic or some reactive frontend framework? -
Django: 'str' object has no attribute 'get'
I am trying to effectively make a Reddit clone just for practice with Django and I am trying to set up my upvote/downvote system with just a simple integer(upvote adds one, downvotes subtract one) however when I hit my "upvote" or "downvote" buttons it gives me the error 'str' object has no attribute 'get'. I have no idea what is causing this and all of the other answers with this error were not at all related, any help would be awesome. My Model: class post(models.Model): title = models.CharField(max_length=200) body = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) ranking = models.IntegerField(default=0) My Views: class Feed(ListView): model = post template_name = 'thefeed/feed.html' def UpvoteView(request, pk): selected_post = post.objects.get(pk=pk) selected_post.ranking+=1 selected_post.save() return reverse('feed-home') def DownvoteView(request, pk): selected_post = post.objects.get(pk=pk) selected_post.ranking-=1 selected_post.save() return reverse('feed-home') My Urls: urlpatterns = [ path('', views.Feed.as_view(), name="feed-home"), path('post/<int:pk>/downvote', views.DownvoteView, name='downvote-post'), path('post/<int:pk>/upvote', views.DownvoteView, name='upvote-post'), ] My Feed.html(homepage): {% block content %} <div class="announcement"> <h5 style="background: yellow;">Forum.Chat is the Internet's home for debate on any topic, keep it civil!</h5> </div> <br> {% for post in object_list %} <div style="margin-bottom: 2%;"> <h3><a href="{% url 'feed-post' post.pk %}">{{post.title}}</a><a href="#"></h3> <p><a href="#">By: {{post.author}}</a><a href="{% url 'edit-post' post.pk %}"> Edit Post</a></p> <p><a href="{% url 'upvote-post' pk=post.pk %}">Upvote</a><a … -
Django Views and Model: Create ManyToMany User relationship with all other relationships - triangular number series problem
I have 4 models: class User(models.Model): ... class Invite(models.Model): ... user = models.ForeignKey( User, related_name="invites", on_delete=CASCADE) class House(models.Model): ... members = models.ManyToManyField(User, related_name="houses") class Balance(models.Model): balance_owed = models.DecimalField( max_digits=10, decimal_places=2, default=0) two_users = models.ManyToManyField(User, related_name="between_balance") As a User joins a house, I want that user to create a balance with ALL other users in the house. Number of Balance instances per User will start to form a triangular number sequence (for ref see https://www.101computing.net/triangular-numbers/ ); The pattern for number of Balance instances per User would look like: 1, 3, 6, 10, 15 etc. And on a grid, the relationships would look like: User1 User2 User3 User4 User1: x bal bal bal User2: bal x bal bal User3: bal bal x bal User4: bal bal bal x This is where I'm lost! In my views.py I tried: my_invite.house.members.add(this_user) # this_user is the one joining the house all_users = this_house.members.all() # store all members of house, including new user for user in all_users: balance_obj = Balance.objects.create() balance_obj.two_users.add(user) balance_obj.two_users.add(this_user) Unfortunately this does not satisfy a forming of relationships between every single user. I'm guessing this requires some kind of algorithm perhaps? Thank you in advance for your input -
Jsonresponse not returning add data in quaryset
I am using Ajax quary to get filtered data to template. I am appending new data value in quaryset. But json response not included newly append values. Please guide to get append values to template by json. my ajax is: $.ajax( { type: "GET", url: "/waccounts/listaccttrans_date", dataType: "json", data: { {#'id': 1235,#} 'csrfmiddlewaretoken': '{{csrf_token}}' }, success: function (accts) { console.log(accts); ....... my view is: def listaccttrans_date(request): if request.method == "GET": alltrans = FinTransDetail.objects.filter(fd_acct=1601) openbal = 0 # to add new items# for item in alltrans: acctname = item.fd_acct.AcctName transdate = item.fd_no.fh_dt openbal = openbal + (item.fd_debit - item.fd_credit) item.balance = openbal item.acctname = acctname item.transdate = transdate accts=list(alltrans.values()) return JsonResponse({'accts':accts}) my console output not included added values: 0: fd_acct_id: "1601" fd_credit: "1250.00" fd_debit: "0.00" fd_detail: "office files purchased" fd_no_id: 119 fd_posting: false fd_tax: "0.00" id: 45 please note in other view (not for ajax) they are included while rendering: context = {'alltrans': alltrans,} return render(request, 'waccounts/detail_account_trans.html', context) -
how to insert values into mysql database through django restapi
I am going through some trouble lately, I have created 2 tables which are User and Phones models.py from django.db import models class User(models.Model): userid = models.AutoField(primary_key=True,default=None) name = models.CharField(max_length= 100) age = models.IntegerField() class Meta: db_table = 'user' class Phones(models.Model): phoneId = models.AutoField(primary_key=True,default=None) userid = models.IntegerField(null=False) numbers = models.CharField(max_length = 15, null=True) phonesCountryCode = models.CharField(max_length=5,null=True) class Meta: db_table = 'phones' I want to send a post request like this : "User": [ { "name": "abc", "age": 100" }, { "name": "pqr", "age": 50 }, { "name": "xyz", "age": 80 } ], "Phones": [ { "numbers": "65452124", "phonesCountryCode": "+93" }, { "numbers": "45215124", "phonesCountryCode": "+93" } ] multiple data can be added into both databases. I have created a view and tried to add data like that but failed views.py : lass UpdateAll(APIView): def post(self, request ): userid = User.objects.latest('userid').userid name = request.data.get('name') age = request.data.get('age') numbers = request.data.get('numbers') phonesCountryCode = request.data.get('phonesCountryCode') User_Serializer = UserSerializer(data={"name":name,"age":age}) if User_Serializer.is_valid(raise_exception=True): User_Serializer.save() Phone_Serializer = PhoneSerializer(data={"userid":userid,"numbers":numbers,"phonesCountryCode":phonesCountryCode}) if Phone_Serializer.is_valid(raise_exception=True): Phone_Serializer.save() return Response({'status': 'Success'}) finaly serializer.py class UserSerializer(serializers.ModelSerializer): name=serializers.CharField(required=True) age = serializers.IntegerField(required=True) class Meta: model = User fields= '__all__' class PhoneSerializer(serializers.ModelSerializer): userid = serializers.IntegerField(required=True) numbers = serializers.CharField(max_length = 15) phonesCountryCode = serializers.CharField(max_length=5) class Meta: model = Phones … -
Django executes almost all .py files at request
I have Django project with 6 apps. I added logging to every app's init.py, models.py and views.py files (inside any classes/functions) and I've seen that on every GET/POST request almost every of this files are executed. Why is this happening and is there any way to change this behavior? -
How to copy executables in dockerfile multi-stage
I have an django image with multi-stage build. I install dependencies required by the the app, e.g heroku, psql, etc in the first stage. But when when I copy the bin path to the 2nd stage, they don't work in the app. dockerfile FROM python:3.8-slim as base WORKDIR /test # libpq-dev and gcc help with psycopg2 RUN apt-get update \ && apt-get install -y curl unzip git libgtk-3-0 locales postgresql-client libpq-dev gcc gnupg \ && apt-get clean all \ && rm -rf /var/lib/apt/lists/* RUN curl -sL https://deb.nodesource.com/setup_10.x | bash \ && apt-get install nodejs -yq \ && apt-get clean all # Install yarn RUN npm install -g yarn RUN curl https://releases.hashicorp.com/terraform/0.13.6/terraform_0.13.6_linux_amd64.zip -o /tmp/terraform.zip && cd /tmp && unzip /tmp/terraform.zip -d /usr/local/bin RUN curl https://cli-assets.heroku.com/install.sh | sh COPY . . RUN pip3 install --no-cache-dir pipenv \ && pipenv install --deploy --system \ && mv src/* /usr/local/lib/python3.8/site-packages/ RUN python manage.py collectstatic --no-input FROM python:3.8-slim RUN apt-get update WORKDIR /test COPY post-install.sh /test COPY media.tar.gz /test COPY --from=base /usr/local/lib/python3.8/site-packages/ /usr/local/lib/python3.8/site-packages/ COPY --from=base /usr/local/bin/ /usr/local/bin/ COPY --from=base /test/static/ /test/static/ ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV LANG C.UTF-8 # Run the image as a non-root user RUN adduser --disabled-password --gecos "" django USER django … -
I can't display my var in template even if var is in my context
My variable created in my view, so i can find it in my contexte of my view but when i want to display it in template base.html that doesn't work my view def accueil(request): if request.method == 'POST': form_plot_one_way = plot_onewayForm(request.POST) if request.POST.get('Plot'): if form_plot_one_way.is_valid(): listbox_values = [key for key in fig_dict.keys()] print(listbox_values) else: form_plot_one_way = plot_onewayForm() context = locals() print(context) return render(request, 'base.html', locals()) my html <select name="Key_" id="Key_" size="5"> {{ listbox_values }} {% for list in listbox_values %} <option> {{ list }} </option> {% endfor %} </select> in my context : {'listbox_values': ['Pclass', 'Name', 'Sex', 'Age', 'Siblings/Spouses Aboard', 'Parents/Children Aboard', 'Fare']} terminal : ['Pclass', 'Name', 'Sex', 'Age', 'Siblings/Spouses Aboard', 'Parents/Children Aboard', 'Fare'] -
Problems with different types of test databases
I am working on a large Django project with lots of tests. To improve the performance I want to make the test database persistent - by default, it's in memory. One exemplar test class runs perfectly fine in in-memory Sqlite3. When I switch to MariaDB, I get stacked exception for all but the first test case: django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. and MySQLdb._exceptions.OperationalError: (2006, '') So I thought it may be a problem with MariaDB, I switch to file-based SQLite3. But there, again - on the same tests! - a stacked exception: sqlite3.ProgrammingError: Cannot operate on a closed database. and django.db.utils.ProgrammingError: Cannot operate on a closed database. The interesting thing is that lots of tests work and the code looks good. I tried to get the broken query which causes the transaction in MariaDB to fail but after searching around for an hour, I ended up with zero results. Looking for closed database connections to SQLite always points to some custom shenanigans what I am not doing. I am running Django (v2.2.23) on Windows 10 Pro with PyCharm (latest). -
Payment Integration using Just Card Number Visa/MasterCard etc | No Stripe, No Paypal, No PayTm, No RazorPay etc
I am developing a web app that supports Online payment in Django. Stripe, Paypal, RazorPay, etc does not support my country. I would like to have those type of payment integration which Google and some other companies uses. Like: Payment through just Card Number + Expiry date and 3-digit pin(from the back of card) Is there any library or method available to do this task using Django Thanks in advance -
Sorting queryset by repeating values in django
There is a school with a total of 12 classes. 9-A, 9-B, 9-C 10-A, 10-B,10-C 11-A,11-B,11-C We have students in each class and I want to order a queryset that contains these students. We can access the degree and letter of the class separately. I want to order them like that : 9-A 10-A 11-A 9-B 10-B 11-B 9-C 10-C 11-C (A B C is not sorted, it should be random. I want to sort 9 10 11.) It will repeat itself every three times like 9,10,11,9,10,11. I couldn't figure how to write a query to sort them with this algorithm. students= Student.objects.distinct().filter(exams__schedule_id=1).order_by('') Here is the student queryset. How should I fill order_by part ? -
Render django-recaptcha's script tag inside head tag
I'm facing issue while rendering django recaptcha inside form because it is adding script tag along with captcha input. <div class="g-recaptcha" data-sitekey="KEY-HERE" data-callback="correctCaptcha"></div> <script type="text/javascript" src="https://www.google.com/recaptcha/api.js?hl=en"></script> How to avoid rendering along div tag and move this script to head tag? -
Having problems in SQLite using Django
I had created two lists First List and Second List, and I'm trying to access the Items of both lists but somehow when trying to access the items of the second list, it shows exception main.models.Item.DoesNotExist: Item matching query does not exist. https://i.stack.imgur.com/9WTJa.png -
Redirecting user to dynamic url after google login using django allauth
NOTE: I asked this question 5 days ago without response so trying again. Remove if this violates the rules of duplicate questions. I am using google sign in to authenticate users using django allauth. There is no need to log the user in prior to them trying to interact with the website, which happens at https://www.example.com/example/5 where 5 is just an id to a model instance in my database. After user login, I would like to redirect the user to the same page they are on. Would it be possible to do this either through passing the model id (5 in this example) through the google credentials and receive the number back at the /accounts/google/login/callback/ callback, or something similar? Or perhaps there is way using django allauth. This question is close to what I need, but I don't know how to get access to the model ID using this approach. Django-Allauth, Multiple login redirect url # In myapp/adapter.py from allauth.account.adapter import DefaultAccountAdapter class AccountAdapter(DefaultAccountAdapter): def get_login_redirect_url(self, request): url = super(AccountAdapter, self).get_login_redirect_url(request) user = request.user ''' # pseudocode, change it to actual logic # check user role and return a different URL role = get_user_role(user) if role == 'student': url = … -
Why is CSS not updating with live reload in django
I just figured out how to use live reload with django - (How to get liveserver to render django templates?). I used the first answer (but instead of ./manage.py livereload, I did python manage.py livereload. My problem is that now the CSS is not uploading. I know it is because of the live reload because when I use the regular python manage.py runserver, the CSS loads. Any help on this will be appreciated. (When in my command prompt (I use Windows 10), and while in the directory which contains the manage.py file, I type ./manage.py livereload.) -
How to solve PytestConfigWarning: Unknown config option: DJANGO_ SETTINGS_MODULE error?
I am using django to build my website and I have used django-pytest to test my apps but I have got this error Note I am usign python 3.9 ================================================================== warnings summary =================================================================== ..\venv\lib\site-packages\_pytest\config\__init__.py:1233 c:\users\eng_diaa_shalaby\desktop\unittest\venv\lib\site-packages\_pytest\config\__init__.py:1233: PytestConfigWarning: Unknown config option: DJANGO_ SETTINGS_MODULE self._warn_or_fail_if_strict(f"Unknown config option: {key}\n") -- Docs: https://docs.pytest.org/en/stable/warnings.html This is my pytest.ini file content # -- FILE: pytest.ini (or tox.ini) [pytest] DJANGO_SETTINGS_MODULE = testing_settings # -- recommended but optional: python_files = tests.py test_*.py *_tests.py and I run this command pytest and this is my venv packages Package Version ------------- ------- asgiref 3.3.4 atomicwrites 1.4.0 attrs 21.2.0 colorama 0.4.4 coverage 5.5 Django 3.2.4 django-pytest 0.2.0 iniconfig 1.1.1 packaging 20.9 pip 21.1.2 pluggy 0.13.1 py 1.10.0 pyparsing 2.4.7 pytest 6.2.4 pytz 2021.1 setuptools 57.0.0 sqlparse 0.4.1 toml 0.10.2 -
TemplateDoesNotExist at / on Heroku while working on local server
New to Django and Heroku; I get "TemplateDoesNotExist at /" when loading the page. Have read somewhere that it might have something to do with Caps. My template is called templates. In settings.py : from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent print(BASE_DIR) print(BASE_DIR / 'templates') And TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], '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', ], }, }, ] HOWEVER in the error, I get : "django.template.loaders.filesystem.Loader: /app/Templates/homepage.html (Source does not exist)" It seems like Heroku doesn't upload the changes I've made to settings.py even though I get "Everything up-to-date" Everybody seems to be using os.path.join but my Pathlib is working correctly (I assume). Thanks in advance for any help :) -
Map selected radio button to existing post category: Cannot assign "'Artikel'": "Post.category" must be a "Category" instance
I want to map radio buttons to given categories. One way is to do this with the help of a choice field. I don't know if this is a good approach. I have seen many other articles and SO-posts but they did not point me to a direction from where I could see my mistake - so after many hours of research I wanted to ask you here. Thanks! models.py class Category(models.Model): title = models.CharField(max_length=255, verbose_name="Kategorie") ... class Post(models.Model): title = models.CharField(max_length=150) .... category = models.ForeignKey(Category, verbose_name="Kategorie", forms.py CAT_CHOICES= [ ('Artikel', 'Artikel'), ('Videos', 'Videos'), ('Anderes', 'Anderes'), ] class PostForm(forms.ModelForm): category = forms.ChoiceField(widget=forms.RadioSelect, choices=CAT_CHOICES) class Meta: model = Post # is this throwing an error because I only handle the 'Post' model? fields = [ 'title', ... 'category', ] views.py def function_name(request): ... if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): # error happens here template.html: <label>Artikel</label> <input id="category0" type="radio" name="category" value="Artikel"> <label>Videos</label> <input id="category1" type="radio" name="category" value="Videos"> <label>Anderes</label> <input id="category2" type="radio" name="category" value="Anderes"> output: ValueError at / Cannot assign "'Artikel'": "Post.category" must be a "Category" instance. What would be a good practice to handle this? I am thankful for any advice. -
Will django notifications be there in React Native?
I am building a simple blogapp in Django AND i made few features like like, dislike, chat, comment on blog and i set up to create notification using models.py class Notification(models.Model): receiver = models.ManyToManyField( User, related_name="notification_receiver", default=None) sender = models.ForeignKey( User, on_delete=models.CASCADE, related_name='notification_sender') content = models.CharField(max_length=100, null=True, blank=True) When someone send a message using chat then i am getting a notification from browser. BUT i am trying to convert my django app into React Native. So, will notifications be sent in React Native with same lines of code in django. I am new in React Native and i have no idea how notifications works in React Native. So, Any help would be Appreciated. Thank you in Advance. -
404 error when access Wagtail cms page after Integrating Wagtail with existing Django project
I am new to Wagtail and intended to learn by practice. Django=3.0.5 | Wagtail=2.13.1 | Python=3.7.10 I have existing Django project with below file structure: |- manage.py |- static/ |- templates/ |- IoTSite/ ___|- urls.py ___|- settings.py ___|- ... I was strictly following Wagtail official guide: Integrating Wagtail into a Django project for this integration. However, after I finish the root urls.py config, // IoTSite/urls.py urlpatterns = [ path('',TemplateView.as_view(template_name='homepage.html'),name='home'), path('admin/', admin.site.urls), path('article/',ArticleListView.as_view(template_name='TL_ArticleList.html'),name='article-list'), path('article/<int:pk>/',ArticleDetailView.as_view(template_name='TL_ArticleDetail.html'),name='article-detail'), path('archive/<int:year>/<int:month>/', ArticleMonthArchieveView.as_view(month_format='%m',template_name='TL_ArticleList.html'),name='archive_mmonth'), path('cms/', include(wagtailadmin_urls)), path('documents/', include(wagtaildocs_urls)), path('pages/', include(wagtail_urls)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) when I try to access Wagtail admin site; http://127.0.0.1/cms/ I encountered 404 not found error with below debug details. Using the URLconf defined in IoTSite.urls, Django tried these URL patterns, in this order: 1. [name='home'] 2. admin/ 3. article/ [name='article-list'] 4. article/<int:pk>/ [name='article-detail'] 5. archive/<int:year>/<int:month>/ [name='archive_mmonth'] The current path, cms/, didn't match any of these. Q1: Why 127.0.0.1/cms was not matched when it was clearly configured in urls.py? are there any required configs not mentioned in the official guide ? Q2: Behind the scene, how Django and Wagtail interacts with each other? I did not see a Watgail app folder within the Django project directory, it seems that Django interacts with Wagtail purely via import … -
Restoring Django request object in graphene
I'm using graphene-django to make an API, I don't have access to the request object anymore. I want a global variable to access the logged in user in any file. I want to implement this solution and I want to know if it's unnecessary or the right way. class user: __instance = None def __new__(cls, username, id, **_ignored): if cls.__instance is None: cls.__instance = object.__new__(cls) cls.__instance.username = username cls.__instance.id = id return cls.__instance Also opened to your solutions. Thanks!