Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Spotipy can't access user's info using SpotifyOAuth (authorization flow error)
I'm trying to do an API using spotify, and spotipy (I use django rest framework for this). I followed the documentation and when I use SpotifyClientCredentials It works just fine but I can't access user's information (in my exemple I try to get the username). To do this, spotipy tells me to use SpotifyOAuth But then things get worse, I have a "test" endpoint and when I connect my account, postman opens TONS of tabs https://accounts.spotify.com/authorize?client_id=....&response_type=code&redirect_uri=... Here is my code : @api_view(['GET']) @permission_classes([permissions.IsAuthenticated]) def test(request): if request.method == 'GET': urn = 'spotify:artist:3jOstUTkEu2JkjvRdBA5Gu' sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=envi.SECRET_ID, client_secret=envi.SECRET_PASS, redirect_uri=envi.SPOTIPY_REDIRECT_URI)) artist = sp.artist(urn) print(artist) user = sp.current_user() print(user) return JsonResponse(test, safe=False) It's just the code from the documentation, but I don't know where to look. -
Adding ordering on serializer (Django)
I have an issue for which I'm not sure if I am getting the right path to the soluction, hope you guys could help me out. I have added an extra field to my serializer, called distance (distance is equal the distance in miles between 2 different locations) I am looking to return the Business Object order my this new field, would it be possible? or am I taking the wrong path for this soluction? Down here you have my Serializer and ModelViewSet Serializer class BusinessesSerializer(serializers.ModelSerializer): distance = serializers.SerializerMethodField('get_location') class Meta: model= Businesses fields = ('id', 'address_first_line', 'address_second_line', 'city', 'region', 'post_code', 'phone_number', 'logo', 'join_date', 'distance') def get_location(self, business): ip_info = requests.get('https://api64.ipify.org?format=json').json() ip_address = ip_info["ip"] response = requests.get(f'http://api.ipstack.com/{ip_address}?access_key=8eba29fcae0bbc63c1e93b8c370e4bcf').json() latitude = response.get("latitude") longitude = response.get("longitude") first = (float(latitude), float(longitude)) second = (business.lat, business.long) distance = great_circle(first, second).miles return distance ModelViewSet class BusinessesViewSet(ModelViewSet): serializer_class = BusinessesSerializer queryset = Businesses.objects.all() -
In Django how can I get result from two tables in a single queryset without having relationship?
I have two models like this : class A(models.Model): is_available = models.BooleanField() date = models.DateTimeField(auto_now_add=True) # Some Other Fields class B(models.Model): is_available = models.BooleanField() date = models.DateTimeField(auto_now_add=True) # Some Other Fields I want to get the records from both models in a single list of dictionaries based on available or not and filter by date in descending order. How can I do it? -
Values join two tables without prefetch_related in Django with Postgress
I have one table "table1" I have other table "table2" "Table2" has a foreing key with "table1" I need to get "table1" values, with all register joined in "table2" in Django Table1.objects.filter().values("id","table2__id") My question is simple. Should I use select_prefetch mandatorily? Table1.objects.prefetch_related('table2').filter().values("id","table2__id") I'm suspecting that a lot of prefetch_related in one query are consuming a lot of memory, because is so slow. Thanks -
How to compute on the fly + download a file - React / Django?
I am working on an app which uses React and Django. I need a functionality whereby a user on the app can click a button and download a csv file on their machine. Importantly, the file is not already available anywhere, it needs to be generated on the fly when the user requests it (by clicking on the download button). I am thinking of implementing this flow: When the user clicks on the button, an API call is made which tells the backend to generate the csv file and store it in an s3 bucket the backend then sends a response to the frontend which contains the URL that the frontend can access to download the file from the s3 bucket the file gets downloaded Would this be a good approach? If not, what is the best practice for doing this? -
Filter model without using distinct method
I have a model with a list of products. Each product has an ID, price, brand, etc. I want return all the objects of the model where brand name is distinct. I am currently using django's built-in SQLite, so it does not support something like products = Product.objects.all().distinct('brand') Is there another way of returning all the objects where the brand name is distinct? -
Why is model._meta.get_fields() returning unexpected relationship column names, and can this be prevented?
Imagine I have some models as below: class User(AbstractUser): pass class Medium(models.Model): researcher = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="medium_researcher") old_medium_name = models.CharField(max_length=20, null=True, blank=True) class Uptake(models.Model): material_quality = models.CharField(max_length=20, null=True, blank=True) medium = models.ForeignKey(Medium, on_delete=models.CASCADE, blank=True, null=True, related_name="uptake_medium") Now I have a function to return all column names to generate some overview in my HTML as such: from database.models import Medium MODEL_HEADERS=[f.name for f in Medium._meta.get_fields()] MODEL_HEADERS ['uptake_medium', 'id', 'researcher', 'old_medium_name'] Why does this return uptake_medium? As this is a ForeignKey relation set within the Uptake model, it should only be present within the Uptake model right? When I review the admin models this column does not show up, neither in the db.sqlite3 model when checking Uptake, so it seems to be sort of hidden, and only show up when requested with _meta. The relationship seems to be correct... This is causing a lot of problems with my code, and it would be great if only the 'non-meta' columns only could be returned. How should I approach? -
Is there any way to get name of request path in Django
I wanted to get django re_path's name parameter value from request or in any way. I have a url pattern like that, re_path(r'^user/query/page/list$', views.UserListView.as_view(), name="user_list") When request comes with user/query/page/list, I want to match it with name or directly get name of the path that described in re_path. I checked all request data and didn't reach it. -
I want to create a temporary url for login in my django project, how would I go about doing that?
My friend is teaching me coding via a project and I wanted to see if I could go a bit beyond what he is currently asking. I'd like to have a code to create a temporary url to give out for my site to create a profile. I basically want it to jump to a "create profile page", allow them to create the profile, and then redirect back to the home page. Keep in mind, I'm relatively new to this, so any and all excess explanation is more than welcome! I read some things about model.tempurl might be what I'm looking for, but I couldn't figure out where the temp url gets spit out. -
filter queryset for multiple models in Django
I'm implementing a search feature where I'm matching keys from the description. and also matching media if description and media type of ['mp4','mkv','mov','avi'] match so the condition is satisfied. So I have tried many methods but didn't find an efficient way. to make it possible without for loop. I want to use those together. description and media type ['mp4','mkv','mov','avi'] postinlang_queryset = PostInLanguages.objects.filter(description__contains=search_name) media_type_query_set = LanguageMedia.objects.filter(content_type__contains ['mp4','mkv','mov','avi']) -
Django UserCreationForm and Bootstrap Forms Layouts
I am trying to extend the UserCreationForm using a Bootstrap layout style for the field username. After the input tag in the registration form, I would like to add a div element like an example that I have readapted from the Bootstrap page: i.e. suggesting the user to enter the same username as the company domain. Let's focus to the bare minimum. The form readapted from Bootstrap is: <form class="row gy-2 gx-3 align-items-center method="POST" action="{% url 'register' %} "> <div class="col-auto"> <div class="input-group"> <input type="text" name="username" class="form-control" placeholder="your.username" id="id_username"> <div class="input-group-text">@company.domain.com</div> </div> </div> <div class="col-auto"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> Which produces the following: For the moment, I am using only {{form.as_p}} in my html template file: <form class="row gy-2 gx-3 align-items-center method="POST" action="{% url 'register' %} "> {{form.as_p}} <div class="col-auto"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> And I don't know how to add the <div class="input-group-text">@company.domain.com</div> part embedded in a <div class="input-group">...</div> block. My actual forms.py is a bit more complex, but readapted for this minimum example it contains the widget attributes as follows: class SignupForm(UserCreationForm): username = forms.CharField(label="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'your.username'})) class Meta: model = User fields = ( 'username', ) Without additional libraries, is there … -
Why do i keep encountering this error when i try to migrate on django app
return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: theblog_categories i expected to migrate succesfully -
Preventing certain values adding to Django model
I'm trying to put a restriction on my Django model. I have a user model and then a model which allows one user to "follow" another. I want to put a restriction so the user cannot follow themselves. It's not really working at all but I'm sort of stuck what to do. When I try to add a new object. It will let me alter an existing entry but if I try to create a new one I get the error: Follower: Follower object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. It's like I have to save it somehow before I check for the items but I'm not sure how to go about it. Models class User(AbstractUser): pass class Follower(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, related_name="followers", unique=True) follows = models.ManyToManyField(User,blank=True,related_name="follows") # Prevent User from following themselves def save(self, *args, **kwargs): if self.follows.contains(self.user): return else: super().save(*args, **kwargs) I've tried variations of the if statement and I've tried using a for loop to go through the ManytoMany field but I can see the object doesn't exist yet -
Get n value with n parameter with Django Queryset
this is my first question. If my question is not clear, let me know :) So I learn Django (learning by doing) for 4 Months in my project. I have one table name material, which is the table contains material name and price. Here I will describe my table: id materialName price 1 Not Required 0 2 Material 1 123 3 Material 2 456 4 Material 3 900 I want to calculate the total material price by getting the price from the table. It looks ok if I only want to get 1 price only. But, I need to get 4 values of prices from what the user wants in input. Let's say the user chooses Material 3, Material 2, Not Required and Not Required. So there is 4 material price. Then, I use a queryset like this: x = rawmaterial.objects.filter(Q(materialName = 'Material 3') | Q(materialName = 'Material 2') | Q(materialName = 'Not Required') | Q(materialName = 'Not Required')).values_list('price',flat=True) but the result is (900, 456, 0) not like (900, 456, 0, 0). I have been trying with SQL query using OR, is there any possibility to get 4 values? Thank you :) -
XMLParser.__init__() takes 1 positional argument but 4 were given
I am getting this error while running the below command:- Python version=3.10.8 Django version=2.1 openpyxl=2.6.2 python manage.py runserver 127.0.0.1:8000 Error:- Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x118793400> Traceback (most recent call last): File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/opt/homebrew/Cellar/python@3.10/3.10.8/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/tablib/__init__.py", line 3, in <module> from tablib.core import ( File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/tablib/core.py", line 15, in <module> from tablib import formats File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/tablib/formats/__init__.py", line 12, in <module> from . import _xlsx as xlsx File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/tablib/formats/_xlsx.py", line 14, in <module> import openpyxl File "/Users/chandanvarma/Desktop/project/retailer-backend/venv/lib/python3.10/site-packages/openpyxl/__init__.py", line 6, in <module> from openpyxl.workbook import Workbook … -
django rest_framework error MultipleObjectsReturned get method return more than one
I making a project where everytime someone create an Item, in the ClearingOffice it will increment office_serial +1, but it's saying get() returned more than one ClearingOffice -- it returned 14! so when I try filter it increment all office_serials models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) userid = models.CharField(null=True, max_length=9) office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20, default=get_default_id) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' class ClearingOffice(models.Model): # this should be office_id office = models.OneToOneField('Office', models.DO_NOTHING, primary_key=True) staff = models.TextField(blank=True, null=True) office_serial = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'clearing_office' signals.py @receiver(post_save, sender=ClearanceItem) def create_transaction_log(sender, instance, created, **kwargs): if created: TransactionLog.objects.create(cl_itemid=ClearanceItem.objects.get(cl_itemid=instance.cl_itemid), trans_desc="Add Clearance Item", trans_recorded=str(datetime.now().strftime('%Y-%m-%d'))) ClearingOffice.objects.get(office_serial=instance.office.office_serial).update(office_serial=F('office_serial') + 1) the strange part is I have two users one of them is working currectly incrementing his office_serial while the other increments all of them can anyone explain why this is happening? Edit: I added the serializer.py class ClearanceItemSerialize(serializers.ModelSerializer): class Meta: model = ClearanceItem fields = '__all__' def … -
"invalid literal for int() with base 10:" error while changing DateTimeField to DateField in models.py | Django
I want to show how many posts are being made each day so i wrote this code: class ServerInsightsView(View): def get(self, request, server_tag): server = Server.objects.get(tag=server_tag) post_daily_count =server.posts.all().values('created').annotate(dailycount=Count('created')).order_by() #to get the number of posts each day depending on the DateTimeField return render(request, 'servers/insights.html', {'server':server, 'post_daily_count': post_daily_count}) This code is working but since created is a DateTimeField it groups the data depending on both date and time so for example (2022, 11, 15, 16, 24, 10, 577648) and (2022, 11, 15, 16, 40, 39, 224605) are in the same day but in different Time. so in order to fix this i've changed DateTimeField to DateField: Here is the models.py: class Post(models.Model): title = models.CharField(max_length=200) text = models.TextField(null=True, blank=True) saved = models.ManyToManyField(User, blank=True, related_name='saves') upvotes = models.ManyToManyField(User, blank=True, related_name='upvotes') downvotes = models.ManyToManyField(User, blank=True, related_name='downvotes') votes_count = models.IntegerField(default=0) server = models.ForeignKey(Server, on_delete=models.CASCADE, related_name='posts') creator = models.ForeignKey(User , on_delete=models.CASCADE, related_name='posts', null=True) created = models.DateField(auto_now_add=True) #was DateTimeField updated = models.DateField(auto_now=True) #was DateTimeField and now i get this error after this change: invalid literal for int() with base 10: b'15 16:24:10.577648' -
DJango displaying incorrect view
I am trying my best to learn Django for the past few days, and I came across an unusual problem. I know this is very basic form some, so I'm asking for your help on this one. I created two different views that will show two different outputs. from django.shortcuts import render from django.template import loader from django.http import HttpResponse # Create your views here. def computers(request): template_name = loader.get_template('computers/computers.html') context = { 'a':[ { 'sample1': 'WMCD0001', 'sample2': 'Desktop', 'sample3': 'Lenovo ThinkPad', 'sample4': '10.10.10.100', 'sample5': 'Active', }, ] } return HttpResponse(template_name.render(context, request)) def newdevice(request): return render(request, 'computers/newdevice.html') # return HttpResponse(template.render(request, context)) I also configured the urls file on the app which goes like this from django.urls import path from . import views urlpatterns = [ # path('', views.index, name='computers'), path('', views.computers, name='computers'), path('computers/newdevice/', views.newdevice, name='computers/newdevice') ] The last this I wrote was the urls in the project which is like this from django.contrib import admin from django.urls import include, path urlpatterns = [ path('computers/', include('computers.urls')), path('computers/newdevice/', include('computers.urls')), path('admin/', admin.site.urls), ] When I try to go to the localhost:8000/computers, it shows the correct view. The problem is when I try to view the page under localhost:8000/computers/newdevice it shows the same view … -
Multiple small API call vs single API call in Django Rest Framework
I have an application with user data associated with multiple models. All associated models need to be populated with certain data when a user is created. Should I create multiple APIs called at the same time from frontend or should I create a single API that does it all -
Handling notification Redirects to mobile apps and the frontend with Django Rest Framework
My project is in Django rest framework. It have web with react as well as android and ios. I am using Firebase push notification for notification purpose. Since I have to show my notification in app also, I have stored the notification in database and the notification database is as below: class Notification(models.Model): """ model to manage all notification """ receiver = models.UUIDField(max_length=255) title = models.CharField(max_length=255) body = models.TextField(blank=True, null=True) type = models.CharField(max_length=255) # order_type, registration_type is_read = models.BooleanField(default=False) redirect_url = models.CharField(max_length=255) Now the main problem I am facing is setting a redirect url for every notification. I want to redirect to specific page for different type of notification. For example for order_type notification i want to redirect user to order page, for comment_type notification I want to redirect user to comment page. How can I do that since i cannot just simply redirect to html url since there is react app, ios app as well as android app. I did not find much resource regarding this. Any help will be very much appreciated. Thanks. -
Does Django Headless CMS provide fronted Interface Templates?
I am new in Python/Django Framework and i want use CMS for my website so i can use fronted and admin ready-made templates. please suggest. -
Only Owner of the Profile able to Update the data
Using class Based (APIView) in Django rest framework for Getting and Patch (Updating) UserInfo data. views.py class getUserInfo(APIView): permission_classes = [permissions.IsAuthenticated] def get(self, request, format=None): user = request.user userinfos = user.userinfo_set.all() serializer = UserInfoSerializers(userinfos, many=True) return Response(serializer.data) def patch(self, request, pk, format=None): user = UserInfo.objects.get(id=pk) serializer = UserInfoSerializers(instance=user, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py from django.contrib.auth.models import User from .models import UserInfo class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first_name', 'username') class UserInfoSerializers(serializers.ModelSerializer): user = UserSerializer(many=False, required=True) class Meta: model = UserInfo fields = ('id', 'picture', 'profession', 'user') Everything is working so far so good. Able to GET and PATCH (Update) logged-in user data. While Testing the API in Postman, I found out that if User1 is logged in he can change the data of User2 by only using the pk of User2. urls.py urlpatterns = [ path('userinfo/', views.getUserInfo.as_view(), name="UserInfo"), path('userinfo/<str:pk>/', views.getUserInfo.as_view()), path('api/token/', views.MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('register/', views.RegisterView.as_view(), name='auth_register'), ] Using rest_framework_simplejwt for Auth models.py from django.contrib.auth.models import User class UserInfo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) picture = models.ImageField(upload_to="profile_pics", null=True) profession = models.CharField(max_length=200, null=True) def __str__(self): return "%s's Profile Picture" % self.user Any help would be appreciated -
How to compare two serializer field and show whichever is higher in django rest
I have product serializer which return category_offer_price & product_offer_price, before getting this response I want to compare both price and only return whichever is highest price. #Serilaizer.py class ProductSerializer(ModelSerializer): category = CategorySerializer() product_offer_price = SerializerMethodField() category_offer_price = SerializerMethodField() class Meta: model = Products fields = [ "id", "product_name", "slug", "category", "description", "category_offer_price", "product_offer_price", "base_price", "stock", "is_available", "created_date", "images", "images_two", "images_three", ] def get_product_offer_price(self, obj): try: product_offer = ProductOffer.objects.get(product=obj) if product_offer.is_active: offer_price = product_offer.product_offer_price() return offer_price except Exception: pass return None def get_category_offer_price(self, obj): try: category_offer = CategoryOffer.objects.get(category=obj.category) if category_offer.is_active: offer_price = category_offer.category_offer_price(obj) return offer_price except Exception: pass return None #Models.py class Products(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) product_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=100, unique=True) description = models.TextField(max_length=500) base_price = models.IntegerField() images = models.ImageField(upload_to="photos/products") images_two = models.ImageField(upload_to="photos/products") images_three = models.ImageField(upload_to="photos/products") stock = models.IntegerField() is_available = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Products" def __str__(self): return self.product_name I'd like to know is it possible to compare serializer fields in a serializer class? -
dfr TypeError: unsupported operand type(s) for +: 'Office' and 'str'
I'm trying to concatenate some fields ex. When I do this in postman { "sem": "2", "sy": "2021-2022", "remarks": "test", "resolution": "test", "studid": "2012-5037" } this is the customuser I made The cl_itemid shoud be OSA-2021-2022-2 class ClearanceItemSerialize(serializers.ModelSerializer): class Meta: model = ClearanceItem fields = '__all__' def create(self, validated_data): validated_data["office"] = self.context["request"].user.officeid validated_data["recorded_by"] = self.context["request"].user.userid validated_data["cl_itemid"] = self.context["request"].user.officeid + '-' + validated_data.get('sy') + '-' + validated_data.get('sem') return super().create(validated_data) above is the code but it's throwing me an error TypeError: unsupported operand type(s) for +: 'Office' and 'str' if I use userid instead validated_data["cl_itemid"] = self.context["request"].user.userid + '-' + validated_data.get('sy') + '-' + validated_data.get('sem') it's working 321-05 2021-2022-2 What's happening here can somebody explain? Edit: I added the models incase that's the problem class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20, default=get_default_id) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('Office', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) remarks = models.TextField(blank=True, null=True) -
django postgres different values
Hi Django + Postgresql While studying aware datetime, I had a question and asked a question. Postgresql document For timestamp with time zone, the internally stored value is always in UTC (Universal Coordinated Time, traditionally known as Greenwich Mean Time, GMT). An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone. If no time zone is stated in the input string, then it is assumed to be in the time zone indicated by the system's TimeZone parameter, and is converted to UTC using the offset for the timezone zone. Are you changing only the output differently according to the timezone setting value? (internally stored value is UTC ?) SET TIME ZONE 'KST' (Asia/Seoul +9) Why is the same query but different values? Django Settings TIME_ZONE = "Asia/Bangkok" # ( +7 ) USE_TZ = False Postgres Settings SET TIME ZONE 'KST' (Asia/Seoul +9) Django Server TimeZone UTC Django ORM Create Query INSERT INTO "timezone_timezone" ("datetime") VALUES ('2022-11-22T01:58:14.373201'::timestamp) RETURNING "timezone_timezone"."id"; args=(datetime.datetime(2022, 11, 22, 1, 58, 14, 373201),) psql select query psql insert Django ORM Query INSERT INTO "timezone_timezone" ("datetime") VALUES ('2022-11-22T01:58:14.373201'::timestamp) RETURNING "timezone_timezone"."id"; psql select query