Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
matplotlib savefig() in django works in local server but not in docker
So when I try to savefig it works on django running on localserver but does not work on docker. Below is the example code for save fig df_2["vendor"].value_counts().plot(kind="barh") plt.title("Custom HTML Tags by Vendor") path = folder + "/" + timestamp_o + f"vendors for custom html temp.png" plt.savefig(path) img_sheet.insert_image("E" + str(cell_number), path) plt.savefig(path, bbox_inches="tight") Below are the images- in local server in docker -
Unable to do migrations in django
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency userauths.0001_initial on database 'default'. 1)I have tried commenting "django.contrib.admin", and path("admin/", admin.site.urls), 2)I have tried python manage.py migrate userauths zero and then deleting all migration file except init file then python manage.py makemigrations userauths then after that i used python manage.py migrate still facing the same issue -
Python Django ModelViewSet implementation with SAML ACS
In the current system with the legacy IAM, we have implemented a class inherited from ModelViewSet with login and logout functions. In the legacy IAM, it is not compulsory to obtain name_id and session_index to logout. Therefore, we can bypass acs (a.k.a. assertion_consumer_service) to obtain these information and go straight to the logout. Now, a new IAM system is deployed and we need to extend the current implementation to support both login and logout (along with acs). name_id and session_index shall be provided in LogoutRequest. Given we have different set of URLs for login/logout: https://example.com/saml2/account/[login|logout] acs: https://example.com/saml2/sso/acs How can we update the following code to support the callback from acs so that we can save the name_id and session_index? urls.py router = DefaultRouter() router.register("saml2/account", Saml2AccountView, basename="account") urlpatterns = [ url("", include(router.urls)), ] views.py class Saml2AccountView(viewsets.ModelViewSet): @action(detail=False, methods=['get']) def login(self, request, *args, **kwargs): # implement the login function @action(detail=False, methods=['get']) def logout(self, request, *args, **kwargs): # implement the logout function -
error in the application's ajax request in an azure app
I have an app in python-django and on localhost everything works normally. I make ajax requests to Python correctly, however it doesn't work in the Azure application, follow the example code of how I make a request: $.ajax({ url: '/PlanEx/DCC/GerarTabelaAnova', data: formData, type: 'POST', Furthermore, my gateway app constantly times out -
Django: first data record not being saved when field = zero
I am new to Django and I am currently struggling to find out the reason the first data record from a formset is not saved (included) into database when the numeric field poQtyof the ProductOrder model is equal to zero. QueryDict seems to be okay with 4 records in this example, but the first record is not included in the database when productorder_set-0-poQty is zero: <QueryDict: {'csrfmiddlewaretoken': ['6b85qEA4LMz7f3lcUvlpAi74BATLiouApAE1AKLMQhz0I7Gohvmw8jhAHnMf82LT'], 'orderOpen': ['on'], 'orderTable': ['02'], 'menuQuery': ['1'], 'productorder_set-TOTAL_FORMS': ['4'], 'productorder_set-INITIAL_FORMS': ['0'], 'productorder_set-MIN_NUM_FORMS': ['0'], 'productorder_set-MAX_NUM_FORMS': ['1000'], 'productorder_set-0-prodQuery': ['1'], 'productorder_set-0-poQty': ['0'], 'productorder_set-0-poOrder': [''], 'productorder_set-0-id': [''], 'productorder_set-1-prodQuery': ['2'], 'productorder_set-1-poQty': ['0'], 'productorder_set-1-poOrder': [''], 'productorder_set-1-id': [''], 'productorder_set-2-prodQuery': ['4'], 'productorder_set-2-poQty': ['0'], 'productorder_set-2-poOrder': [''], 'productorder_set-2-id': [''], 'productorder_set-3-prodQuery': ['3'], 'productorder_set-3-poQty': ['0'], 'productorder_set-3-poOrder': [''], 'productorder_set-3-id': ['']}> I would appreciate some help on that... thanks! Here are further details: models.py class ProductClass(models.Model): classDescription = models.CharField(max_length=255, verbose_name='Type', unique=True, null=True) classPrint = models.BooleanField(default=True, verbose_name='Print?') class Meta: verbose_name_plural = 'Product Classes' def __str__(self): return self.classDescription class Product(models.Model): prodclassQuery = models.ForeignKey(ProductClass, on_delete=models.PROTECT, verbose_name='Product Class', default=1) prodDescription = models.CharField(max_length=255, verbose_name='Product') prodPrice = models.DecimalField(max_digits=6, decimal_places=2, verbose_name='Price') class Meta: ordering = ['prodclassQuery', 'prodDescription'] def __str__(self): return self.prodDescription class Menu(models.Model): menuActive = models.BooleanField(verbose_name='Active?', default=False) menuDescription = models.CharField(max_length=255, verbose_name='Menu') prodQuery = models.ManyToManyField(Product, verbose_name='Product') class Meta: ordering = ['menuDescription', ] def __str__(self): return … -
Use Multiple analyzer in elastic search.(Autocomplete and phonetic)
The analysis algorithm is performing well on autocomplete with fuzzy matching but the fuzzy matching is not soo good so i wanted to add phonetic analyzer to same firstname index. i ran through many documentation and didnot find good one on how to use 2 analyzer. "settings": { "analysis": { "analyzer": { "autocomplete_analyzer": { "type": "custom", "tokenizer": "autocomplete_tokenizer", "filter": [ "lowercase" ] }, "phonetic_analyzer": { "type": "custom", "tokenizer": "standard", "filter": [ "lowercase", "phonetic" ] } }, "tokenizer": { "autocomplete_tokenizer": { "type": "edge_ngram", "min_gram": 2, "max_gram": 10, "token_chars": ["letter", "digit"] } } } }, "mappings": { "properties": { "full_name": { "type": "text", "analyzer": "autocomplete_analyzer" }, "relation_name": { "type": "text", }, "address": { "type": "text" } } } } -
How does Django Implicitly Set Data Types for CharField or Any Other?
from django.db import models class Post(models.Model): title = models.CharField(max_length=100, null=True) When I define a field named title = models.CharField(max_length=100, null=True) in a Django model, how does Django implicitly set the data type for this field? Django automatically recognised title as CharField[str | None]. If i set null = False then type become CharField[str]. I want to know how can i implement this in my class. Thank You! Python version: 3.11.6 Using Pylance -
How to change the default directories of your project
So, i'm developing this app in python and when i try to show some html in the browser i get this error: TemplateDoesNotExist at /xPharma/hello/ hello.html Request Method: GET Request URL: http://127.0.0.1:8000/xPharma/hello/ Django Version: 4.2.11 Exception Type: TemplateDoesNotExist Exception Value: hello.html Exception Location: C:\Users\Marco\.virtualenvs\XpharmBackend-9gJJ8jLG\lib\site-packages\django\template\loader.py, line 19, in get_template Raised during: xPharma.views.say_hello Python Executable: C: \Users\Marco\.virtualenvs\XpharmBackend-9gJJ8jLG\Scripts\python.exe Python Version: 3.9.7 Python Path: ['C:\\Users\\Marco\\Desktop\\Desktop\\progetto X pharme\\XpharmBackend', 'C:\\Python39\\python39.zip', 'C:\\Python39\\DLLs', 'C:\\Python39\\lib', 'C:\\Python39', 'C:\\Users\\Marco\\.virtualenvs\\XpharmBackend-9gJJ8jLG', 'C:\\Users\\Marco\\.virtualenvs\\XpharmBackend-9gJJ8jLG\\lib\\site-packages'] Server time: Mon, 01 Apr 2024 15:44:22 +0000 but i find out that i get this error because python is searching for a file in the wrong directory... Using engine django: django.template.loaders.app_directories.Loader: C:\Users\Marco\.virtualenvs\XpharmBackend-9gJJ8jLG\lib\site-packages\django\contrib\admin\templates\hello.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Marco\.virtualenvs\XpharmBackend-9gJJ8jLG\lib\site-packages\django\contrib\auth\templates\hello.html (Source does not exist) Is there a way to change this directories and redirect python to where i saved my file? -
IntegrityError: insert or update on table
I am currently working on a web application that uses Django as a backend, Django Rest Framework as an API, React as a frontend, and PostgreSQL as a database. For user authentication, I utilized SimpleJWT. However, I encountered an issue where I am able to create a user account through the frontend, but I cannot log in with the newly created account. There's an error message appearing in the console, the user information is present in the database. However, I can still log in with a couple of accounts that were created a while ago(all accounts from the same database table), both through the front end and Django Rest Framework. I keep getting this error on Django: the parenthesis for (user_id) can be different every time in the error IntegrityError at /api/token/ insert or update on table "token_blacklist_outstandingtoken" violates foreign key constraint "token_blacklist_outs_user_id_83bc629a_fk_auth_user" DETAIL: Key (user_id)=(4) is not present in table "auth_user". Here's my database table, this first 3 accounts I can successfully log in through frontend and Rest framework settings.py (only the simpleJWT part): SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=30), "REFRESH_TOKEN_LIFETIME": timedelta(days=90), "ROTATE_REFRESH_TOKENS": True, "BLACKLIST_AFTER_ROTATION": True, "UPDATE_LAST_LOGIN": True, # FOR SECURITY REASON (ABOVE) "ALGORITHM": "HS256", "SIGNING_KEY": SECRET_KEY, "VERIFYING_KEY": "", "AUDIENCE": … -
Django + React Session Based Auth 'AnonymousUser' object has no attribute '_meta'
I am learning Django & React. I created a little session-based auth app that worked fine for an attempt and then I broke it by pressiong 'logout'. Now it is impossible to log in. It always return the following error: AttributeError: 'AnonymousUser' object has no attribute '_meta'. "POST /api/login/ HTTP/1.1" 500 75814 Here is my api/views.py code: from django.shortcuts import render # Create your views here. import json from django.contrib.auth import authenticate, login, logout from django.http import JsonResponse from django.views.decorators.csrf import ensure_csrf_cookie from django.views.decorators.http import require_POST @require_POST def login_view(request): data = json.loads(request.body) username = data.get("username") password = data.get("password") if username is None or password is None: return JsonResponse({"details": "Please provide both username and password"}) user = authenticate(request, username=username, password=password) if user is not None: return JsonResponse({"details": "invalid username and password"}, status=400) login(request, user) return JsonResponse({"details": "login successful"}) def logout_view(request): if not request.user.is_authenticated: return JsonResponse({"details": "you are not logged in"}, status=400) logout(request) request = JsonResponse({"details": "logout successful"}) @ensure_csrf_cookie def session_view(request): if not request.user.is_authenticated: return JsonResponse({"isauthenticated": False}) return JsonResponse({"isauthenticated": True}) def whoami_view(request): if not request.user.is_authenticated: return JsonResponse({"isauthenticated": False}) return JsonResponse({"username": request.user.username}) Thanks a lot for your help ! I tryed to: create another user on the admin pannel. restart server edit views.py … -
Cannot use Model in deployment, despite being created
I have a Django app with several apps within. I have App_A with the settings.py and then App_B where I have created the following models: from django.db import models from decimal import Decimal import re class Webshop(models.Model): name = models.CharField(max_length=255, unique=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) compare_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) webshop = models.ForeignKey(Webshop, on_delete=models.CASCADE, related_name='products') date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name @staticmethod def parse_price(price_str): # Remove currency and convert to a format suitable for Decimal price_str = re.sub(r'[^\d,]', '', price_str).replace(',', '.') return Decimal(price_str) if price_str else None Locally, I am able to get all the products, but once I deploy the app, I cannot get any items. I use the following view to show the products, and locally this is fine, but deployed, it gives me an error, see below. from django.shortcuts import render from .models import Webshop, Product def webshop_dashboard_view(request): # get all products products = Product.objects.all() print(products) return render(request, 'webshop_dashboard.html') And the error I get is: Exception Type: ProgrammingError at /webshop-dashboard/webshop_dashboard/ Exception Value: relation "WebshopDashboard_product" does not exist LINE 1: ...id", "WebshopDashboard_product"."date_added" FROM "WebshopDa. I have tried to re-create the database and migrations, but I cannot seem … -
drf_yasg openapi swagger keeps on showing Django Login link
settings.py INSTALLED_APPS = [ .. 'drf_yasg', .. ] views.py class myapi(APIView): permission_classes = (permissions.AllowAny,) authentication_classes = () @swagger_auto_schema(operation_description="A custom description", request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'token': openapi.Schema(type=openapi.TYPE_STRING, description='token'), }, required=['token'], )) urls.py from drf_yasg.views import get_schema_view from drf_yasg import openapi from rest_framework import permissions schema_view = get_schema_view( openapi.Info( title="MY API", default_version='v1', ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('user_api.urls')), re_path(r'^apidoc/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), ] https://gist.github.com/axilaris/2e15f9c0cc8aff2727c39917123d25f4 nginx configuration server { listen 80; server_name 182.20.4.110 mydomain.io; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/myproj_app/static/; } location / { alias /home/ubuntu/myproj_app/frontend/build/; } location /apidoc { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } sudo tail -f /var/log/nginx/error.log 2024/04/01 12:37:01 [error] 3618#3618: *128 open() "/home/ubuntu/myproj_app/static/static/drf-yasg/insQ.min.js" failed (13: Permission denied), client: 172.20.1.172, server: 182.20.4.110, request: "GET /static/drf-yasg/insQ.min.js HTTP/1.1", host: "mydomain.io", referrer: "https://mydomain.io/apidoc/" 2024/04/01 12:37:01 [error] 3618#3618: *129 open() "/home/ubuntu/myproj_app/static/static/drf-yasg/immutable.min.js" failed (13: Permission denied), client: 172.20.1.172, server: 182.20.4.110, request: "GET /static/drf-yasg/immutable.min.js HTTP/1.1", host: "mydomain.io", referrer: "https://mydomain.io/apidoc/" 2024/04/01 12:37:01 [error] 3618#3618: *128 open() "/home/ubuntu/myproj_app/static/static/drf-yasg/swagger-ui-dist/favicon-32x32.png" failed (13: Permission denied), client: 172.20.1.172, server: 182.20.4.110, request: "GET /static/drf-yasg/swagger-ui-dist/favicon-32x32.png HTTP/1.1", host: "mydomain.io", referrer: "https://mydomain.io/apidoc/" However, I keep getting this is I go into https://mydomain.io/apidoc/. It should the swagger api page. I got it working on my … -
nginx cannot serve React due to permission denied. www-data cant access frontend/build/
I'm trying to configure nginx so that it can serve both React and Django. Here is my configuration: server { listen 80; server_name 182.20.4.110 mydomain.io; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/myproj_app/static/; } location / { alias /home/ubuntu/myproj_app/frontend/build/; } location /apidoc { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } https://gist.github.com/axilaris/2329d3ff73034b51483366772c7cef9c However, I keep getting 403 Forbidden And based on the nginx error logs, it keeps getting permission denied in the React build directory sudo tail -f /var/log/nginx/error.log 2024/04/01 12:23:57 [error] 3616#3616: *68 "/home/ubuntu/myproj_app/frontend/build/index.html" is forbidden (13: Permission denied), client: 172.20.4.193, server: 182.20.4.110, request: "GET / HTTP/1.1", host: "182.20.4.110" 2024/04/01 12:23:58 [error] 3616#3616: *69 "/home/ubuntu/myproj_app/frontend/build/index.html" is forbidden (13: Permission denied), client: 172.20.1.172, server: 182.20.4.110, request: "GET / HTTP/1.1", host: "182.20.4.110" 2024/04/01 12:24:21 [error] 3616#3616: *67 "/home/ubuntu/myproj_app/frontend/build/index.html" is forbidden (13: Permission denied), client: 172.20.1.172, server: 182.20.4.110, request: "GET / HTTP/1.1", host: "mydomain.io" 2024/04/01 12:24:27 [error] 3616#3616: *70 "/home/ubuntu/myproj_app/frontend/build/index.html" is forbidden (13: Permission denied), client: 172.20.4.193, server: 182.20.4.110, request: "GET / HTTP/1.1", host: "182.20.4.110" 2024/04/01 12:24:28 [error] 3616#3616: *71 "/home/ubuntu/myproj_app/frontend/build/index.html" is forbidden (13: Permission denied), client: 172.20.1.172, server: 182.20.4.110, request: "GET / HTTP/1.1", host: "182.20.4.110" 2024/04/01 12:24:30 [error] 3616#3616: *67 "/home/ubuntu/myproj_app/frontend/build/index.html" is forbidden (13: Permission denied), client: … -
how to import functions inside /static/ dir Django
When i make script for my django project i made a few functions but when i started optimising it and divide for few files i encounter a problem with the importing of function ** cart_methods.js** export function cartFunction() { console.log("work"); } ** home_script.js** import { cartFunction } from './cart_methods.js'; cartFunction(); with this part of code my .js not work at all not even small part of code not working. it stop everything every files is in same folder static> shop> asstets> js> cart_methods.js home_script.js -
How can I call/reach "gettype()" from oracledb connection through objects defined in "django.db"?
I have a small Django application with an Oracle DB as database. I use "Django 5.0.3" with "oracledb 2.0.1". In "oracledb" library the object "connection" has a method called "gettype()" see https://python-oracledb.readthedocs.io/en/latest/api_manual/connection.html#Connection.gettype How can I call/reach this method through objects defined in "django.db"? DB configuration in "settings.py" import oracledb from pathlib import Path # Database d = r"/path/to/oracle/instantclient" oracledb.init_oracle_client(lib_dir=d) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': '<db-name>', 'USER': '<db-user>', 'PASSWORD': '<db-password>', } } For example, it doesn't work via the "connection" object: from django.db import connection def myfunc(): with connection.cursor() as c: c.execute("select * from v$version") rows = c.fetchall() print(rows) my_db_type = connection.gettype("MY_DB_TYPE") [('Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production', 'Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production\nVersion 19.23.0.1.0', 'Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production', 0)] ERROR:root:global error: ERROR:root:global Exception type: AttributeError ERROR:root:global Exception message: 'DatabaseWrapper' object has no attribute 'gettype' -
error in deleting payments in Xero, confused what else am I missing
first time poster and really desperate to find a solution to this. I am running a django project, one of the functions will delete payments in Xero, reading through the documentation, I thought it should be easy as it only needs one parameter and to include in the resourceID. but I got an error back saying {"Title":"An error occurred","Detail":"An error occurred in Xero. Check the API Status page http://status.developer.xero.com for current service status.","Status":500,"Instance":"f137f1e1-4011-43ed-b921-1e1827a90dad"} This is my code snippet. for paymentID in payment_IDs: token = XeroOAuth2Token.objects.latest('id') delete_payment_endpoint = f'https://api.xero.com/api.xro/2.0/Payments/{paymentID}' headers_del_payments = { "Authorization":f"Bearer {token.access_token}", "Xero-Tenant-Id": TENANT_ID, "Accept": "application/json", "Content-Type": "application/json" } response = requests.post(delete_payment_endpoint, headers=headers_del_payments) return HttpResponse(response.text) I tried adding Status:DELETE or paymentID:{ID here} as a payload but it just gave me an Error14 { "ErrorNumber": 14, "Type": "PostDataInvalidException", "Message": "Invalid Json data" } -
Virtual enviroment - Why can't I set enviromental variable?
I am trying to start up daphne for my Django project. The issue is that I am not able to set up the envirometnal variable for DJANGO_SETTINGS_MODULE. I am using python venv. Path of my project is as follows: C:\Users\HP ELITEBOOK\Documents\Projects\myenv\MyProject\MyProject\settings I tried many different combinations already. I activate venv. I cd into "C:\Users\HP ELITEBOOK\Documents\Projects\myenv\MyProject" and use command: set DJANGO_SETTINGS_MODULE=MyProject.settings But when I try to check the variable with echo I still get only "%DJANGO_SETTINGS_MODULE%". Which to my understanding means the variable is not set. What am I missing? -
How can I customize django TextField for Inline Editor
I'm developing an internet forum platform using Django and facing a challenge regarding the customization of the TextField to support inline editor without third-party editors such as TinyMCE or CKEditor. The objective is to empower users to compose rich content including code snippets, links, images, tables, and formatted text directly within the TextField. However, after I found a tutorial, I haven't found a clear solution for implementing inline editor functionality. I want to create inline editor that uses different special characters to display content in the browser. Could anyone point us an examples or documentation for customizing Django TextField to support inline editor? -
Django ValueError at /en/admin/auth/user/ year -1 is out of range
i have production django server one of the users with id 399 is causing this error every time it included in search results, the user model i am using is the default django User model. Django Version: 4.0.10 Exception Type: ValueError Exception Value: year -1 is out of range Exception Location: ../.venv/lib64/python3.9/site-packages/django/db/utils.py, line 98, in inner Python Executable: ../.venv/bin/python3.9 Python Version: 3.9.18 database : Postgresql 10.23 even when i go to the django admin page and trying to delete the user the same error raised but it is possible to delete any other user. -
Unable to link a model Object to another model, which takes in a OnetoOnefiled
So I have a login page, which also has an option to register if you're a new user. The registration phase consists of two pages, one where the user enters their personal information, and two where the user sets the username and password. Right now I am storing them as strings just to get my website running. I am successful in creating a model object for the personal information, and also successful in linking that object to the newly created login details object. I am trying to compare the entered values of the user on the login page to the objects stored in the database and once they match, I want to be able to retrieve the role of the user, which is a part of the UserData object and navigate to the appropriate dashboard. I dont seem to to get it working Registration.js import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { useNavigate } from 'react-router-dom'; const RegistrationPage = () => { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const navigate = useNavigate(); const [latestUserData, setUserData] = useState(null); useEffect(() => { const fetchLatestObject = async () => { try { const … -
Django ORM get latest from each group
I have records in below format: | id | name | created | ----------------------------------------------- |1 | A |2024-04-10T02:49:47.327583-07:00| |2 | A |2024-04-01T02:49:47.327583-07:00| |3 | A |2024-03-01T02:49:47.327583-07:00| |4 | A |2024-02-01T02:49:47.327583-07:00| |5 | B |2024-02-01T02:49:47.327583-07:00| Model: class Model1(model.Models): name = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) I want to perform a group by in django with month from field created and get latest record from that month. Expected output: | id | name | created | ----------------------------------------------- |1 | A |2024-04-10T02:49:47.327583-07:00| |3 | A |2024-03-01T02:49:47.327583-07:00| |4 | A |2024-02-01T02:49:47.327583-07:00| So far, I have tried: from django.db.models.functions import ExtractMonth m = Model.objects.get(id=1) ( Model1.objects.filter(name=m.name) .annotate(month=ExtractMonth("created")) .annotate(latest_time=Max("created")) .values("month", "id") .order_by("-latest_time") ) But this is still returning be duplicate month data. Please provide some insights. -
Connect to Server signed with openssl certificate with Android Studio Virtual Device
I am creating an app on my computer with React Native as frontend and Django as backend. I had a prototype working with requests in protocol HTTP from the app to the Django server, but as I wanted to implement HTTPS, I installed Apache as a reverse proxy server and everything looks good but now, I have an error while requesting the virtual device of Android Studio to the new URL... (have to mention that from Postman it works perfectly) I think is has to do with the CA Certificate I created for using HTTPS as it is not trusted because it was created with OpenSSL. I can enter all the URLs from Django in my local network but when I try to enter them from the virtual device browser they don't render I can see that the certificate I created is there but I can't install it as the virtual device's screen goes black when I try to do that Photos: Error when fetching Local PC Virtual Device: enter image description here enter image description here Do you have any clue of what am I missing? Thanks! -
Django custom user admin not reflected in admin site
I am new to django and going through legacy django project where Custom user admin is configured with following: app1/admin.py from .models import User @admin.register(User) class UserAdmin(DjangoUserAdmin): """Define admin model for custom User model with no email field.""" fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('email', 'first_name', 'last_name', 'phone_number', 'type_of_user', 'timezone', 'deleted', 'is_supervisor', 'supervisor', 'role')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined', 'created_date')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'username', 'password1', 'password2'), }), ) list_display = ('username', 'first_name', 'last_name', 'is_staff') search_fields = ('username', 'first_name', 'last_name') ordering = ('username',) Also in app1.models.py, where CustomUser is further inherit from AbstractBaseUser. class User(CustomUser): first_name = models.CharField(max_length=1024, db_index=True) last_name = models.CharField(max_length=1024, db_index=True) phone_number = models.CharField(max_length=1024, blank=True, null=True) is_supervisor = models.BooleanField(default=False, db_index=True) license = models.CharField(max_length=1024, blank=True, null=True) type_of_user = models.IntegerField(choices=TYPE_OF_USER, default=1, db_index=True) created_date = models.DateTimeField(default=timezone.now) timezone = TimeZoneField(choices=[(tz, tz) for tz in pytz.all_timezones]) deleted = models.BooleanField(default=False, db_index=True) load_id = models.CharField(max_length=1024, null=True, blank=True) approval_status = models.IntegerField(choices=APPROVAL_STATUS, null=True, blank=True) supervisor = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) last_alert_sent_on = models.DateTimeField(null=True, blank=True, db_index=True) role = models.ForeignKey("common.Role", on_delete=models.SET_NULL, null=True, blank=True) In settings.py: AUTH_USER_MODEL = 'app1.User' There's no admin.py in main_app folder. The problem here is that the User model … -
How can I re-filter queryset without N+1 problems in Django?
I have simple N+1 problem with queryset in Django. Simple views.py code example of the problem what I'm having. a_queryset = AA.objects.filter(user=request.user).all() # some codes in here with a_queryset . . . b_queryset = a_queryset.filter(id__in=[3,4,5]) # re-filtered # some codes in here with b_queryset . . . c_queryset = a_queryset.get(id=10) # re-filtered # some codes in here with c_queryset . . . I have N+1 problem which is three SELECT queries and I already know these codes cause it. It would be very nice to call queryset at once, but I can't because there're some tasks in the middle. What should I do? -
i am facing the issue when submiting the form of second section , the returns back to the first section insted of updating the content of curent page
User this is my script for the single page with side bar in which 4 four buttonsrespectivey for page 1 page 2 page 3 page 4, these four pages are in a single template and containing the relevant content , page is containg two form, the first form showing the drop down of the loc_ids as i selects the value from the drop down and submits the form it should update the current page content as the second form from the views file rendering the same template which containing the four pages , as the view sending the value to the template, on the front as page loading completes it showing me the first page which welcome page , instead of this how can i remain on the current page(specific section of the template), this is due to as the view rendering the template and on submiting the previus form it rediret to the second form's view which is rendering the template and when loading it show the template from the start . on tis page i have a multiple forms , here i have also same forms but rendering from diffrent views. <script> window.addEventListener('load', function() { var urlPath = …