Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I capture a picture from webcam and store it in a ImageField in Django?
I want to take a picture from a webcam and save it in ImageField. I've seen some results related to this question, but I'm not able to understand how they work. For example: How can I capture a picture from webcam and store it in a ImageField or FileField in Django? My HTML form <div class="contentarea"> <div class="Input"> <form method="POST" name="inputForm" enctype='multipart/form-data'> {% csrf_token %} <div id="camera" class="camera"> <video id="video">Video stream not available.</video> <button id="startbutton" type="button">Take photo</button> <input id="webimg" value="" name="src" type="text" style="display: none;"> <canvas id="canvas"> </canvas> </div> <br> <div> <img id="photo" alt="your image"> </div> <br> <button type="submit" class="btn btn-outline-warning" id="submit">Save</button> </form> </div> <img src="{{ path }}" alt="The screen capture will appear in this box."> Javascript (function() { var width = 320; var height = 0; var streaming = false; var video = null; var canvas = null; var photo = null; var startbutton = null; function startup() { video = document.getElementById('video'); canvas = document.getElementById('canvas'); photo = document.getElementById('photo'); startbutton = document.getElementById('startbutton'); navigator.mediaDevices.getUserMedia({video: true, audio: false}) .then(function(stream) { video.srcObject = stream; video.play(); }) .catch(function(err) { console.log("An error occurred: " + err); }); video.addEventListener('canplay', function(ev){ if (!streaming) { height = video.videoHeight / (video.videoWidth/width); if (isNaN(height)) { height = width / (4/3); } … -
How can I get my html to display my django model?
I'm trying to get my django model to be shown in the footer of my base.html but I can't get it to show up. I've looked at a few videos and I can't figure out where I'm going wrong. I know that the model works as I've made 4 entries in my database and I can view them on the admin page. The code also doesn't show any errors so I have nothing to go off of there. Here it is: Models.py class SocialMediaPlatform(models.Model): name = models.CharField(max_length=50, blank=True, null=True) font_awesome_class = models.CharField(max_length=50, blank=True, null=True) base_url = models.CharField(max_length=50, blank=True, null=True, default='https://instagram.com/ or https://tiktok.com/@') def __str__(self): return self.base_url Views.py def social_media_base_view(request): context = {} smbase = SocialMediaPlatform.objects.all() context['smbase'] = smbase return render(request, 'index.html', context) Urls.py urlpatterns = [ path('', views.social_media_base_view), ] Admin.py @admin.register(SocialMediaPlatform) class SocialPlatformAdmin(admin.ModelAdmin): list_display = ('name', 'font_awesome_class', 'base_url') base.html {% for smlink in smbase %} <a href="{{ smlink.SocialMediaPlatform.name }}"> <i class="{{ smlink.SocialMediaPlatform.font_awesome_class }}"> </a> {% endfor %} -
How can I see how many child-tasks a pool worker is currently executing?
I'm using Celery in Django and the workers are eating up all of the memory of my Dynos in Heroku. Setting the --max-tasks-per-child seems to be a valid solution but I can't seem to find what the ramifications of setting a low number might be. So, I wanted to know if it's possible to either monitor the amount of child-tasks a worker is currently running or log this data somewhere. -
Unable to setup mysql with Django on Mac
I installed the recent version of MySQL for my mac (macOS 12(ARM, 64-bit), DMG Archive) and created a database called storefront. I'm working in a pipenv virtual environment and install mysqlclient. I've also updated my DATABASES settings to point to my new database in my settings.py file. DB Settings. But whenever I try to run the server I get an error. NameError: name '_mysql' is not defined Also at the top, (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e') I thought by installing the ARM version I wouldn't deal with this error. I wonder if it's pointing to the wrong file within my env despite adding the PATH to my .zshrc info. Is there a special way to point to the correct mysql or am I setting things up incorrectly? Here's my error message " Traceback (most recent call last): File "/Users/a0c08w6/.local/share/virtualenvs/storefront-A2x2yZd3/lib/python3.9/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/a0c08w6/.local/share/virtualenvs/storefront-A2x2yZd3/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so, 0x0002): tried: '/Users/a0c08w6/.local/share/virtualenvs/storefront-A2x2yZd3/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e')) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/a0c08w6/Documents/Scripts/Django/storefront/manage.py", line 22, in <module> main() File "/Users/a0c08w6/Documents/Scripts/Django/storefront/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/a0c08w6/.local/share/virtualenvs/storefront-A2x2yZd3/lib/python3.9/site-packages/django/core/management/__init__.py", line … -
Django Trigram Similarity for list of strings in Postgres
I have a list of names ["May", "Brown", "Chaplin", etc...] containing about 200 names. For each name string I want return a corresponding object from the database using Django TrigramSimilarity. Normally I would do something like this: result = [] for surname in surnames: person = Person.objects.annotate( similarity=TrigramSimilarity("surname", surname) ) .filter(similarity__gt=0.3) .order_by("-similarity").first() if person: result.append(person) but executing 200 queries in a row doesn't seem very optimal. Is there a way to create a single query for this operation? Also what are the ways to optimize this task even more? Here is my Django model: class Person(models.Model): name = models.Charfield(max_length=100) surname = models.Charfield(max_length=100) age = models.IntegerField() etc... -
how can i prevent access to streamlit outside of django?
I have django and Streamlit running independently, but with an Iframe I can access streamlit by placing the ip inside a template, from django. The question is... How can I prevent access to streamlit by placing the ip directly in the browser. so that it is only see through django. Any help would be greatly appreciated -
Why do I get the path error to view the contents of a single email in the below code.?
In the inbox.js file I am trying to listen for a click event for each email single_email_div and send it to the email view in views.py inbox.js function load_mailbox(mailbox) { // Show the mailbox and hide other views document.querySelector("#emails-view").style.display = "block"; document.querySelector("#compose-view").style.display = "none"; // Show the mailbox name document.querySelector("#emails-view").innerHTML = `<h3>${ mailbox.charAt(0).toUpperCase() + mailbox.slice(1) }</h3>`; // Show the emails of that particular mailbox fetch(`/emails/${mailbox}`) .then(response => response.json()) .then(emails => { // Print emails console.log(emails); // ... do something else with emails ... emails.forEach(email => { const single_email_div = document.createElement('div'); single_email_div.innerHTML = `<a href="{%url 'email' email.id %}"> <br> ${email.id} <br> From: ${email.sender} <br> Subject: ${email.subject} <br> TimeStamp: ${email.timestamp} <br> Read: ${email.read} <br><br> </a>` if(`${email.read}` === false) {single_email_div.style.backgroundColor = "white";} else {single_email_div.style.backgroundColor = "grey";} const emails_div = document.querySelector('#emails-view'); emails_div.append(single_email_div); // When a user clicks on an email, the user should be taken to a view where they see the content of that email document.querySelector("single_email_div").addEventListener('click', () => { fetch(`/emails/${id}`) .then(response => response.json()) .then(email => { // show email and hide other views document.querySelector("#emails-view").style.display = "none"; document.querySelector("#compose-view").style.display = "none"; document.querySelector("#email-view").style.display = "block"; // display email const view = document.querySelector("#email-view"); view.innerHTML = `<ul> <li> From: ${email.sender} </li> <li> To: ${email.recipients} </li> <li> Subject: ${email.subject} … -
Django Jinja2 variables in CSS occur red highlights in VSCode
I'm using Visual Studio Code. And I liked it. But when I use jinja in css or javascript, VSC always highlited in red. How can I fix it? It's sometimes annoying. I'm using Better Jinja plugin. -
DRF- how to return field which is not included in model in response
I have view: class SomeView(APIView): def get(self,request): serializer = serializers.SomeViewSerializer return Response({'result_url': ???}) and serializer: class SomeViewSerializer(serializers.Serializer): url = serializers.SerializerMethodField() def get_url(self): res_id = genetare_url(self.id) return res_id in this case url is not part of any model, but I want to return only this (result of get_url) in response, but I couldn't figure out how to write it in view above. any help will be appriciated, thank you -
How to validate the fields by combining lambda and regx?
I want to get a username and password from the user, which should be validated as a function as follows Terms and conditions for input: Password length greater than or equal to 6. Username length greater than or equal to 4. No one is allowed to join with 'test' and 'codecup' usernames. A user whose password consists only of numbers is not allowed to join. def check_registration_rules(**kwargs): li = list() for user,passwd in kwargs.items(): # print(passwd) # print(user) if user == 'test' or user == 'codecup': continue elif len(user) < 4: continue elif str(passwd).isdigit(): continue elif len(passwd) < 6: continue else: li.append(user) return li print(check_registration_rules(username='p', sadegh='He3@lsa')) Now, instead of these nested conditions, I want to use a combination of lambda and regex library -
AttributeError: 'function' object has no attribute 'as_view'
when i am trying to implement class view it showing the below error Thanks in Advance views.py---- - from re import template import django from django.shortcuts import render from django.views.generic import ListView from .models import Post def PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] urls.py----- - from django.urls import path from .views import PostListView from . import views urlpatterns = [ path('', PostListView.as_view(),name="blog-home"), path('about/', views.about,name="blog-about"), ] error------ - return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/kundan/Documents/CodeHub/Python Framework/DjangoWeb/blogspot/blog/urls.py", line 7, in <module> path('', PostListView.as_view(),name="blog-home"), AttributeError: 'function' object has no attribute 'as_view' -
Is it possible to manually change ID value of primary key in Django Model through serializers?
Is it somehow possible to manually change ID value in AutoField (primary key) through serializer? I found this in documentation of Django: https://docs.djangoproject.com/en/4.0/ref/models/instances/#auto-incrementing-primary-keys, but I have no idea how to do this including serializers. My task is: If post with given ID does not exists, fetch post from external API and save it. Model: from django.db import models class Post(models.Model): id = models.AutoField(primary_key=True) user_id = models.IntegerField(default=1) title = models.CharField(max_length=200) body = models.CharField(max_length=500) My serializer: from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['id', 'user_id', 'title', 'body'] My view: @api_view(['GET', 'PUT', 'DELETE']) def post_detail_id(request, id): try: post = Post.objects.get(pk=id) except Post.DoesNotExist: #-----------------------------------------------------------# found_post = search_post(id) #fetch post from external API if request.method == "GET" and found_post is not None: serializer = PostSerializer(data=found_post) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_201_CREATED) #-----------------------------------------------------------# return Response(status=status.HTTP_404_NOT_FOUND) return post_detail(request, "id", post) #method to handle CRUD Post structure: { "user_id": 1, "id": 1, "title": "Blabla", "body": "Lorem Ipsum" }, This implementation fetch post with given ID from API, then saves it, but with different ID. Are there any better ways to do this? Let me know below! -
Can't figure out problem with Django forms
I want to create a custom form in Django, but I keep getting an error with error_messages option. I'm not sure what is wrong. from django import forms class ReviewForm(forms.Form): user_name = forms.CharField(label="Your Name", max_length=100, error_messages={ "required": "Your name must not be empty!", "max_length": "Please, enter a shorter name!" }) The error message messages.update(error_messages or {}) ValueError: dictionary update sequence element #0 has length 0; 2 is required -
How can I add two complex statements in a correct way for queryset.filter in Django?
I am filtering my Article viewset on Django. The code below works fine, from django.contrib.auth.models import User from rest_framework.authtoken.models import Token from rest_framework import serializers, viewsets,filters from rest_framework.permissions import IsAuthenticated from rest_framework import generics from url_filter.integrations.drf import DjangoFilterBackend class ArticleFilterBackEnd(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter( article__author__followers__author=request.user ) But I also want to use queryset.exclude() inside the same loop and filter where article__author__followers__issilent= True when statement is in same loop with request.user so it does not point out to any other followers loop. How can I do it? -
get true file url after user uploads in django
here is the problem. in my project user is going to upload an excel file and right after that the app must take it and read it using pandas. file is uploaded in media/projects/%Y/%m/%d/: views.py: if request.method == 'POST' and request.FILES['createdatabase']: user = request.user data = request.FILES['createdatabase'] new = NewProject( user=user, data=data, ) new.save() models.py: from django.db import models from django.contrib.auth.models import User class NewProject(models.Model): user = models.ForeignKey(User, on_delete=models.DO_NOTHING) data = models.FileField(blank=True, upload_to='projects/%Y/%m/%d/') u = models.TextField(blank=True) v = models.TextField(blank=True) w = models.TextField(blank=True) u, v, and w are in the data file that the user uploads and the app must read it. when I want to read the file in pandas using the read_excel() method, it needs the file URL. using data.url or data.path does not work seems it just says the file name or the wrong path media/datafilename.xlsx. the true file URL must be something like media/2022/07/01/datafilename.xlsx. also, some files might have the same names that are uploaded by the users. so the Django just adds a random string to it. but data.url and data.path print the main name of the file. not the changed one. any help will be appreciated. -
Django channels websocket ValueError: No route found for path 'ws//'
I am currently trying to make a chat application using the Django channel tutorial as a base for the project. I am currently having a problem in which the WebSocket is disconnecting and Handshaking. I am new to Django and WebSocket. chat/routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ] chat/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:room_name>/', views.room, name='room'), ] mysite/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('chat.urls')), path('admin/', admin.site.urls), path("auth/", include("django.contrib.auth.urls")), ] chat/consumers.py import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import Room, Message class ChatConsumer(WebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.room_name = None self.room_group_name = None self.room = None self.user = None def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = self.room_name self.room = Room.objects.get(name=self.room_name) self.user = self.scope['user'] # connection has to be accepted self.accept() # join the room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name, ) if self.user.is_authenticated: # send the join event to the room async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'user_join', 'user': self.user.username, } ) self.room.online.add(self.user) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name, ) if self.user.is_authenticated: # send the leave event to the room async_to_sync(self.channel_layer.group_send)( self.room_group_name, … -
How to make docker-compoe ".env" file take precedence over shell env vars?
I would like my docker-compose.yml file to use the ".env" file in the same directory as the "docker-compose.yml" file to set some envrionment variables and for those to take precedence for any other env vars set in the shell. Right now I have $ echo $DB_USER tommyboy and in my .env file I have $ cat .env DB_NAME=directory_data DB_USER=myuser DB_PASS=mypass DB_SERVICE=postgres DB_PORT=5432 I have this in my docker-compose.yml file ... version: '3' services: postgres: image: postgres:10.5 ports: - 5105:5432 environment: POSTGRES_DB: directory_data POSTGRES_USER: ${DB_USER} POSTGRES_PASSWORD: password web: restart: always build: ./web ports: # to access the container from outside - "8000:8000" environment: DEBUG: 'true' SERVICE_CREDS_JSON_FILE: '/my-app/credentials.json' DB_SERVICE: host.docker.internal DB_NAME: directory_data DB_USER: ${DB_USER} DB_PASS: password DB_PORT: 5432 command: /usr/local/bin/gunicorn directory.wsgi:application --reload -w 2 -b :8000 volumes: - ./web/:/app depends_on: - postgres In my Python 3/Django 3 project, I have this in my application's settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ['DB_NAME'], 'USER': os.environ['DB_USER'], 'PASSWORD': os.environ['DB_PASS'], 'HOST': os.environ['DB_SERVICE'], 'PORT': os.environ['DB_PORT'] } } However when I run my project, using "docker-compose up", I see maps-web-1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection maps-web-1 | connection = Database.connect(**conn_params) maps-web-1 | File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 127, in connect maps-web-1 | conn = _connect(dsn, … -
How do I run an existing Django file?
I downloaded a folder with multiple python files in the form of a Django project for a course and I am unable to run it. Usually, when you create a Django project it is created within the terminal with the line django-admin startproject web_project . and then python manage.py migrate is used and then the line python manage.py runserver to start a server. How do I start a server to run my project? When I use django-admin startproject web_project ., it creates a new project which I don't want. When I use python manage.py migrate or python manage.py runserver it says: Command 'python' not found, did you mean: command 'python3' from deb python3 command 'python' from deb python-is-python3 But even when I used python3 manage.py migrate or python3 manage.py runserver instead and it returned: python3: can't open file 'manage.py': [Errno 2] No such file or directory -
twilio call back status
hello I am doing an app which users can call some numbers anyway this is the idea, I want to know how can I take the status of this calls to make changes in my template such as 'complated or not completed' I am using django 'python' this is my views def callsender(request): phoneNumber = request.GET['phone'] if not phoneNumber: msg = 'Missing phone number value' return JsonResponse({'error': msg}) try: account_sid = settings.TWILIO_ACCOUNT_SID auth_token = settings.TWILIO_AUTH_TOKEN client = Client(account_sid, auth_token) except Exception as e: msg = 'Missing configuration variable: {0}'.format(e) return JsonResponse({'error': msg}) try: call = client.calls.create( # twiml='<Response><Say>Ahoy, Wake up!</Say><Play>https://demo.twilio.com/docs/classic.mp3</Play></Response>', # url='http://demo.twilio.com/docs/classic.mp3', to=phoneNumber, from_=settings.TWILIO_NUMBER, url='http://127.0.0.1/voice', status_callback = 'https://crimson-cod-9776.twil.io/status_callback', status_callback_method='POST', status_callback_event=['initiated','ringing','answered','completed'], ) except Exception as e: message = e.msg if hasattr(e, 'msg') else str(e) return JsonResponse({'error': message}) print(call.sid) return JsonResponse({'message': 'Call incoming!'}) the function I have created wouldn't help on anything, the idea is like this after the people answered my app users I want to write completed instead of the button 'call constumer' -
No Django POST data when sent over a form?
I am on a development server (no CSRF protection), sending over login data to Django via a web form (Django: 127.0.0.1:8000). HTML: <!DOCTYPE html> <html> <head> <title>Log In</title> <meta charset="utf-8"> </head> <body> <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script> <header> </header> <script> $("document").ready(function () { $("header").load("static/header.html"); }) </script> <div id="loginbox"> <h3>Log In</h3> <form action="http://127.0.0.1:8000" method="post"> <input type="text" id="uname"><br> <input type="password" id="pass"><br> <button id="login" type="submit">Log In</button></br> </form> <a href="signup.html">Sign Up</a><br> <a href="forgotCredentials.html">Forgot Username/Password?</a> </div> </body> </html> Django: from django.shortcuts import render # Create your views here. from django.contrib.auth import authenticate, login from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse @csrf_exempt def index(request): uname = request.POST.get("uname") passwd = request.POST.get("pass") print(uname + " pass " + passwd) user = authenticate(username=uname, password=passwd) if user is not None: login(request, user) return render(request, "taxnow/index.html") return render(request, "taxnow/Login.html") I'm pretty sure that the POST data is not being transmitted (TypeError: unsupported operand type(s) for +: 'NoneType' and 'str') in the print statement, but I can't figure out why. (The HTML is on localhost and the django is on 127.0.0.1:8000 as mentioned previously.) Is there any reason for this? -
how can integrate voice calls in django rest framework
I know about Twillio, but it is not free There is some open source SI servers like FreeSWITCH, Kamailio, OpenSIPS but I'm quite confused how integrate it in django (there is a android app with backend on drf with possibility of voice calls in it) -
Django navlink URL are not working and receiving no error
enter image description here I have used django URL on navlink for some reasons unable to click on them and there is no error returning just nothing is happening. <nav class="main-nav"> <!-- ***** Logo Start ***** --> <a href={% url 'home_page' %} class="logo"> <img src={% static "assets/images/templatemo-eduwell.png" %} alt="EduWellTemplate"> </a> <!-- ***** Logo End ***** --> <!-- ***** Menu Start ***** --> <ul class="nav"> <li class="scroll-to-section"><a href={% url 'home_page' %} class="active">Home</a></li> <li class="scroll-to-section"><a href={% url 'services' %}>Services</a></li> <li class="scroll-to-section"><a href={% url 'contact_us' %}>Contact Us</a></li> <li class="scroll-to-section"><a href={% url 'home_page' %}>Login</a></li> <li class="scroll-to-section"><a href={% url 'home_page' %}>Buy now</a></li> </ul> <a class='menu-trigger'> <span>Menu</span> </a> <!-- ***** Menu End ***** --> </nav> urlpatterns = [ path('admin/', admin.site.urls), path('', views.home_page, name='home_page'), path('about-us/', views.about_us, name='about_us'), path('contact-us/', views.contact_us, name='contact_us'), path('services/', views.our_services, name='services') ] -
React i18next fails to load translation after in build
I don't know why react i18next display loading namespace fails on the debug console. I tried many suggestions without success. I'm using the react build folder inside Django project. It works fine on localhost:3000 only which is crazy but once i try to use the build folder I get the above error on the debug console i18n.js : import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; import Backend from 'i18next-http-backend'; import LanguageDetector from 'i18next-browser-languagedetector'; // don't want to use this? // have a look at the Quick start guide // for passing in lng and translations on init const Languages = ['ar', 'en', 'fr'] i18n .use(Backend) .use(LanguageDetector) .use(initReactI18next) // passes i18n down to react-i18next .init({ lng: 'en', react: { useSuspense: true, }, // the translations // (tip move them in a JSON file and import them, // or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui) supported: ["en", "fr", "ar"], fallbackLng: "en", detection: { order: ['path', 'cookie', 'htmlTag', 'localStorage', 'subdomain'], caches: ['cookie'], }, debug: true, whitelist: Languages, interpolation: { escapeValue: false, // not needed for react as it escapes by default }, nsSeperator: false, keySeperator: false, backend: { loadPath: '/locales/{{lng}}/{{ns}}.json', }, }); export default i18n; index.js : import … -
Why does Django ORM do operations on my timestamp field even if I didn't setup TIME_ZONE and USE_TZ in my settings.py
Django ORM seems to be converting my timestamp in a weird way and I'm not sure why. Currently, our app doesn't have the settings TIME_ZONE and USE_TZ. There wasn't any need so far so we didn't use it. Now, I'm trying to show some specific timestamp details while we don't have the settings mentioned above The insert to the database (postgresql) works ok. the field that I'm using is timestamp with time zone. The timezone set in my local DB is "Asia/Singapore" db value is: "2022-07-01 23:09:14.253877+08" which is correct. Now, if I try to retrieve this value, what I get from the Django object is: 2022-07-01 10:09:14.253877. which is totally of and not even close to UTC. The timestamp value got converted to a different timezone (like for MST which is -7 from UTC). But it's actually not following any pattern since I also had some test data added at 1:11:00PM but the stamp retrieved from the Django ORM is 00:11:28.848820 To summarize, my question is how does Django ORM treat a timestamp value if TIME_ZONE and USE_TZ settings are not configured. I was naive to expect that it will retrieve the value as is from the database but … -
Django Rest Framework"detail": "Method \"GET\" not allowed."
I;m trying to build api by using django rest framework but I got the issue. @api_view(['PUT', ]) def api_update_blog_view(request, title): try: post = Post.objects.get(title=title) except Post.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'PUT': serializer = PostSerializer(post, data=request.data) data = {} if serializer.is_valid(): serializer.save() data["success"] = "update successful" return Response (data=data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urlpatterns = [ path('<str:title>/update', api_update_blog_view, name="update"), ] When I'm trying to update post I can see "detail": "Method "GET" not allowed." error. Where is the issue ?