Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
POST method sends no data to Django function based views
I have been trying to write a function based delete view: urls.py from django.urls import path from ttt import views urlpatterns = [ path('', views.home, name='home'), path('delete_task/<str:pk>/', views.delete_task, name='delete_task'), ] views.py def delete_task(request, pk): task_details = Task.objects.get(id=pk) if request.method == 'POST': task_details.delete() return redirect('/') context={ 'task_details' : task_details } return render(request, 'ttt/delete_task.html', context) delete_task.html <form action = "#" method="POST"> {% csrf_token%} <input type="submit" name="Confirm Delete"></input> <a href="{% url 'home' %}" >Cancel</a> </form> When I submit the delete form, I am redirected to an error page. In python shell, I can see the POST data is empty when I select 'Confirm Delete'(this should be passing the id of the task I want to delete). The error I am gett ing is : NoReverseMatch at / Reverse for 'view_task' with arguments '('',)' not found. 1 pattern(s) tried: ['view_task/(?P<pk>[0-9]+)/$'] Also, my models.py : from django.db import models # Create your models here. class Member(models.Model): DESIGNATION = [ ('Developer', 'Developer'), ('Tester', 'Tester'), ('Support', 'Support'), ] name = models.CharField(max_length=200, null=True) role = models.CharField(max_length=100, null=True, choices=DESIGNATION) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Task(models.Model): CATEGORY = [ ( 'Low', 'Low'), ('Medium', 'Medium'), ('Urgent', 'Urgent'), ] STATUS = [ ('Not Started', … -
How to put 2 context_object_name for listView Django
I have developed a context within a context. here's my views.py: class AgentClientListView(OrganizerAndLoginRequiredMixin, generic.ListView): template_name = "agents/agent_client_list.html" context_object_name = "clients" def get_queryset(self): queryset = Client.objects.filter(agent_id=self.kwargs['pk'], agent__isnull=False).order_by('company_name') return queryset however I need to add another context_object_name: "agent" what would I do? thank you in advance -
How to combine and sort multiple OrderedDict in Django?
The below data's are from from three different Django Serializer outputs post=[{"title" :"abc", "date" : "10-03-2021"}, {"title" :"xyz", "date" : "28-01-2021"}, ......] comments=[{"comment_text" :"heloo", "date" : "31-05-2021"}, {"comment_text" :"heloo", "date" : "20-04-2021"}, ......] friends=[{"friend" :"abc", "date" : "12-03-2021"}, {"friend" :"xyz", "date" : "10-05-2021"}, ......] Now I want to combine all three in to single output element and sorted it by date. it is possible?? -
I uploaded the image using SQL query in the blob format. can I use that to display the image Django template?
I am using MySQL workbench as a database and actually, I have not created any model, I uploaded the image using SQL query in the blob format. can I use that to display the image Django template? main.html===>{{ para_image }} we are using to display the image <div class="parallax1" style="text-align:center ; background-image: url('{{ para_image }}')"> <p style=" color: black; font-weight: bold; font-size: 20px; display: flex; align-items: center; justify-content: center; padding: 30px; "> {{ para_text|safe }} </p> </div> views.py===(para_image) is the variable which holds the image def main(request): try: mycursor = mydb.cursor() mycursor.execute("SELECT * FROM counts") myresult = mycursor.fetchall() mycursor1 = mydb.cursor() mycursor1.execute("SELECT * FROM parallax") myresult1 = mycursor.fetchall() mycursor1.execute("SELECT * FROM footer_content") myresult2 = mycursor.fetchall() mycursor3 = mydb.cursor() mycursor3.execute("SELECT * FROM about_us") myresult3 = mycursor.fetchall() print("##########00001111111100000##########") if(1): context={ 'students':myresult[0][2], 'teachers':myresult[0][3], 'workers': myresult[0][4], 'para_text':myresult1[0][2], """image""" 'para_image':myresult1[0][1], 'ftext':myresult2[0][1], 'flink':myresult2[0][2], 'tlink':myresult2[0][3], 'ilink':myresult2[0][4], 'about_us':myresult3[0][2] } return render(request, 'main.html', context) else: context={} return render(request, 'main.html', context) except: context = {} return render(request, 'main.html', context) thank you -
How to rename and upload the files to Google drive, which are uploaded to Django admin page through FileField in models.py
When a File is Uploaded to Django admin database, it gets saved into the database and the "media_url" path mentioned. I want to rename the file with the username of the user appended by timestamp and upload this renamed file to a specific folder in google drive. Thank you in Advance. -
How can I join two tables in order to get records based on some conditions in django?
I need to get those payments whose payment has not been transferred. I have tried something but its not that efficient so I was thinking if I could join the tables in order to accomplish the task but don't know how just started learning django. models.py class Orders(models.Model): payment_gateway_code = models.CharField(max_length=20,choices=[('PAYTM','PAYTM')]) is_active = models.BooleanField(default=True) class Payments(models.Model): id = models.AutoField(primary_key=True) orders = models.ForeignKey(Orders, on_delete=models.CASCADE) direction = models.CharField(max_length=20,choices=[('COLLECTION','COLLECTION'), ('TRANSFER','TRANSFER')]) settlement_status = models.CharField(max_length=50,blank=True, null=True,choices=[('YES','YES'), ('NO','NO')]) is_active = models.BooleanField(default=True) I have tried : # getting all payments whose direction is COLLECTION and settlement_status is YES collection_payments = Payments.objects.filter(Q(direction='COLLECTION') & Q(settlement_status='YES')).select_related('orders').filter(payment_gateway_code='CASHFREE') for collection_payment in collection_payments: order_id = collection_payment.orders_id #order corresponding to one payment order = Orders.objects.get(id=order_id,payment_gateway_code='PAYTM') #payments corresponding to one order payments = Payments.objects.filter(orders=order_id) # check weather transfer initiated if Payments.objects.filter(orders=order_id).filter(direction='TRANSFER').count()==0: initiate transfer Please suggest if there is a better way to do this by joining the tables. -
Django 2.2 cannot serialize default malues once migration has been done
I have a model which is refered to as a foreignkey with on_delete set to SET_DEFAULT. Because of that, I need to provide this model with a default item. I created a static method which does just that. class ScheduleChoice(models.Model): """ This model allows users to define crontab schedules. """ label = models.CharField(max_length=256, verbose_name="Label", unique=True) job_schedule = models.CharField( max_length=256, default="0 0 * * *", verbose_name="Crontab" ) @staticmethod def get_default_schedule_choice(): """ Because some models rely on ScheduleChoice and need a default value, we need to give them a default ScheduleChoice. """ try: choice = ScheduleChoice.objects.get_or_create( label="Every minute", job_schedule="* * * * *" ) except ProgrammingError: choice = None return choice @classmethod def get_choice_count(cls): """ Returns how many schedule choices have been defined. """ return len(cls.objects.all()) class Meta: verbose_name = "schedule choice" verbose_name_plural = "schedule choices" def __str__(self): return self.label class MyOtherModel(models.Model): """ Model using ScheduleChoices. """ job_schedule = models.ForeignKey( "ScheduleChoice", on_delete=models.SET_DEFAULT, default=ScheduleChoice.get_default_schedule_choice(), verbose_name="Schedule" ) activated = models.BooleanField(default=False, verbose_name="activated") I am able to run makemigrations and migrate without issue. My problem starts when I modifiy my models and try to use makemigrations again in order to update the migrations files. I get the error : ValueError: Cannot serialize: <ScheduleChoice: Every minute> There … -
why i am getting Direct assignment to the forward side of a many-to-many set is prohibited.?
I am getting this error when I am trying to add data on the auction_watching model. I tried make ManytoMany relation with auction_watching and products table. But why I am getting this error. Please help me out models.py from django.db import models from PIL import Image from datetime import datetime, timedelta from django.contrib.auth.models import User # Create your models here. class Products(models.Model): product_img = models.ImageField(upload_to='pics') product_title = models.CharField(max_length=100) price = models.IntegerField() deadline = models.DateTimeField() def save(self, *args, **kwargs): super(Products, self).save(*args, **kwargs) img=Image.open(self.product_img.path) if img.height >= 300 and img.width >=300: img = img.resize((200, 300)) # resize use to resize image, don't care about ration # output_size = (200,300) # img.thumbnail(output_size) # thumbnail use to resize image with aspect ration img.save(self.product_img.path) class Auction_Watching(models.Model): product_info = models.ManyToManyField(Products, null=True ) User_id = models.IntegerField() current_bid = models.IntegerField(null=True) action_status = models.BooleanField(default='True') def __str__(self): return self.name views.py def auction_watch(request,pk): username=request.session['username'] user_id= request.session['value'] product_information = Products.objects.get(id=pk) product_watch = Auction_Watching.objects.create(product_info=product_information, User_id=user_id) return render(request, 'auctionApp/auction_watch.html') -
tile name is not display only object name is display on Django admin
models.py from django.db import models class Blog(models.Model): title=models.CharField(max_length=50,default="") auther=models.CharField(max_length=100, default="") body=models.TextField(default="") def __self__(self): return self.title http://127.0.0.1:8000/admin/ BLOG Blog object (3) Blog object (2) Blog object (1) Here title name is not shown -
How to fix "M" value must be True or False
This is my model.py where my gender is a booleanfield This is my forms.py where i put my gender as a choicefield and the widget is radioselect Maybe my wrong is in the views.py but i don't know how to fix This is the error that i need to fix Please help me -
How to change many to many field name in the serializer?
I know it is relatively simple to change a represented filed name in the serializer with source argument like this: class SomeSerializer(ModelSerializer): alternate_name = serializers.SomeField(source='field_name') class Meta: fields = ('alternate_name') But when dealing with a many to many field, the source is a ManyRelatedManager and using source in it leads to errors: class SomeModel(models.Model): field_name = models.ManyToManyField(OtherModel, related_name='groups') class SomeModelSerializer(ModelSerializer): alternate_name = models.ListField(source='field_name') class Meta: fields = ('alternate_name') This gives ManyRelatedManager object is not iterable! Using other Fields instead of ListField gives other errors. What is the right approach here? -
How can I access Django Source Code on VsCode?
When I do control + click in VsCode inside a django application, it takes me to a new window, which i thought to be Django's source code, but I'm not sure what all of this means: class UserCreationForm(forms.ModelForm): error_messages: Any = ... password1: Any = ... password2: Any = ... def __init__(self, *args: Any, **kwargs: Any) -> None: ... def clean_password2(self) -> str: ... Meanwhile the source code for the same form, looks completely different and readable on Djando docs: https://docs.djangoproject.com/en/1.8/_modules/django/contrib/auth/forms/ Then again that document is for an older version of Django, so maybe they changed the way they write the code to the extent that looks like gibberish to me. -
Move <label> after <input type="file"> using FileInput in Django
I want to create a custom design for a file upload button in Django. In the CSS styling I use the selector .custom-upload[type=file] + label, just like this CodePen does, but in order for this styling to work the <label> element must come after the <input> element. It seems that Django by default puts the <label> element before the <input> element. Is there any way of changing the HTML order? I don't feel like my code is relevant to the question but here it is anyway for the sake of completeness: models.py from django.db import models class File(models.Model): file = models.FileField() views.py class UploadFileForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(UploadFileForm, self).__init__(*args, **kwargs) self.fields['file'].label = 'Choose your file' class Meta: model = File fields = ('file',) widgets = { 'file': forms.FileInput(attrs={'id': 'upload-file', 'class': 'custom-upload'}) } def index(request): return render(request, "homepage/index.html", { "form": UploadFileForm() }) -
Django - Best User model in an employee context - storing ranks/titles for different years
I'm starting a new Django project and am trying to create a custom User model. This will ultimately be used for a small internal employee portal. The intention is to track each employee's titles across different years. For instance, my aim is to be able to have a table with two columns, each column having dropdown fields that allows me to select the year, and the title from a set of pre-defined titles. I can then add a new row each time I want to add specify a new year and new title. I am having difficulty figuring out what field to implement here within the custom User model, and would be grateful to be pointed to the right direction. -
Django: Input field disappear when html and css are use d
I'm trying to costumize with html e css a form that I made with bios info that are saved in the database (I have also login/signup forms using the same template and that works). Unfortunaly when I render it the field to input data is missing. Can someone help me? This is my code. Also I don't know is the right way to have radiobutton for gender since in the database it appeared as a dropdown list. models.py class PHUser(models.Model): last_name = models.CharField('Last Name', max_length=30) gender_options = (('m', 'Male'),('f', 'Female'),) gender = models.CharField(max_length=1, choices= gender_options) birthday = models.DateTimeField('Birthday') phone = models.CharField(max_length=10) forms.py class PHUserForm(ModelForm): class Meta: model = PHUser fields = ('last_name', 'gender', 'birthday', 'phone') widgets = {'gender': forms.RadioSelect} def add_user(request): submitted = False if request.method == "POST": form = PHUserForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('add_user?submitted=True') else: form = ExperimentUserForm if 'submitted' in request.GET: submitted = True return render(request, 'ph/add_user.html', {'form': form, 'submitted': submitted}) file.html <form method="POST" action=""> {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-user"></i></span> </div> {{ form.last_name }} </div> <div class="input-group mb-2"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-envelope-square"></i></span> </div> {{ form.gender }} </div> <div class="input-group mb-2"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-envelope-square"></i></span> </div> {{ … -
There is a billing page that I fill in all the details and click on make bill button, then the invoice page should be generated
There is a billing page that I fill in all the details and click on make bill button, then the invoice page should be generated, it is not coming. views.py def makebill(request): if request.method == "POST": cart = request.POST.get('cart') price = request.POST.get('price') n = request.POST.get('name') phone = request.POST.get('phone') data = json.loads(cart) for c in data: name = c['name'] qty = c['qty'] prod = Product.objects.get(name=name) prod.qty = prod.qty - int(qty) if prod.qty <= 0: messages.warning(request, f'{prod.name} has finished') prod.delete() else: prod.save() p= Sales(items_json=cart, amount=price, name=n, phone=phone) p.save() total = price product = Product.objects.all().order_by('name') product_list = list(product.values('name', 'cost')) context = {} context["product"] = json.dumps(product_list) try: context["total"] = total except: pass return render(request, 'makebill.html', context) Thanks in advance! -
PYTHON: How can i set file as a value for session variable or is there any better option for accessing the file in another view?
overall concept is user uploads the resume and selects either auto-corrections, show corrections, and no corrections. If the user selects auto-corrections it will automatically correct the misspelled words but when the user selects show corrections, will show the user list of misspelled words and allow the user to select specific words to correct with the predefined words or with their own words. I'm new to python. so if the code is wrong. please teach me # called from HTML form action when user selected show corrections option and uploads the resume .docx file. def uploading_resume(request): user = request.user if user.is_authenticated: if request.method == 'POST': if corrections == 'show': global u_file u_file = request.FILES['file'] resume_text = show_corrections(request=request, file=file) # gets the list of incorrect words and returns the list. def show_corrections(request, file): user = request.user resume_text = [] document = Document(file.file) parser = GingerIt() text = '' for line in document.paragraphs: text += line.text matches = parser.parse(line.text) for obj in matches['corrections']: word_obj = {'word': obj['text'], 'correct_word': obj['correct']} resume_text.append(word_obj) return resume_text # when user selected specific words from the above list. def correct_selected(request): user = request.user if user.is_authenticated: if request.method == 'POST': if request.POST['selected_words'] != '': selected_words = demjson.decode(request.POST['selected_words']) file_name = request.POST['selected_file_name'] … -
How to retain image file in django
I have a newclaim form which allows user to upload a picture and editclaims which allows users to retain or add new pictures which will overwrite the old one. The current problem I faced is whenever I try to edit without making any changes, the picture will become an empty field so I have to resubmit the picture again. This is my views.py # Submit a new Claim def newclaim(request): context = initialize_context(request) user = context['user'] if request.method == 'POST': receipt = request.FILES['receipt_field'] ins = SaveClaimForm(receipt=receipt) ins.save() print("The Data has been written") return render(request, 'Login/newclaim.html/', {'user':user}) # Edit a claim def editclaims(request,id): context = initialize_context(request) user = context['user'] # get original object claims = SaveClaimForm.objects.get(id=id) if request.method == 'POST': # update original object receipt = request.FILES['receipt_field'] # save it with original `ID` claims.save() return render(request, "Login/editclaims.html", {'claims':claims, 'user':user}) This is my editclaims.html <form method="POST" action="/editclaims/{{claims.id}}" enctype="multipart/form-data"> <div> <input id="receipt" name="receipt" type="file" value="receipt"> <label for="receipt"> {{ claims.receipt }} </label> </div> </form> This is my newclaim.html <form action="/newclaim/" method="post" enctype="multipart/form-data"> <div> <input id="receipt" type="file" name="receipt_field" style="display: none; visibility: none;"> </div> </form> -
Unable to get Zero/0 in If Statement wile using if in Django template
I am trying to use a Django template for executing some if/else statement , the issue is in the last option header_info.status.error the value from where I am fetching this info is zero but only blank table cell is coming , anything missing here or anything can be modified here to fix it ? <th>{{ header_info.status.total }}</th> <th>{{header_info.status.success}} {% if header_info.status.failure%}</th> <th>{{ header_info.status.failure }}{% endif %}{% if header_info.status.skip%}</th> <th>{{ header_info.status.skip}} {% endif%} {% if header_info.status.error%}</th> <th>{{ header_info.status.error }}{% endif %}</th> -
Django Rest Framework: if leave request is approved marked as absent on those days
this is leave approve and decline action this is the student attendance modelThis is leave model -
Adding a new object to the model returns 'list' object has no attribute '_committed' error
I want to add a new object to the model in database but when I tried to add it, it gives an error like 'list' object has no attribute '_committed' It gives an error at the part of car_model.save() Traceback Error Environment: Request Method: POST Request URL: http://127.0.0.1:8000/cars/add_car Django Version: 3.1.7 Python Version: 3.9.0 Installed Applications: ['cars.apps.CarsConfig', 'pages.apps.PagesConfig', 'accounts.apps.AccountsConfig', 'contact.apps.ContactConfig', 'houses.apps.HousesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'django.contrib.humanize', 'django.contrib.sites'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\gx760_000\Desktop\sahibinden\cars\views.py", line 434, in add_car car_model.save() File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\base.py", line 790, in save_base updated = self._save_table( File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\base.py", line 895, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\base.py", line 933, in _do_insert return manager._insert( File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\query.py", line 1254, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\sql\compiler.py", line 1396, in execute_sql for sql, params in self.as_sql(): File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\sql\compiler.py", line 1339, in as_sql value_rows = [ File "C:\Users\gx760_000\Desktop\myvenv\lib\site-packages\django\db\models\sql\compiler.py", line 1340, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] … -
How to generate pdf with vertical table?
I want to generate a pdf report containing data in a vertical table. Is there any library to achieve this functionality? I can use the following format of the dictionary to render data context = { "name":["A","B","C","D","E"] "age":[23,23,23,23,23], } but data is huge so it can affect performance.is there any other way to achieve this?I just want to generate pdf report with the table in the following format : | Name | A | 23 | | Age | B | 23 | -
I want to filter the clients of every agent individually. Django
I'm creating a view where I can show all the clients of specific agents via there PK. I am not having error when I use Client.objects.all() as the queryset and it gets to show all of the clients. however I don't know how to filter clients via select pk for Url. Please help. Here's my Views.py class AgentClientListView(OrganizerAndLoginRequiredMixin, generic.ListView): template_name = "agents/agent_client_list.html" context_object_name ="clients" def get_queryset(self): user= Agent.objects.get(pk=id) queryset = Client.objects.filter(user=user, agent__isnull=False).order_by('company_name') return queryset My Urls.py: from django.urls import path from .views import AgentListView, AgentCreateView, AgentDetailView, AgentUpdateView, AgentDeleteView, AgentClientListView app_name = 'agents' urlpatterns = [ path('', AgentListView.as_view(), name='agent-list'), path('<int:pk>/', AgentDetailView.as_view(), name='agent-detail'), path('<int:pk>/update/', AgentUpdateView.as_view(), name='agent-update'), path('<int:pk>/delete/', AgentDeleteView.as_view(), name='agent-delete'), path('<int:pk>/agent_client_list', AgentClientListView.as_view(), name='agent_client_list'), path('<int:pk>/delete/', AgentDeleteView.as_view(), name='agent-delete'), path('create/', AgentCreateView.as_view(), name='agent-create'), ] And HTML: {% extends "base.html" %} {% block content %} <section class="text-gray-600 body-font overflow-hidden"> <div class="container px-5 py-24 mx-auto"> <div class="lg:w-4/5 mx-auto flex flex-wrap"> <div class="lg:w-1/2 w-full mx-auto"> <h2 class="text-sm title-font text-gray-500 tracking-widest">AGENT</h2> <h1 class="text-gray-900 text-3xl title-font font-medium mb-4">{{ agent.user.first_name }} {{ agent.user.last_name }}</h1> <div class="flex mb-4"> <a href="#" class="flex-grow text-blue-500 border-b-2 border-blue-500 py-2 text-lg px-1"> Description </a> </a> <a href="#" class="flex-grow border-b-2 border-gray-300 py-2 text-lg px-1"> Update </a> </div> <div class="flex flex-col w-full"> <div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8"> <div class="py-2 align-middle inline-block … -
How to execute code on SIGTERM in Django request handler thread
I'm currently trying to understand the signal handling in Django when receiving a SIGTERM. Background information I have an application with potentially long running requests, running in a Docker container. When Docker wants to stop a container, it first sends a SIGTERM signal, waits for a while, and then sends a SIGKILL. Normally, on the SIGTERM, you stop receiving new requests, and hope that the currently running requests finish before Docker decides to send a SIGKILL. However, in my application, I want to save which requests have been tried, and find that more important than finishing the request right now. So I'd prefer for the current requests to shutdown on SIGTERM, so that I can gracefully end them (and saving their state), rather than waiting for the SIGKILL. My attempt My theory is that you can register a signal listener for SIGTERM, that performs a sys.exit(), so that a SystemExit exception is raised. I then want to catch that exception in my request handler, and save my state. As a first experiment I've created a mock project for the Django development server. I registered the signal in the Appconfig.ready() function: import signal import sys from django.apps import AppConfig import logging … -
Simple jwt breaks when Secret Key is put into environment variable on Google App Engine
In a Django project hosted on Google App Engine using the simplejwt library, I receive this error message as soon as I put the secret key into an environment variable: TypeError at /api/v1/auth/jwt/create/ Expected a string value The key is stored in the apps yaml file as SECRET_KEY_ENV and loaded in Django's settings file like this: SECRET_KEY = str(os.environ["SECRET_KEY_ENV"]), The Database environment variables are loaded in exactly the same manner and everything is working fine. The first time the key pops up in the error message is in this file: /layers/google.python.pip/pip/lib/python3.9/site-packages/jwt/api_jwt.py, line 63, in encode and in this form: key : ('ai0eobey86soimfxb6ax4uqdmo49yiauxchgnspsh',) from there he gets passed on to: /layers/google.python.pip/pip/lib/python3.9/site-packages/jwt/api_jws.py, line 110, in encode /layers/google.python.pip/pip/lib/python3.9/site-packages/jwt/algorithms.py, line 180, in prepare_key /layers/google.python.pip/pip/lib/python3.9/site-packages/jwt/utils.py, line 21, in force_bytes without being changed and the last file "utils.py"is the one raising the error message. I have tried changing the variable name, removing special characters from the key, moving the definition around inside the settings file, nothing works. As soon as I put it back into cleartext, it works fine but I can't keep doing that for obvious security reasons. How can I fix this? Thanks and BR