Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: TemplateSyntaxError: Could not parse the remainder with user authorization
I am using django for a project and I am trying to let the user access a page if they are authenticated and authorized to perform that action. I have a model called Post and my app is called myblog. I am currently getting the error Django:Could not parse the remainder: '('myblog.add_Post')' from 'user.has_perm('myblog.add_Post')' {% extends 'base.html' %} {% block title %} Add Post... {% endblock %} {% block content %} {% if user.is_authenticated and user.has_perm('myblog.add_Post') %} <h1>Add A Blog Post</h1> <br/><br/> <div class="form-group"> <form method="POST"> {% csrf_token %} {{form.as_p}} <button class="btn btn-outline-success">Post</button> </div> {% else %} Access Denied! {% endif %} {% endblock %} If i remove the "and user.has_perm('myblog.add_Post')" this template works; however, I need to check if the user has permissions. -
Pickling issue in Django management command but works in regular Python environment
I am facing a pickling issue specifically when using the dfi.export() function within a Django management command, while the same code works without any issues in a regular Python environment. I am using Django version 2.2.4 and Python version 3.10.0 The code involves exporting a Pandas DataFrame to an image file using the dfi.export() function from the dataframe_image library. The goal is to generate an image file from the DataFrame within the Django management command. from decimal import Decimal import dataframe_image as dfi import pandas as pd def color_negative_red(val): color = 'red' if val < 0 else 'green' return 'color: %s' % color futures_risk_table_1={'PNL ITD': {'BTCUSDT': Decimal('-366.91850000'), 'ETHUSDT': Decimal('20.11800000'), 'TOTAL': Decimal('-241.39039746')}, 'FUNDING ITD': {'BTCUSDT': Decimal('285.87113447'), 'ETHUSDT': Decimal('11.23925312'), 'TOTAL': Decimal('230.66567605')}, 'DELTA VOLUME ITD': {'BTCUSDT': Decimal('11413146.44950000'), 'ETHUSDT': Decimal('3739417.96300000'), 'TOTAL': Decimal('16904364.71747007')}, 'HEDGE VOLUME ITD': {'BTCUSDT': Decimal('5858487.37460000'), 'ETHUSDT': Decimal('2208062.55358281'), 'TOTAL': Decimal('9812329.10964750')}, 'GROSS OI': {'BTCUSDT': 1142375.5, 'ETHUSDT': 34665.484173792, 'TOTAL': 1507336.3651526954}, 'DEFICIT': {'BTCUSDT': 4126.2, 'ETHUSDT': 6105.2643768768, 'TOTAL': 14643.812931051634}, 'PNL 4HR': {'BTCUSDT': Decimal('-110.42400000'), 'ETHUSDT': Decimal('-19.04450000'), 'TOTAL': Decimal('-58.85838895')}, 'FUNDING 4HR': {'BTCUSDT': Decimal('51.78039448'), 'ETHUSDT': Decimal('-0.15025893'), 'TOTAL': Decimal('35.63325078')}, 'DELTA VOLUME 4HR': {'BTCUSDT': Decimal('2554914.73350000'), 'ETHUSDT': Decimal('1032545.61450000'), 'TOTAL': Decimal('3892830.05291726')}, 'HEDGE VOLUME 4HR': {'BTCUSDT': Decimal('1393409.78960000'), 'ETHUSDT': Decimal('332477.41883101'), 'TOTAL': Decimal('2029616.07723308')}} futures_risk_table_1=pd.DataFrame.from_dict(futures_risk_table_1) print(type(futures_risk_table_1)) futures_risk_table_1_styler = futures_risk_table_1.style.applymap(color_negative_red).set_caption("Futures Risk Monitor").format("{:20,.0f}").set_properties( subset=pd.IndexSlice[futures_risk_table_1.index[-1], :], **{'background-color': 'lightblue'} ) futures_risk_table_1_styler dfi.export(futures_risk_table_1_styler,"files/images/futures_risk_table_1_styler.png") … -
Better way in updating/creating model data through local script
I have a python web scraping script that updates/create Django models instances in Production from my local machine. The reason I'm doing this way and not using something like celery is because I run multiple asynchronous requests and do not want to the server costs raises. Currently I do this through os.environ.setdefault("DJANGO_SETTINGS_MODULE # import whatever model... # Scraping logic... I know this is not a good way but is there any better way to do it? -
Integrate keycloak as a server authentication in django api
I'm trying to connect Django with Keycloak using mozilla-django-oidc the problem is when i log in succefully using the keycloak login i got redirect to my localhost:8000 instead of my LOGIN_REDIRECT_URL that i have declared . my django settings.py my redirect url declared in keycloak dashboard -
Django JWT token not working properly with my react app
When I have SessionAuthentication it's working but the same code didn't work when enabling jwt token-based authentication. Take a look at my working code when SessionAuthentication: settings.py INSTALLED_APPS = [ .... others 'rest_framework', 'rest_framework_simplejwt', 'drf_spectacular', 'corsheaders', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), } API endpoint code @api_view(['GET']) @permission_classes([IsAuthenticated]) def get_user_profile(request): print(request.headers) if request.user.is_anonymous: return Response({'error': 'User is not authenticated.'}, status=status.HTTP_401_UNAUTHORIZED) user = request.user profile = Profile.objects.get(user=user) data = { 'username': user.username, 'account_point': profile.account_point, 'mobile_number': profile.mobile_number, 'city': profile.city, 'country': profile.country, 'address': profile.address, 'is_verified_email': profile.is_verified_email, 'is_verified_mobile_number': profile.is_verified_mobile_number, } return Response(data, status=status.HTTP_200_OK) my react code: let headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', }; axios.get(`${CustomDomain}/user_profile/`,{withCredentials:true,headers: headers}) .then((res) => { console.log(res); }) .catch((error) => { console.error(error); }); When added JWTAuthentication in my api code then it's not working. my not working code: @api_view(['GET']) @authentication_classes([JWTAuthentication]) #not working when added @permission_classes([IsAuthenticated]) def get_user_profile(request): .... others code error which I am getting in my frontend {"detail":"Authentication credentials were not provided."} I also added few screenshot here from my network tab -
GCP Cloud Auth Proxy connection reset by peer
A web app built in Django is hosted in GCP Cloud Run. It has been working flawlessly for more than a month without any issues. Then I started getting issues in the past week when I ran locally python3 manage.py runserver from one terminal, and from another one is the auth proxy. django.db.utils.OperationalError: connection to server at "127.0.0.1", port 5432 failed: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. Out of nowhere when I try to connect to the Cloud SQL using auth proxy I get the below error: cloud_sql_proxy -instances=gcloud-xx-yz:europe-west3:mydb=tcp:5432 2023/06/19 21:44:02 Listening on 127.0.0.1:5432 for gcloud-xx-yz:europe-west3:mydb 2023/06/19 21:44:02 Ready for new connections 2023/06/19 21:44:02 Generated RSA key in 122.002994ms 2023/06/19 21:44:18 New connection for "gcloud-xx-yz:europe-west3:mydb" 2023/06/19 21:44:18 refreshing ephemeral certificate for instance gcloud-xx-yz:europe-west3:mydb 2023/06/19 21:44:19 Scheduling refresh of ephemeral certificate in 54m59.590187s 2023/06/19 21:44:19 couldn't connect to "gcloud-xx-yz:europe-west3:mydb": read tcp 172.30.21.57:57791->xx.xx.xx.xx:3307: read: connection reset by peer I have no clue where this IP is coming from 172.30.21.57. This is not the ip from VPC (Not the CIDR range I am using at least) nor from my local computer. I tried with --private-ip but the same issue pops up. … -
Django-taggit: can not have all the data with key in tags object
I am trying to achieve my event model with tags object nested with it. But tags have only name field, I need both id, name and slug as well. here is my Model looks like model.py class Event(models.Model): title = models.CharField(max_length=151, db_index=True) description = models.TextField(blank=True, null=True) tags = TaggableManager() serializers.py class EventSerializer(serializers.ModelSerializer): slug = serializers.SerializerMethodField() tags = TagListSerializerField() the Result I am having: { "id": 52, "slug": "52-aperiam-amet", "tags": [ "hello", "world" ], "title": "Aperiam amet", "description": "Quibusdam ipsum sun Quibusdam ipsum sun Quibusdam ipsum sun ", }, but expected tags nest should look like "tags": [ { id:"1", slug:'1-hello', name:"hello" }, { id:"2", slug:'2-world', name:"world" }, ], -
I'm getting a problem when a JPEG image is uploaded in Django
I'm developing an app in Django, and I'm getting a problem when I try to upload an JPEG image, the problem is this: Internal Server Error: /publish_offer/ Traceback (most recent call last): File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\utils\deprecation.py", line 136, in __call__ response = self.process_response(request, response) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\G-FIVE\Desktop\Projects\revenue\venv\Lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: ^^^^^^^^^^^^ AttributeError: 'SafeString' object has no attribute 'get' [19/Jun/2023 14:08:35] "POST /publish_offer/ HTTP/1.1" 500 66377 With PNG images does not occur this, I'm really confused. I'll share my code: My Models: class ImagenesOferta(models.Model): imagen = models.ImageField(verbose_name='Imagen Oferta', blank=False, null=False, upload_to='img_ofertas/') class Meta: verbose_name = 'Imagen de Oferta' verbose_name_plural = 'Imagenes de Ofertas' ordering = ['-id'] class Oferta(models.Model): titulo = models.CharField(verbose_name='Título', max_length=100, null=False, blank=False) descripcion = models.TextField(verbose_name='Descripción', null=True, blank=True) cantidad = models.PositiveSmallIntegerField(verbose_name='Cantidad', null=False, blank=False, default=1) valor = models.DecimalField(verbose_name='Valor', max_digits=3, decimal_places=2, null=False, blank=False) material = models.CharField(verbose_name='Material', max_length=20, null=False, blank=False, choices=MATERIAL_CHOICES) imagenes = models.ManyToManyField(ImagenesOferta, verbose_name='Imagenes de la Oferta', blank=True) usuario = models.ForeignKey(Usuario, verbose_name='Usuario', null=False, blank=False, on_delete=models.CASCADE) is_active = models.BooleanField(verbose_name='Activo/Inactivo', default=True) vendido = models.BooleanField(verbose_name='Vendido', default=False) fecha_creacion = models.DateTimeField(verbose_name='Fecha de Creación', auto_now_add=True) def __str__(self): return self.titulo class Meta: verbose_name = 'Oferta' verbose_name_plural = 'Ofertas', ordering = ['-fecha_creacion'] My view: @login_required(login_url='login') def … -
[django,AWS S3 problem]An error occurred (AccessDenied) when calling the PutObject operation: Access Denied
I am trying to make a django gallery site using S3 bucket. I followed the tutorial on youtube It worked well locally but didnt work on EC2. I have checked the IAM user access id and secret key and they are correct. I made a new access key but didnt work. Errror Message (...) Exception Type: ClientError at /gallery/add/ Exception Value: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied Settings.py (couldnt upload it looked like spam) S3 Policy { "Version": "2008-10-17", "Statement": [ { "Sid": "AllowPublicRead", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::photoshare20230619/*" } ] } IAM User ScreenShot of IAM User My buddy's Summary (because I worked with AI) You're running a Django application on a server using Gunicorn and Nginx. The application includes a feature to upload photos, which are then stored in an Amazon S3 bucket. However, you're encountering a few issues: You're getting a Server Error (500) from Django. The error logs indicate that this is due to an AccessDenied error when the application tries to put an object in the S3 bucket. You've confirmed that the IAM user has the AmazonS3FullAccess policy and the bucket policy allows the … -
I need to create a project manager for a university in Django
I need advice on how to create a Django app to create "projects" by adding "staff", a title and a description to it. My app is supposed to read a small database with the data of the non-academic staff of a university, i'm guessing I should create an independent app to do this. After that, another app is supposed to let the administrator create "projects", add them staff members from the previously mentioned DB, create a description to the project and create "tasks" in it. Obviously the app will use it's own DB to register the projects, it's tasks and it's members. My question is how should I make these apps? how do I read a DB of staff? and how can I create these projects and tasks? should I make an entirely different class "task" from the class "project"? I haven't tried anything yet, I'm afraid to screw up. -
i built a server from my playstation 3 to run my django-drf app [closed]
i built a server from my playstation 3 to run my django-drf app, How can I write software to compress data on a PlayStation 3 to improve the performance of my Django-DRF app? The PlayStation 3 has limited RAM, so it is important to find ways to compress data in order to improve the performance of my Django-DRF app. -
Show Button in Admin ListView - Upgrade to Django 4
I have upgraded to django 4.2.2. from 1.X. In my listview I have buttons for every element, the button contains a link. Everything worked well but after upgrading the quotes are rendered as '&quot' in html instead of '"'. def clone_button(self,obj): button = "<button type=\"button\" onclick=\"location.href='/admin/clone/%s/%s'\";>Clone</button>" % (obj.id,"keep_date") return button clone_button.allow_tags=True What do I have to do differently now? -
Django rest api and axios post request don't work
I am trying to make a simple api where a user writes something in an input, presses a button and a new instance is added in a database. To do this I am using react and django rest framework. App.js const [name,setName] = useState('') const handleChange = (e) => { setName(e.target.value) } function handleClick(e) { e.preventDefault() axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = "X-CSRFTOKEN" axios.post('http://127.0.0.1:8000/post/', { headers: { "Content-Type": "application/x-www-form-urlencoded", 'X-CSRFToken': 'csrftoken' }, data:{ title: name, name: name } }) } return ( <> <form> <input type='text' value={name} onChange={handleChange} /> <button onClick={handleClick}>OK</button> </form> </> ); views.py @api_view(['POST']) def home2(request): serializer = ItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) urls.py from django.urls import path from . import views urlpatterns = [ path('api/',views.home,name='home'), path('post/',views.home2,name='home2'), path('a/',views.home3,name='home3') ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'main', 'corsheaders' ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True But when I press the button I get manifest.json:1 GET http://127.0.0.1:8000/manifest.json 404 (Not Found) and manifest.json:1 Manifest: Line: 1, column: 1, Syntax error. in javascript. In django I get "POST /post/ HTTP/1.1" 200 0 Also I am using npm run build for javascript and manifest.json is in public folder. React is inside django and the structure looks like this: … -
csrftoken is null in React-rendered form
I am using purely React for the frontend, with Django on the backend. I am using React to render a form & not using the Django form. I am currently unable to make a POST request from my React front end (http://localhost:3001/) to my Django backend (http://127.0.0.1:8000) because of the Forbidden (CSRF cookie not set.): /createListing error. This is what my POST request code looks like async function createListing(listing) { let csrftoken = getCookie('csrftoken'); const response = await fetch( "http://127.0.0.1:8000/createListing/", { method: "POST", body: JSON.stringify(listing), headers: { "Content-Type": "application/json", "X-CSRFToken": csrftoken }, } ); const data = await response.json(); return data; } // The following function are copying from // https://docs.djangoproject.com/en/dev/ref/csrf/#ajax function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } I got this snippet from a SO answer. This is my Django API endpoint def createListing(request): # Creating a new Listing must be via … -
"empty_value_display" doesn't work for an empty value on "change list" page in Django Admin
I defined name field which accepts an empty string in Person model as shown below: # "models.py" class Person(models.Model): name = models.CharField(max_length=20, blank=True) def __str__(self): return self.name Then, I set "-empty-" to AdminSite.empty_value_display, ModelAdmin.empty_value_display, @admin.display()'s empty_value or view_name.empty_value_display as shown below: # "admin.py" admin.site.empty_value_display = "-empty-" # Or @admin.register(Person) class PersonAdmin(admin.ModelAdmin): list_display = ("view_name",) empty_value_display = "-empty-" # Or @admin.display(empty_value="-empty-") # Or def view_name(self, obj): return obj.name view_name.empty_value_display = '-empty-' # Or But, -empty- is not shown even though I saved an empty string as shown below: So, how can I show -empty- when I save an empty string? -
Host the django on https in ec2 for production with a free SSL certificate for it. Without a domain
I have a django deployed on aws and i have a frontned react js running on a https endpoint server. The frontend allows only https requests to be made. But when i run the django python manage.py runserver in my "production" of django app on ec2 i only get to use http not https. So, is there any way to get a free SSL certificate for that django app running on ec2 public ip without a domain. -
Template doesn't exist at /users/login while creating a login page using Django
TemplateDoesNotExist at /users/login/ registration/login.html Request Method: GET Request URL: http://127.0.0.1:8000/users/login/ Django Version: 4.2.2 Exception Type: TemplateDoesNotExist Exception Value: registration/login.html Exception Location: C:\Users\shubh\OneDrive\Desktop\django-app\main-app\env\Lib\site-packages\django\template\loader.py, line 47, in select_template Raised during: django.contrib.auth.views.LoginView Python Executable: C:\Users\shubh\OneDrive\Desktop\django-app\main-app\env\Scripts\python.exe Python Version: 3.11.4 Python Path: ['C:\Users\shubh\OneDrive\Desktop\django-app\main-app\ablog', 'C:\Users\shubh\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\shubh\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\shubh\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\shubh\AppData\Local\Programs\Python\Python311', 'C:\Users\shubh\OneDrive\Desktop\django-app\main-app\env', 'C:\Users\shubh\OneDrive\Desktop\django-app\main-app\env\Lib\site-packages'] Server time: Mon, 19 Jun 2023 15:46:25 +0000 I should be able to get a Login Page I should have gotten a login page but the template file can't be fetched -
why django celery beat worker not relaying expected tasks data
hello everyone i'm trying to perform a task like an APY(annual percentage yield) kind of funtionality, where my user savings will increase by a certain percentage at an interval(monthly or by seconds). my beat scheduler is working but the worker is not returning the expected output in the terminal, nor is it altering the value MODELS.PY def save(self,*args,**kwargs): if self.funds == '' or self.funds is None: self.funds=0 if self.referrer_bonus== '' or self.referrer_bonus is None: self.referrer_bonus=0 if self.total== '' or self.total is None: self.total=0 if self.bonus== '' or self.total is None: self.bonus=0 self.bonus=int(self.referrer_bonus)*15/100 if self.withdrawn == False: # self.total=(int(self.funds)*15/100 * int(self.funds))+self.bonus self.total=int(self.funds)+self.bonus interval=IntervalSchedule.objects.get(every=20,period='seconds') if self.total != 0 and self.funds!=0: PeriodicTask.objects.create( interval=interval, name=f'{self.user.email} investment increment', task='increment_user_funds', start_time=self.timestamp, args=json.dumps([self.total,self.funds]), ) # increment_user_funds(self) super().save(*args,**kwargs) CELERY.PY from __future__ import absolute_import,unicode_literals from celery import Celery import os from celery import shared_task from django.conf import settings from celery.schedules import crontab # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rawfx.settings') app = Celery('rawfx') app.config_from_object('django.conf:settings', namespace='CELERY') # app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.autodiscover_tasks() TASK.PY from __future__ import absolute_import,unicode_literals from celery import Celery from celery import shared_task from rawfx.celery import app @app.task def increment_user_funds(total,funds): total=int(total)+int(funds)*15 print(total) return total below is the picture of both my worker and beat [![beat][2]][2] … -
Django unable to get Environment Variables from Vercel
I am hosting a Django application with Vercel. To help improve the security of the app I attempted establishing the environment variables within Vercel and retrieving them in the settings.py file. The app no longer works, and when I tried to revert the changes and start using the .env file again, the app is still completely down. When Vercel builds the new deployment the entire site is down because Django cannot connect to the db. My code is as follows: #settings.py import os.path import os from django.contrib.messages import constants as messages from pathlib import Path import pymysql DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": os.environ.get('DB_NAME'), "HOST": os.environ.get('DB_HOST'), "PORT": os.environ.get('DB_PORT'), "USER": os.environ.get('DB_USER'), "PASSWORD": os.environ.get('DB_PASSWORD'), "OPTIONS": {'ssl': {'ca': os.environ.get('MYSQL_ATTR_SSL_CA')}} } } #.env/Vercel environment variables DB_NAME=xxxxxx DB_USER=xxxxxxxxxxxxxxx DB_PASSWORD=xxxxxxxxxxxxxxxxxxxxxxxxxx DB_HOST=xxxxxxxxxxxxxxxxxxxxxx DB_PORT=xxxx MYSQL_ATTR_SSL_CA=xxxxxxxxxxxxxxxxxxxxxxx I have no idea why the .env wont even work now as no changes were made to the code other than the removal, then replacement of the .env file. Any direction on this would be greatly appreciated. -
How do I output only the last form submission in for a form. Using React and javascript here. Thank you
Currently, I have a form on a page. I wish to display the latest form submission below the form, but it will display all the form submissions till date. I am wondering how to approach this issue. I have no idea how to approach this issue. I tried several methods, such as using data filter, or using an if else statement to see if the input value is same as the latest logged value. However, I have no idea what to pass in as the argument and I keep getting errors.. Hope I can receive tips on how to tackle this issue. Thank you so much. This is the frontend render of the website This is an example of the backend database. Please let me know if you guys require any extra information. Thank you so much! -
CSRF Token issue in Django app deployed in Railway, "CSRF verification failed. Request aborted."
The error I get is "CSRF verification failed. Request aborted." Error Image The site works fine and there are no issues on localhost I tried adding this base domain in my settings.py but I am still getting the same error: enter image description here I also tried this fix, and reloaded the requirements.txt but to no avail: enter image description here Any help would be appreciated. -
How to change link in Django admin backend "Webseite anzeigen"
I am developing a Django app and using both the admin backend and the developed website, which I refer to as the frontend, for the user. In the admin backend, there is a button "Webseite anzeigen" (Django German version) located at the top right corner. The code for this button is provided by Django. This button leads to the website or the frontend. I want to modify this button but I am not sure where to find it. For example, I want to increase the font size and change the color. -
Django app sending jwt token and refresh token to browser cookie but why my frontend app couldn't verify it?
I am using jwt authentication on my Django app. When user login to my website my server sends jwt token and refresh token to the browser cookie but I am getting "User is not authenticated." error and not getting any profile data for my user_profile/ api endpoint. Even I can see jwt token and refresh token also avaiable on the browser cookie after user login and aslo {withCredentials:true} in my axois post. here is my login code: @api_view(['POST']) def user_login(request): if request.method == 'POST': ...others code refresh = RefreshToken.for_user(user) response = Response({'message': 'Login successful.'}, status=status.HTTP_200_OK) response.set_cookie('jwt_token', str(refresh.access_token)) response.set_cookie('refresh_token', str(refresh)) return response else: return Response({'error': 'Invalid credentials.'}, status=status.HTTP_401_UNAUTHORIZED) here is my api for get user profile @api_view(['GET']) def get_user_profile(request): if request.user.is_anonymous: return Response({'error': 'User is not authenticated.'}, status=status.HTTP_401_UNAUTHORIZED) user = request.user profile = Profile.objects.get(user=user) data = { 'username': user.username, } return Response(data, status=status.HTTP_200_OK) my settings.py REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), } my frontend code: axios.get(`${CustomDomain}/user_profile/`,{withCredentials:true}) .then((res) => { console.log(res); }) .catch((error) => { console.error(error); }); }) ; -
How to show items in dropdown based on alphabet search from Model in Django?
Just like Stackoverflow Tags auto-complete dropdown, I have a model of name Tags which contains 68311 name of Tags and key which contains the first alphabet it starts with. **Note ** : There are few words which starts with dot (.) for example, (.post) in that case, we will consider the second alphabet. class Tags(models.Model): name = models.CharField(max_length=255) key = models.CharField(max_length=1, null=True, default='') def __str__(self): return self.name def save(self, *args, **kwargs): if not self.key: if self.name.startswith('.'): self.key = self.name[1].upper() else: self.key = self.name[0].upper() super().save(*args, **kwargs) class Meta: indexes = [ models.Index(fields=['name']) Following is the view I am using to search the possible words starts with the user specified alphabet. def tag_search(request): search_term = request.GET.get('search', '') print("search_term", search_term) if search_term.startswith('.'): search_term = search_term[1].upper() else: search_term = search_term[0].upper() tags = Tags.objects.filter(name__istartswith=search_term).values_list('name', flat=True) return JsonResponse({'tags': list(tags)}) When I try to input any character from frontend on the auto=-complete dropdown, It executes tag_search only once and provide the words which contains first character that the user provider. What I required is when the user delete the first character and delete and type another one, then it should not show the result of previous written character. For example, I refreshed the page, and in auto-complete … -
Why date from data base dont show on home.html Python Django
The problem is that date from database that i have created doesnt show on my html page and i dont understand what is the problem maybe i connected something wrong models.py from django.db import models class table_1(models.Model): datetime = models.DateField() machine_1 = models.IntegerField() machine_2 = models.IntegerField() dryer = models.IntegerField() machine_1_time = models.TimeField() machine_2_time = models.TimeField() dryer_time = models.TimeField() def __int__(self): return self.title settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'data', 'USER': 'postgres', 'PASSWORD': '1221', 'HOST': 'localhost', 'PORT': '5432', } } home.html <h2>1{{ tablet.machine_1_time }}</h2> {{ mytable.machine_1 }} {% for item in tablet %} <h3>{{ item.datetime }}</h3> <!-- Выведите другие поля модели --> {% endfor %} views.py from django.shortcuts import render from .models import table_1 def home(request): tablet = table_1.objects.all() return render(request, 'table/home.html', {' tablet': tablet}) When i runserver there is no data shown at all machine_data.sql create table machine_dara ( datetime DATE, machine_1 INT, machine_2 INT, dryer INT, machine_1_time INT, machine_2_time INT, dryer_time INT ); insert into machine_dara (datetime, machine_1, machine_2, dryer, machine_1_time, machine_2_time, dryer_time) values ('2022-12-31', 55, 77, 35, 84, 91, 63); insert into machine_dara (datetime, machine_1, machine_2, dryer, machine_1_time, machine_2_time, dryer_time) values ('2023-01-14', 67, 69, 79, 80, 50, 64); insert into machine_dara (datetime, machine_1, machine_2, dryer, …