Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What framework should I learn for backend [closed]
What framework should I learn for backend in 2024? I have tried Django and Laravel I just do not know witch one is better to get a job these times and I am going with react too so I see a lot of people use node js but I just know it is no good in my country to learn int. that is why I am going with these two frameworks ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, do not read the next lines : it is just nothing so that stack overflow tkae my qustion it said 220 but i just do nt know why it still do not want to send this qustion to you all man come onnnnnnnnnnnnnnnnnnnn it is my first time on this website and I am thinking of going back to chat gpt 3 not even 4 if u do not allow this man come on -
ModuleNotFoundError: No module named '_sqlite3' trying to connect with sqlalchmey and pandas
I am using Python version 3.10. I'm attempting to connect a MySQL database to SQLalchemy and Pandas. The local environment is working fine. But when I deployed in Ubuntu, I got ModuleNotFoundError: No module named '_sqlite3'. Note:- But I tried to connect with Django Orm with Ubuntu, which was also working as expected. the only problem with sqlalchemy and Pandas. from sqlalchemy import create_engine import pandas as pd engine = create_engine(url,echo=False) ## en conn = engine.connect() df = pd.read_sql_query('SELECT * FROM role_master', con=engine) Need solution to fix this issue. -
How to convert a synchronous view to async view in Django
I'm working on a django view to get list of available riders. I first created in a synchronous context and when I tested it, it worked as expected. I need it to be in an asynchronous context, but when I tried to convert i to an async context, I get this error message below: raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Here's the code in an async context I came up with trying to convert to an async context, but got the error above: riderexpert_db = firestore.AsyncClient(project="riderexpert", database="riderexpert-db") class GetAvailableRidersView(APIView): permission_classes = [IsAuthenticated] SEARCH_RADIUS_METERS = 10 async def get_google_maps_client(self): """Initialize and return the asynchronous Google Maps API client.""" return GoogleMapsClient(key=settings.GOOGLE_MAPS_API_KEY) async def validate_parameters(self, order_location, item_capacity, is_fragile): """Validate input parameters.""" try: item_capacity = float(item_capacity) is_fragile = str_to_bool(is_fragile) except (ValueError, TypeError): return False, "Invalid or missing parameters" if not all( [ order_location is not None and isinstance(order_location, str), item_capacity is not None and isinstance(item_capacity, (int, float)), is_fragile is not None and isinstance(is_fragile, bool), ] ): return False, "Invalid or missing parameters" return True, "" def handle_google_maps_api_error(self, e): """Handle Google Maps API errors.""" return Response( {"status": "error", "message": f"Google Maps API error: {str(e)}"}, … -
Token is automatically changing on every request
I get access and refresh token after logging in by following code. class Employee_Login(APIView): permission_classes=[AllowAny] employee_login_data = serializers.employee_login_serializer def post(self,request): try: employee_data = self.employee_login_data(data=request.data) employee_data.is_valid(raise_exception=True) data = employee_data.validated_data employee = authenticate(request,email=data.get('email'), password= data.get('password')) if not employee: return Http404("Employee not found") if not employee.is_verified: raise ForbiddenException("Employee is not verified") payloads = { "user": "admin" if employee.is_admin and employee.is_verified and employee.is_staff else "staff" if employee.is_staff and employee.is_verified else "" } employee_detail = { "name":employee.name, "email":employee.email, "type":"admin" if employee.is_admin and employee.is_staff and employee.is_verified else "staff" if employee.is_admin and employee.is_verified else "" } refresh = RefreshToken.for_user(employee) refresh.payload.update(payloads) acess_token = str(refresh.access_token) refresh_token = str(refresh) return Response({"success":True, "data":employee_detail, "token":{"access":acess_token,"refresh":refresh_token}}) except Exception as e: return Response({"success":False,"message":str(e)}) The problem is, when I use the access token obtained from above code in below custom permission class class AdminPermission(permissions.BasePermission): def has_permission(self, request, view): print("Here",AccessToken(request.auth).payload) STAFF_METHODS = ['GET','POST','PATCH'] USER_METHODS = ['GET'] if request.method in USER_METHODS: return True print(AccessToken(request.auth)) if request.user.is_authenticated: if request.user.is_admin and request.user.is_staff and request.user.is_verified: return True if not request.user.is_admin and request.user.is_staff and request.user.is_verified and request.method in STAFF_METHODS: return True return False The print(AccessToken(request.auth)) is printing different token than the token that I passed from request. And it is printing different things in every request. I am frustrated by this … -
Unable to create a google meet link in Django
I am getting credentials from the service account. SCOPES = ['https://www.googleapis.com/auth/calendar','https://www.googleapis.com/auth/calendar.events'] credentials = Credentials.from_service_account_file(path , scopes=SCOPES) To generate the meet link here's my body code event = { "end": { "dateTime": "2023-12-29T11:00:00", "timeZone": "UTC" }, "start": { "dateTime": "2023-12-29T10:00:00", "timeZone": "UTC" }, "conferenceData": {"createRequest": {"requestId": "sample123", "conferenceSolutionKey": {"type": "hangoutsMeet"}}}, } event_response = service.events().insert(calendarId=calendarId, body=event,conferenceDataVersion=1).execute() I am getting the error:- returned "Invalid conference type value.". Details: "[{'domain': 'global', 'reason': 'invalid', 'message': 'Invalid conference type value.'}]"> -
Locking a row for the duration of the inner transaction
Consider: with transaction.atomic(): ... with transaction.atomic(): row = MyModel.objects.select_for_update().get(...) ... # I need the lock on the row to be released here ... # It is actually released here, which is not what I need As this article puts it: In many database engines, such as PostgreSQL, there’s no such thing as a nested transaction. So instead Django implements this using a single outer transaction. I have confirmed that the lock is released only when the outer transaction ends. How can I achieve the effect explained in the comments in the above code block, i.e. that a row locked in the inner transaction become released upon the completion of that transaction? -
Payload is missing from jwt token in djanog
I'm setting updating payload of token by following way. payloads = { "user": "admin" if employee.is_admin and employee.is_verified and employee.is_staff else "staff" if employee.is_staff and employee.is_verified else "" } refresh = RefreshToken.for_user(employee) refresh.payload.update(payloads) acess_token = str(refresh.access_token) refresh_token = str(refresh) And when I print the payloads of token by print(refresh.access_token.payload) it is showing {'token_type': 'access', 'exp': 1703799022, 'iat': 1703763022, 'jti': '7b09308f00194f149cadd7ec6f1728cc', 'user_id': 3, 'user': 'admin'} I have set custom permission class as follows class AdminPermission(permissions.BasePermission): def has_permission(self, request, view): print(AccessToken(request.auth).payload) STAFF_METHODS = ['GET','POST','PATCH'] USER_METHODS = ['GET'] if request.method in USER_METHODS: return True print(request.user) if request.user.is_authenticated: if request.user.is_admin and request.user.is_staff and request.user.is_verified: return True if not request.user.is_admin and request.user.is_staff and request.user.is_verified and request.method in STAFF_METHODS: return True return False When this permission class is called print(AccessToken(request.auth).payload) is printing only {'token_type': 'access', 'exp': 1703799137, 'iat': 1703763137, 'jti': '402403953a4d4810b3d453385d005330'}. user_id and user field is missing from the token. I don't know where I went wrong. I have been stucked in this from several hours. How can I solve this? Please help. I'm passing Bearer token -
multi-tenant with multiple database
I am trying to create database per tenant automatically and also trying to do makemigrations and migrant automatically but this error comes, give me solution of it: ProgrammingError at /account/register/ relation "account_user" does not exist LINE 1: SELECT 1 AS "a" FROM "account_user" WHERE "account_user"."us... POV: I am uisng DRF, Postgresql -
My static files are not loading due to permission denied?
ubuntu@ip-172-26-13-151:~$ sudo tail /var/log/nginx/error.log 2023/12/28 05:14:20 [error] 17570#17570: *14 open() "/home/ubuntu/Donor/static/assets/plugins/slick-carousel/slick/slick.css" failed (13: Permission denied), client: 182.191.136.55, server: 44.222.2.190, request: "GET /static/assets/plugins/slick-carousel/slick/slick.css HTTP/1.1", host: "44.222.2.190", referrer: "http://44.222.2.190/" 2023/12/28 05:14:21 [error] 17570#17570: *12 open() "/home/ubuntu/Donor/static/assets/plugins/slick-carousel/slick/slick.min.js" failed (13: Permission denied), client: 182.191.130.7, server: 44.222.2.190, request: "GET /static/assets/plugins/slick-carousel/slick/slick.min.js HTTP/1.1", host: "44.222.2.190", referrer: "http://44.222.2.190/" 2023/12/28 05:14:21 [error] 17570#17570: *13 open() "/home/ubuntu/Donor/static/assets/plugins/bootstrap/bootstrap.min.js" failed (13: Permission denied), client: 182.191.130.7, server: 44.222.2.190, request: "GET /static/assets/plugins/bootstrap/bootstrap.min.js HTTP/1.1", host: "44.222.2.190", referrer: "http://44.222.2.190/" This is the error how could I solve this I am using Nginx and Gunicorn for deploying my django app. -
How to customize the default Token invalid json response in django for JWTAuthentication
In my django rest app i like to change the default error response from JWTAuthentication. Currently my application is using JWT With django to work on login and logout (which blacklists the token). Below is my code. settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } account app views.py from rest_framework.views import APIView from rest_framework_simplejwt.tokens import RefreshToken, BlacklistMixin class BlacklistRefreshTokenView(APIView, BlacklistMixin): def post(self, request): token = RefreshToken(request.data.get('token')) token.blacklist() # return Response({'message': 'Token blacklisted successfully.'}) return json_response('Logout successful', None, 200) class CustomTokenObtainPairView(TokenObtainPairView): def post(self, request, *args, **kwargs): # Call the base class's post method to continue with the login process response = super().post(request, *args, **kwargs) return response urls.py from django.urls import path from .views import CustomTokenObtainPairView, BlacklistRefreshTokenView urlpatterns = [ path('login/', CustomTokenObtainPairView.as_view(), name="login"), path('logout/', BlacklistRefreshTokenView.as_view(), name='blacklist_token'), ] response im getting when token is invalid { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } expected response { "message": "Given token not valid for any token type", "status": "401" } -
Nginx returns 502 errors with Gunicorn/Daphne with bursts connections
Kubernetes deployment contains 2 containers: Django application with Daphne, binded on Unix socket Nginx is in front of it as reverse proxy UDS is shared as volume between app and Nginx container, Memory type. Configuration works as expected except when there are burst in connections, eg, when pod is restarted and all connections from killed pod are spreaded to remaining pods. When connections are being terminated, we can observe HTTP 502 errors that upstream server is not available on /var/run/daphne.sock. It lasts for some period, usually up to 20 seconds and it starts working again. If we switch to TCP port instead of UDS, it works slightly better, but 502 errors are still present. Nginx config: worker_processes 1; user nobody nogroup; error_log /var/log/nginx/error.log warn; pid /tmp/nginx.pid; events { worker_connections 16384; } http { include mime.types; # fallback in case we can't determine a type default_type application/octet-stream; sendfile on; access_log off; upstream ws_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response # for UNIX domain socket setups server unix:/var/run/daphne.sock fail_timeout=0; } server { listen 8443 ssl reuseport; ssl_certificate /etc/nginx/ssl/TLS_CRT; ssl_certificate_key /etc/nginx/ssl/TLS_KEY; ssl_client_certificate /etc/nginx/ssl/CA_CRT; ssl_protocols TLSv1.2 TLSv1.3; client_max_body_size 5M; client_body_buffer_size … -
How to make a form that can add an unlimited amount of elements
I'm trying to make my schools web-site for students. In this site i want to allow them create project page. In project page I want to allow them to upload unlimited number of files that can be dowloaded by other users. Image from template How I can do that from django.db import models from django.contrib.auth.models import User import uuid from phonenumber_field.modelfields import PhoneNumberField class News(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, editable = False) name = models.CharField(max_length=50) description = models.TextField(null=True, blank=True) images = models.ImageField(upload_to='media/', default=None, null=True, blank=True) face_image = models.ImageField() created = models.DateTimeField(auto_now_add=True) text = models.TextField() id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False) class Meta: ordering = ["-created"] class profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,) profile_image = models.ImageField(upload_to='profileimages/', default=None, null=True, blank=True) bio = models.CharField(null=True, blank=True, max_length=130) Date_of_birth = models.DateField(null=True, blank=True) phone_number = PhoneNumberField(null=True, blank=True, region="UZ") job = models.CharField(null=True, blank= True, max_length=50) id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False) about = models.TextField(null=True, blank=True) # Create your models here. class Skills(models.Model): skills = models.CharField(max_length=30) user = models.ForeignKey(User, on_delete=models.CASCADE) class Project(models.Model): host = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField() category = models.CharField(null=True, blank=True, max_length=20) cost = models.CharField(null=True, blank=True, default="0.0$", max_length=10) profit = models.CharField(null=True, blank=True, default="Non-profit", max_length = … -
Custom Filtering Based on Published Posts (In Django admin)
I'm working on a training project for a social network where users can post their recipes. I want to add the ability to filter users in Django admin based on whether they have published recipes or not. My filter class is: class UserHasRecipeFilter(admin.SimpleListFilter): title = _('Posted recipes') parameter_name = 'posted_recipes' def lookups(self, request, model_admin): return ( ('yes', _('Yes')), ('no', _('No')), ) def queryset(self, request, queryset): if self.value() == 'yes': return queryset.annotate(recipes_count=Count('recipes')).filter(recipes_count__gt=0) elif self.value() == 'no': return queryset.annotate(recipes_count=Count('recipes')).filter(recipes_count=0) Custom filter is added: @admin.register(UserProfile) class UserAdmin(UserAdmin): list_filter = ('is_active', 'UserHasRecipeFilter’,) But when I try to run make migrations, It is failing with an following error : ERRORS: <class 'recipes.admin.UserAdmin'>: (admin.E116) The value of 'list_filter[2]' refers to 'UserHasRecipeFilter', which does not refer to a Field. Please advise where I made a mistake.. -
Applying Additional Styles to Inherited Django Templates with Jinja Templating
In my Django project, I've set up a base HTML template (base.html) with a set of CSS styles. This base template is inherited by several other templates across my project. The challenge I'm facing is that some of these inherited templates require additional styles that are specific to each template. While I attempted to include all styles in base.html, I found that it doesn't work seamlessly for templates with unique styling needs. What is the recommended approach for applying additional styles to individual templates while still leveraging the common styles defined in base.html? Are there best practices or Django conventions for managing such scenarios effectively? I appreciate any insights or suggestions on how to structure my templates and styles to achieve a cohesive design across the project. I initially attempted to consolidate all styles within the base.html file, expecting them to seamlessly apply to all templates. However, this approach didn't work as intended. The additional styles for individual templates were not being applied correctly. -
Generating python code and adding it to python files
**What I am trying to do is? ** I want to generate crud APIs based on the models and add them to the views.py file. What is the best way to do so? I know I can just simply append strings in a file but somebody knows some library that can help me do things like these in a more manageable way. As I can see the same name view exists so I can replace that class only instead of just blindly appending strings I tried appending strings in the view file but it is not efficient enough for my use case. -
I am unable to load data from my custom package's database in to my running project(project is running in docker), it shows me following error
I have a custom package name "xyz", i installed it in my project running in docker, but its unable to load data from databse of package "xyz", it show me following error. django.db.utils.ProgrammingError: relation "xyz" does not exist even while executing makemigrations and migrate command, it shows a same error django.db.utils.ProgrammingError: relation "xyz" does not exist although i have intial migrations file in my docker container. how i can access my database of my package.? i try makemigrations and migrate command, but same error. -
django.db.utils.ProgrammingError: relation does not exist during installing external packages using pip
I have created an django resuable app. It has an model file contain following modle models.py from django.db import models class KnApiGatewayToken(models.Model): access_token = models.TextField() refresh_token = models.TextField() There is 1 migration file from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='KnApiGatewayToken', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('access_token', models.TextField()), ('refresh_token', models.TextField()), ], ), ] The resuable app i.e. the django project is working perfectly. I can see the models in the admin side also. Now i have installed this package ( django resuable app ) in another django project using following command pip install /path/to/package/dist/package.tar Package get installed successfully, but during runserver, it is giving following error django.db.utils.ProgrammingError: relation "kn_python_amazon_ad_api_knapigatewaytoken" does not exist LINE 1: ...on_ad_api_knapigatewaytoken"."refresh_token" FROM "kn_python... I have tried running makemigration and migrate command too, but still it gives me the same error. -
Convert datetime string to with timezone in django based on active time zone
I am reading a get request and adding the data to db. import dateutil.parser as dt date_string = '2023-12-14 08:00:00' date_obj = dt.parse(date_string) It shows warning RuntimeWarning: DateTimeField RequestLab.end_time received a naive datetime (2023-12-14 08:00:00) while time zone support is active. Is there any way i can convert this to date object with time zone from django.utils import timezone curr_timezone = timezone.get_current_timezone() and store in the db.. I tried using various methods like datetime_obj_test1 = date_obj.replace(tzinfo=curr_timezone) datetime_obj_test2 = date_obj.astimezone(curr_timezone) But these 2 are changing the time i.e for timezone = "Asia/Kolkata" datetime_obj_test1 = 2023-12-14 08:00:00+05:53 datetime_obj_test2 = 2023-12-14 19:30:00+05:30 I am expecting this as output: 2023-12-14 08:00:00+05:30 -
NoReverseMatch for submitting my form on my profile page
I have a blog project for a assignment and i have all functionality except for my user profiles editing and deleting. I have created the profile page and ability to edit the page. When i then submit my update request, i can see that it submits the change as after i get the error the profile page is updated. I am getting this error and i know it is due to the redirect but i cannot figure out for the life of me how to just redirect back to the user profile. I have tried to just use a httpredirect or reverse and now using reverse_lazy as that has worked fine for blog posts and comments and edits. This is my error and code bellow. I belive it is down to the get_success_url and am hoping that someone has had this error or knows the best fix for this. Thank you NoReverseMatch at /1/edit_profile_page/ Reverse for 'show_profile_page' with no arguments not found. 1 pattern(s) tried: ['(?P[0-9]+)/profile/\Z'] Views.py class EditProfile(LoginRequiredMixin, SuccessMessageMixin, UserPassesTestMixin, generic.UpdateView): model = Profile template_name = 'edit_profile_page.html' form_class = ProfileForm success_message = 'Updated Profile' def get_success_url(self): return reverse_lazy('show_profile_page') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def test_func(self): profile … -
Axios response interceptor times out with put data, but works without put data
Why does the response interceptor not fire for 401 when I use data in put (django server shows 401 due to access_token being outdated, but response interceptor fires timeout of 5000ms exceeded), however if I pass nothing (no data arg in put) fires the response interceptor with 401 as expected. This code does not trigger 401 in the response interceptor const updateProfile = async ({ _isPrivate, _color_scheme, _avatar }) => { var data= { first_name: first_name, last_name: last_name, venmo_username: venmo_username, about: about, private: _isPrivate, color_scheme: _color_scheme, avatar: _avatar, city: city, country: country, phone_number: phone_number, }; axiosConfig .put(`/api/users/${user.id}/`, data) .then((res) => { if (res.status === 200) { setUser(res.data); updateUser(res.data); } else if (res.status === 202) { var msg = res.data.data; Alert.alert(msg); } }) .catch((res) => { Alert.alert("Error during User Profile update. " + res); }); }; Eliminating the parameter does call the 401 in response interceptor const updateProfile = async ({ _isPrivate, _color_scheme, _avatar }) => { axiosConfig .put(`/api/users/${user.id}/`) .then((res) => { if (res.status === 200) { setUser(res.data); updateUser(res.data); } else if (res.status === 202) { var msg = res.data.data; Alert.alert(msg); } }) .catch((res) => { Alert.alert("Error during User Profile update. " + res); }); }; My interceptors look like this. … -
Getting CSRF verification failed. Request aborted. on a Django forms on live server
Hello I am learning Django i write a app and publish it in AWS EC2 instance with gunicorn and ngnix on local environments everything works fine but in production on every submit on forms i get this 403 Error : Forbidden (403) CSRF verification failed. Request aborted. More information is available with DEBUG=True. iam sure in templates every form have {% csrf_token %} and this is my setting.py file of django app: import os from pathlib import Path from decouple import config BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = config("DJANGO_SECRET_KEY") SITE_ID = 1 DEBUG = False ALLOWED_HOSTS = ["winni-furnace.ca", "www.winni-furnace.ca"] CSRF_COOKIE_SECURE = True CSRF_COOKIE_DOMAIN = '.winni-furnace.ca' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', # local 'accounts.apps.AccountsConfig', 'blog.apps.BlogConfig', 'mail_service.apps.MailServiceConfig', 'messages_app.apps.MessagesAppConfig', 'offers.apps.OffersConfig', 'pages.apps.PagesConfig', 'projects.apps.ProjectsConfig', 'score.apps.ScoreConfig', 'services.apps.ServicesConfig', # 3rd 'taggit', "django_social_share", "whitenoise.runserver_nostatic" ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'app.urls' INTERNAL_IPS = [ # ... "127.0.0.1", # ... ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [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 = 'app.wsgi.application' AUTH_USER_MODEL = "accounts.CustomUser" LOGIN_REDIRECT_URL = "pages:index" LOGOUT_REDIRECT_URL = "pages:index" # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases DATABASES = { … -
1 hour difference between Mariadb timestamp and Django DateTimeField
I have a simple Django project that uses an existing mariadb database running at localhost as the default database. In the database timestamps are stored correctly, in Django however they are one hour later. I created a simple database called test with a table called time: CREATE DATABASE test; CREATE TABLE time (time_id INT PRIMARY KEY AUTO_INCREMENT, time TIMESTAMP); INSERT INTO time (time) VALUES (NOW()); Then I started a Django project called testproject with an app called testapp. I set the database settings and defined the following model: class Time(models.Model): time_id = models.AutoField(primary_key=True) time = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'time' After running migrate, when I open python manage.py dbshell, I get: MariaDB [test]> SELECT CONVERT_TZ(`time`, @@session.time_zone, '+00:00') AS 'utc_datetime' FROM time; +---------------------+ | utc_datetime | +---------------------+ | 2023-12-27 20:40:46 | +---------------------+ 1 row in set (0.000 sec) which ist correct. However when I do the same thing with python manage.py shell, I get: >>> from testapp.models import Time >>> Time.objects.latest('time').time datetime.datetime(2023, 12, 27, 21, 40, 46, tzinfo=datetime.timezone.utc) I noticed this in a more complex project but was able to reproduce it in this very simple example. I live in the timezone CET, in the settings.py … -
How to find the desktop or user path?
I want you to help me to find this path. For example, I work on a project like Django. Then to be able to access the client desktop I need to find that path so I can put the required files directly on it. Although I know Django gives me an address, I only gave an example. I didn't make any effortand just came here hopingto find an answer and asked my question. That's it! -
Docker Compose + Django CLI commands: django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable
I have a django + vue project built using django cookie cutter with docker. Because I've done this with docker, after starting my containers, I can't use the normal python manage.py command command. I instead get this error message django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable. I have searched everywhere to figure out how to fix this but I can't find anyone with a fix for this. So my question is: Is there a fix for the DATABASE_URL error I am getting? -- Steps to reproduce are follow these cookie cutter django with docker instructions and try to run python manage.py migrate. -
I have an issue with my smtp relay server while sending email from Godaddy website
Hello everyone i have a website where Iam sending an outgoing mail from my website to other email accounts during registration for confirming. I am unable to send this email and even after talking to godaddy customer service multiple times, the issue remains unresolved. Iam using Django and these are my settings. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = relay-hosting.secureserver.net EMAIL_PORT = 25 EMAIL_USE_TLS = False # GoDaddy's relay server does not use TLS/SSL EMAIL_HOST_USER = '' # Typically, no username/password is required for internal relay EMAIL_HOST_PASSWORD = '' EMAIL_USE_SSL = False [ Error Screenshot 1 Error Screenshot 2 current_site = get_current_site(request) mail_subject = 'Activate your blog account.' from_email_address = 'noreply@indiaengineerskills.com' message = render_to_string('network/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user_imp.pk)), 'token': account_activation_token.make_token(user_imp), }) to_email = user_email email = EmailMessage(mail_subject, message, to=[to_email]) email.send() The above screenshots are error snippet and code snippet for sending mail. Any help would be appreciated I have tried talking to godaddy about this but they said that their testscript was working fine...