Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SSO manager, trying to pass cookies between websites
I have an application in python for SSO purposes. Users redirect from their website to this app, and the app returns an ACCESS_TOKEN to the website the user got redirected from. I want to redirect the user back to his website after the process and return the ACCESS_TOKEN as a COOKIE, but I don't know how to send the cookie to the user's browser. Thanks for any help. -
Define field in Django which can be of any type
Pymodm is being used to define my model for the MongoDB collection in Django. I want to declare a field that can store values of any type (List, String, or Integer). from pymodm import MongoModel, fields class DefinitionEntity(MongoModel): version = fields.IntegerField(required=True) value = fields.CharField(required=True) I want the "value" field to accept multiple types. Please tell me how to define that. Thanks in advance! -
Why isn't the data sent again after resfresh page in a POST request
I have used axios to send a POST request after pressing a button. I want to make sure not to send the data again after refreshing the page or clicking the button right after. When I refresh the page or click the button the data is not being sent. I suppose it's good but I don't know why. I'm using Vue for the front and Django for the back. In Vue: axios.post('http://127.0.0.1:8000/sendAbility/', params).then(response=>{...}) In Django: return Response({'success':'true'}) -
No module named 'graphene_djangographql_jwt'
I got error when I add graphql_jwt.refresh_token.apps.RefreshTokenConfig in INSTALLED_APPS. I ran the command " pip install django-graphql-jwt" but there is still some packages problems. Does anybody know about it? I am expecting to use GraphQL url with Django. I was going to give request access only auth users. -
How to prevent these malicious requests with nginx config?
My nginx server (using django) is getting hit with thousands of these types of requests per second: 199.127.61.178 - - [09/Nov/2022:08:20:42 +0000] "GET http://www.wuqiaoxianzajituan.com/ HTTP/1.1" 500 186 "http://www.wuqiaoxianzajituan.com" "Mozilla/5.0 (Linux; U; Android 2.3.5; en-in; Micromax A87 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1" 104.238.222.87 - - [09/Nov/2022:08:20:42 +0000] "GET http://www.wuqiaoxianzajituan.com/ HTTP/1.1" 400 55440 "http://www.wuqiaoxianzajituan.com" "Mozilla/5.0 (Linux; Android 8.0.0; SM-G950F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36" 172.93.110.55 - - [09/Nov/2022:08:20:42 +0000] "GET http://tucgd.lixil-kitchen.cn/ HTTP/1.1" 400 55373 "http://tucgd.lixil-kitchen.cn" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/537.86.4" 104.243.37.94 - - [09/Nov/2022:08:20:42 +0000] "GET http://you.br-sx.com/ HTTP/1.1" 400 55205 "http://you.br-sx.com" "Mozilla/5.0 (iPhone; CPU iPhone OS 11_2 like Mac OS X) AppleWebKit/604.4.7 (KHTML, like Gecko) Version/11.0 Mobile/15C114 Safari/604.1" 104.238.222.9 - - [09/Nov/2022:08:20:42 +0000] "GET https://skype.gmw.cn/?nf91C2a99VqP4D43fy6uPrgt0 HTTP/1.1" 400 55722 "https://skype.gmw.cn" "Mozilla/5.0 (iPad; U; CPU OS 4_3_5 like Mac OS X; de-de) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8L1 Safari/6533.18.5" 104.238.205.70 - - [09/Nov/2022:08:20:42 +0000] "GET http://eqksp.drtjy.com/ HTTP/1.1" 400 55224 "http://eqksp.drtjy.com" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36" 103.195.103.32 - - [09/Nov/2022:08:20:42 +0000] "GET http://eqksp.drtjy.com/ HTTP/1.1" 400 55192 "http://eqksp.drtjy.com" "Mozilla/5.0 (Windows NT 5.1; rv:40.0) Gecko/20100101 Firefox/40.0" 104.243.37.94 - - [09/Nov/2022:08:20:42 +0000] "GET http://you.br-sx.com/ HTTP/1.1" 400 55133 "http://you.br-sx.com" … -
failed to format database fetching values
i am trying to format the values for inserting to table of remote server database but i failing to format the values the get_values() failing to format the values and it is exit from script def get_values(listval): for i, x in enumerate(listval): if isinstance(x, unicode): listval[i] = x.encode('ascii', 'ignore') elif isinstance(x, datetime.datetime): listval[i] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") else: listval[i] = x return listval def cluster_template(): try: # Table Name: admin_learnings cmd = "SELECT * FROM cluster_templates" cursor1.execute(cmd) cluster_tmpls = cursor1.fetchall() for cluster in cluster_tmpls: # cluster['id'] = 19 cols = cluster.keys() print(cluster['id']) vals = get_values(cluster.values()) print(vals) try: print('try.................') # cursor2.execute("INSERT INTO %s (%s) VALUES (%s)" % ( # "cluster_templates", ",".join(cols), str(vals)[1:-1])) # dstconn.commit() print("success") except: print('failed to move') break return except Exception as e: srcconn.close() dstconn.close() i am calling get_values() function but it failing and exiting from script -
Django / Laravel Blade - send data from 1 module into 2 different blade templates
I have a blog section created in django which uses blade template files to display on the front end. This allows the user to add the blog content and set featured (yes/no) which will display the 'featured blog' first on the blog page. I am trying to create a separate module to include on the homepage which will grab the first 2 'featured' blogs. I have this in the models.py file. class New(models.Model): IS_FEATURED = ( (0, "No"), (1, "Yes") ) IS_POPULAR = ( (0, "No"), (1, "Yes") ) title = models.CharField(max_length=200, null=False, verbose_name='Title') slug = models.CharField(max_length=255, null=False, unique=True, verbose_name='Slug') keywords = models.CharField(max_length=300, blank=True, default="") description = models.CharField(max_length=300, blank=True, default="") genre = models.CharField(max_length=100, blank=True, default="") is_featured = models.IntegerField(choices=IS_FEATURED, default=0, null=False) is_popular = models.IntegerField(choices=IS_POPULAR, default=0, null=False) custom_meta_copy = models.TextField(blank=True, default="", help_text="Will be rendered inside head tag") og_title = models.CharField(max_length=300, blank=True, default="") og_description = models.CharField(max_length=300, blank=True, default="") og_image = models.FileField(upload_to='social/', blank=True, default="") twitter_title = models.CharField(max_length=300, blank=True, default="") twitter_description = models.CharField(max_length=300, blank=True, default="") twitter_image = models.FileField(upload_to='social/', blank=True, default="") intro_copy = models.CharField(max_length=200, null=False) content_copy = models.TextField(null=True, default="") image = models.FileField(upload_to=get_news_upload_path, blank=True, verbose_name="image", default="", help_text="Recommended: 1140x600") image_alt_text = models.CharField(max_length=300, blank=True, default="") published_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Meta: verbose_name = … -
Using the URLconf defined in ''.urls, Django tried these URL patterns, in this order:
First I know this is a common question. But I can't figure it out. So I have a application with name main. and I have in the main forlder a templates folder and a main folder. and in this folder I have all the html templates, like home.html. So the html page home.html looks like: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> TEST PAGE </body> </html> and my views.py: def home(request): return render(request, "main/home.html") and urls.py in main: path('', views.home), urls.py: path('main/', include('main.urls')), and settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', ] STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = 'C:\\static_files_cdbn' But if I go to: http://127.0.0.1:8000/main/home or http://127.0.0.1:8000/home I just get this error: Using the URLconf defined in schoolfruitnvwa.urls, Django tried these URL patterns, in this order: admin/ main/ [name='index'] main/ The current path, main/home, didn’t match any of these. Question. How to tackle this? -
How to put image in a pdf generated by reportlab which is stored in DO spaces - Django
I want to put my logo in pdf that is stored in digital ocean spaces. The code that I wrote was pdf.drawImage('https://dummycompany.sgp1.cdn.digitaloceanspaces.com/static/images/logo_name_header.svg', -0.10*cm,10*cm) this throws the below error fileName=<_io.BytesIO object at 0x000001D1CE603A90> identity=[ImageReader@0x1d1ce5e6f70] cannot identify image file <_io.BytesIO object at 0x000001D1CE603A90> The file is accessible if entered in the address bar. I do not understand what this error is, please suggest me what to do? -
Django and database MD5-based query
I have a model that represents a program written by the user in some programming language and the results of executing it against some test cases. The model looks like this: class UserProgram(models.Model): code = models.TextField(blank=True) execution_results = models.JSONField(blank=True, null=True) The user first types some code, which is autosaved by the frontend into the code field, then at some point they click a "Run" button, which causes a task to be scheduled which runs the current code inside of a sandbox, which returns a JSON object which details the results of the execution (the fields of this dict aren't relevant to my question), which is ultimately saved into the execution_results field. I want to be able to check whether the execution results object refers to the latest version of the code, i.e. the current value of the code field. This is used to check if, so to speak, the saved results are up to date or whether the user has made modifications to the code since the last time it was run which haven't been run yet. One solution could be to just add a field named code inside of execution_results which just contains the code the results refer to, … -
how to solve the secret key error in django project?
I was trying to run a django project from github and i keep getting this error i dont know how to solve it settings.py is split in to common.py and production.py This is common.py file from pathlib import Path import environ import os BASE_DIR = environ.Path(__file__) - 3 env = environ.Env( DEBUG=(bool, False) ) environ.Env.read_env() SECRET_KEY = env.str('SECRET_KEY') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'storages', 'accounts', 'issues' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'tracker.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(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', ], }, }, ] WSGI_APPLICATION = 'tracker.wsgi.application' # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'EST' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) FIXTURE_DIRS = [ os.path.join(BASE_DIR, 'fixtures'), ] LOGIN_REDIRECT_URL = 'issues:my-issues' LOGOUT_REDIRECT_URL = 'login' below is production.py file … -
Django: How do i remove currently:""image_url" in django image edit form?
When i am trying to edit an image field, you can see the current image path and the upload field. What I want to do is to be able to replace the shown path(the "Currently: /image_url_path.jpg" with the actual image or even remove it totally. How can i achieve this? Template <label class="btn btn-icon btn-circle btn-active-color-primary w-25px h-25px bg-body shadow" data-kt-image-input-action="change" data-bs-toggle="tooltip" title="Change avatar"> <i class="bi bi-pencil-fill fs-7"></i> {{p_form.image}} <input type="file" name="avatar" accept=".png, .jpg, .jpeg" /> <input type="hidden" name="avatar_remove" /> </label> Output -
Improving Django Performance ideas
I have an application with such architecture: BACKEND: Python + Django SERVER: gunicorn + uvicorn + openshift ASYNC: Celery + Redis DB: Oracle STORAGE: S3 Celery, Redis and API are within the same namespace in openshift. I have Django-Toolbar installed for monitoring performance. I have observed that I have veeery long response time for my application: I have already optimized django queries, but I haven't noticed signifant improvement in performance. I know that there is a lot of variables and unknowns, but do you have any ideas where to look for possible improvements? Or maybe how to investigate it better? -
Can you parameterize a template tag library on template directory?
Let's say I'm writing a form template tag library for Django, but want to be able to render both Bootstrap and UIKit forms. The Python code will be identical, except for the template reference. Simplified @register.inclusion_tag('myforms/bootstrap/formrow.html') def form_row(fieldname, labelpos, labelsize, widgetsize): return {...} vs. @register.inclusion_tag('myforms/uikit/formrow.html') def form_row(fieldname, labelpos, labelsize, widgetsize): return {...} I would like to prevent the duplication of the python code, but the @register.inclusion_tag(..) function runs very early in the Django lifecycle, so I'm not sure if it is possible, or how to do it..? -
Getting the date from the form field before calling the template in UpdateView
to update the data in the table, I use the class o inherited from Updateview, the fields are automatically filled from the database, but can I somehow in my class get the data from the user_guid field? Here is my form and class code: class CampaignEditor(UpdateView): model = Campaigns template_name = 'mailsinfo/add_campaign.html' form_class = CampaignsForm def get_context_data(self): context = super().get_context_data() data = list(Emails.objects.values()) # you may want to further filter for update purposes data = MailsTableWithoutPass(data) context['data'] = data return context class CampaignsForm(ModelForm): class Meta: model = Campaigns fields = ['name', 'subject', 'body', 'user_guid'] widgets = { 'name': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Name' }), 'subject': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Subject' }), 'body': Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Body' }), 'user_guid': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'User GuID' }), } -
Docker cache file permission
I use py-staticmaps repository for generate static map image, In normally I run this repo via python .main.py, it is working but I use the repo in Django and docker, I have a problem with cache files,. following error. What can I do? I build it locally al of them working normally but in server I run via docker-compose that is to be problem with cache -
How to show only one object in django admin list view?
Problem I wish to show only the last row of a QuerySet based on the ModelAdmin's ordering criteria. I have tried a couple of methods, but none has worked for me. Model: class DefaultConfig(models.Model): created_at = models.DateTimeField() ... Attempt 1: I tried overriding the ModelAdmin's get_queryset method and slicing super's result, but I came up with some issues. I.E: class DefaultConfigAdmin(models.ModelAdmin): model = Config ordering = ('-created_at',) def get_queryset(self, request): qs = super().get_queryset(request) return qs[<slice>] I tried the following values for [<slice>]s: [-1:]: raised an Exception because negative slicing is not supported [:1]: raised AssertionError: Cannot reorder a query once a slice has been taken. Attempt 2: I tried obtaining the max value for created_at and then filtering for records with that value. I.E: class DefaultConfigAdmin(models.ModelAdmin): model = Config def get_queryset(self, request): qs = super().get_queryset(request) return qs.annotate(max_created_at=Max('created_at')).filter(created_at=F('max_created_at')) But silly me, that works at row level, so it will only return aggregates over the row itself. Further attempts (TBD): Perhaps the answer lies in SubQuerys or Windowing and ranking. Is there a more straight forward way to achieve this though? -
how Querying Dijango date save on JSONField
i save multi date in json filed example : row 1 : [ "2022-10-26", "2022-11-10" , "2022-11-16", , "2022-11-17"] row 2 : [ "2022-09-26", "2022-09-10" , "2022-09-16"] row 3 : [ "2022-12-16" ] **how i can filter date bigger than 2022-10-01 ? ** in the example i must get row 1 & 3 database is MYSQl Django Ver 4.1 example : row 1 : [ "2022-10-26", "2022-11-10" , "2022-11-16", , "2022-11-17"] row 2 : [ "2022-09-26", "2022-09-10" , "2022-09-16"] row 3 : [ "2022-12-16" ] in the example i must get row 1 & 3 -
Django stripe is returning "No such token: 'tok_1M2CbwG5K6HWS5kNipsQbCKh'" as error message
Anytime i tried to make a test payment on stripe, it returns the error below, sk_test_hBNQ83MDWulMeAawYbGftrcC00pDMpmoAB tok_1M2CbwG5K6HWS5kNipsQbCKh 86.0 25 Request req_eboPGGTsmc4D3a: No such token: 'tok_1M2CbwG5K6HWS5kNipsQbCKh' i tried with the api keys from stripe but still it wont work. -
django clone project migrate error occured
"django.db.utils.OperationalError" occurred while setting using django cookiecutter. config\settings\base.py DATABASES = { "default": env.db( "DATABASE_URL", default="postgres://postgres:root@localhost:5432/instagram", ), } C:\dev\clone\instagram>py manage.py migrate Traceback (most recent call last): File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 244, in ensure_connection self.connect() File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 225, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\postgresql\base.py", line 203, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\dev\clone\instagram\manage.py", line 31, in <module> execute_from_command_line(sys.argv) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\migrate.py", line 91, in handle self.check(databases=[database]) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 487, in check all_issues = checks.run_checks( File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\model_checks.py", line 36, in check_all_models errors.extend(model.check(**kwargs)) File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 1461, in check *cls._check_indexes(databases), File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 1864, in _check_indexes connection.features.supports_covering_indexes File "C:\Users\krsai\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 49, in __get__ res = … -
Nginx unable to access css files in static folder for django admin
I have django running on AWS. Nginx is used as proxy with gunicorn as web server. I followed the [digitaocean][1] tutorial to configure. The problem is that django admin interface doesnt show any ui as no css files are loaded. nginx error log show this: [error] 46553#46553: *7 open() "/home/ubuntu/projectdir/static/admin/css/base.css" failed (13: Permission denied), client: 190.176.82.41, server: 142.22.84.99, request: "GET /static/admin/css/base.css HTTP/1.1", host: "142.22.84.99", referrer: "http://142.22.84.99/admin/" i changed the ownership of static folder to group www-data but still the same issue. ubuntu version is 22.04, django is 4.1.3 and python is 3.10.6 [1]: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-22-04 -
Django queryset.update() seems to act lazy
I have a Django model with a field named 'order': class Foo(models.Model): user = models.ForeignKey(...) order = models.PositiveIntegerField(null=True) class Meta: unique_together = [ ['user', 'order'], ] I want to implement an update method for my serializer to be able to reorder an object. Let's consider our object's current order is 5 and we want to change it to 1. So the scenario is sth like this: 1- make obj's current order null 2- increament order of objects that have an order between our obj's current_order and new_order 3- change obj's order to new_order My firs code was this: def update(self, instance, validated_data): user = self.context['request'].user current_order = instance.order new_order = validated_data['order'] instance.reorder(None) if new_order < current_order: qs = PIN.objects.exclude(order__isnull=True).filter( user_id=user.id, order__gte=new_order, order__lt=current_order ).update(order=F('order')+1) else: qs = PIN.objects.exclude(order__isnull=True).filter( user_id=user.id, order__gt=current_order, order__lte=new_order ).update(order=F('order')-1) But the problem is the order of updating objects in database and I get unique constraint error: ('user', 'order') = ('x', '2') already exist I did read the [django documentations][1] for queryset.update method, so, order_by method is not the result. I decided to change my code to this: user = self.context['request'].user current_order = instance.order new_order = validated_data['order'] instance.reorder(None) if new_order < current_order: qs = Foo.objects.exclude(order__isnull=True).filter( user_id=user.id, order__gte=new_order, order__lt=current_order ) … -
Python can not read characters
when i sent request in api import requests url = 'webiste' headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'} response= requests.get(url.strip(), headers=headers, timeout=10) response.encoding = response.apparent_encoding print(response.text) output is 0e1\u10e2\u10d4\u10db\u10d0 BOSE,\u10d3\u10d0\u10ec\u10e7\u10d4\u10d1\u10d0-\u10d2\u10d0\u10e9\u10d4\u10e0\u10d4\u10d1\u10d8\u10e1 \u10e1\u10d8\u10e1\u10e2\u10d4\u10db\u10d0,\u10d4\u10da\u10d4\u10e5\u10e2\u10e0\u10dd\u10dc\u10e3\u10da\u10d8 \u10d3\u10d8\u10e4\u10d4\u10e0\u10d4\u10dc\u10ea\u10d8\u10d0\u10da\u10e3\u10e0\u10d8 \u10e1\u10d0\u10d9\u10d4\u10e2\u10d8,\u10eb\u10e0\u10d0\u10d5\u10d8\u10e1 \u10e1\u10d0\u10db\u10e3\u10ee\u10e0\u10e3\u10ed\u10d4 \u10d9\u10dd\u10dc\u10e2\u10e0\u10dd\u10da\u10d8\u10e1 \u10e1\u10d8\u10e1\u10e2\u10d4\u10db\u10d0,\u10ec\u10d4\u10d5\u10d8\u10e1 \u10d9\u10dd\u10dc\u10e2\u10e0\u10dd\u10da\u10d8\u10e1 \u10e1\u10d8\u10e1\u10e2\u10d4\u10db\u10d0,\u10e1\u10e2\u10d0\u10d1\u10d8\u10da\u10e3\u10e0\u10dd\u10d1\u10d8\u10e1 \u10e1\u10d8\u10e1\u10e2\u10d4\u10db\u10d0,\u10d3\u10d0\u10d1\u10da\u10dd\u10d9\u10d5\u10d8\u10e1 \u10e1\u10d0\u10ec\u10d8\u10dc\u10d0\u10d0\u10e6\u10db\u10d3\u10d4\u10d2\u10dd \u10d3\u10d0\u10db\u10e3\u10ee\u10e0\u10e3\u10ed\u10d4\u10d how to encode in utf-8 ? -
JWT token expire successfully but still able to access Django API's
I'm using JWT token auth in django. I set access-token timing to '1 minute' after 1-min the access & refresh token get expire and but when i try to access API url it gives access and show data. i check with the verifyToken same token shows invalid. and using same token for api call it shows success=True and print 'hello1' Can anyone tell me whats wrong with JWT Check below code for referance. JWT Docs for referance. https://django-rest-framework-simplejwt.readthedocs.io/en/latest/ Code: Setting.py SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'AUTH_HEADER_TYPES': ('Bearer', ), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=1), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PAGINATION_CLASS': 'slash.controllers.pagination.PageNumberCustomPagination', 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', } CRONJOBS = [ ('0 23 * * *', 'slash.cron.delete_expired_blacklisted_token'), ] CORS_ALLOW_METHODS = ( 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS' ) DRF_API_LOGGER_DATABASE = True DRF_LOGGER_QUEUE_MAX_SIZE = 50 DRF_LOGGER_INTERVAL = 10 DRF_API_LOGGER_EXCLUDE_KEYS = ['password', 'token', 'access', 'refresh'] # Sensitive data will be replaced with "***FILTERED***". DRF_API_LOGGER_SLOW_API_ABOVE = 200 URLS.py path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('token/verify/', TokenVerifyView.as_view(), name='token_verify'), path('token/blacklist/', TokenBlacklistView.as_view(), name='token_blacklist'), … -
serialize write-only field which is not present in django model using viewset
I am using a django viewset and I want to serialize a field which is not in the model. it is an extra field that would be passed by the user. class Bank(models.Model) name = models.CharField(max_length=255) objects = models.Manager() class BankingDetailsSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) name = serializer.CharField() documents = serializers.ListField(write_only=True) class Meta: model = Bank fields = ['id', 'name', 'documents'] I am using a modelViewset for my view. However I noticed that after I serialize, the documents field is missing