Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mechanism for returning unreceived websockets
In my project, we are facing a problem that we cannot solve. The technological context: Our application runs under Django and has Websockets. This stand in a Kube environment. The http part with its API is managed by Django and DRF in Gunicorn pods. The websockets and the asgi layer of the app are managed by Daphne in Daphne pods. We use Channel for Django to support WS. We use its ChannelRedis layer to share data in real time between the various server instances, allowing them to access the same websocket information. The functional context: We have users interacting with the application then the front hit the back via the API. This then triggers a workflow which will, as it progresses, notify the front via WS messages. All users'fronts receive these changes and are then updated. Well, this is the classic principle of WS in fact. Our problem: It happens that some users no longer receive any WS messages (network problem, Daphne, Redis service interruption problem or other). So these users no longer have the right values on their front.. After, the WS connection is reestablished, the next ws messages will be sent again. Unfortunately, messages sent during the blackout … -
SSL routines::legacy sigalg disallowed or unsupported] (-1)
I'm trying to connect my django app to a SQL Server instance. In development I'm using a sqlsrv created with a docker image and everything work just fine. In production I have a connection issue: (('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]SSL Provider: [error:0A00014D:SSL routines::legacy sigalg disallowed or unsupported] (-1) (SQLDriverConnect)')) The database settings (settings.py file) are: DATABASES = { 'default': { ... }, 'mssql_db': { "ENGINE":os.environ.get("MSSQL_ENGINE", ""), "NAME": os.environ.get("MSSQL_DB_NAME", ""), "USER": os.environ.get("MSSQL_USER", ""), "PASSWORD": os.environ.get("MSSQL_PASSWORD", ""), "HOST":os.environ.get("MSSQL_HOST", ""), "PORT": os.environ.get("MSSQL_PORT", ""), 'OPTIONS': { 'driver': os.environ.get("MSSQL_OPTIONS", ""), 'MARS_Connection': 'True', 'SSL Mode': 'require', }, } } I've added the following lines, but nothing changed: 'MARS_Connection': 'True', 'SSL Mode': 'require', I've checked the credentials I use and they're correct, also can't find any strange settings of the SQL Server, from Microsoft SQL Server Management Studio. -
Need Help Sending Email Through Office 365 SMTP with Custom Domain
I need to be able to send emails to users from support@example.com which is hosted in office365.My project's setting file for the email backend looks like this # Email settings EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.office365.com" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = "support@example.com" EMAIL_HOST_PASSWORD = "App_password" The specific error message I'm currently facing is [Authentication unsuccessful, the request did not meet the criteria to be authenticated successfully. Contact your administrator.] I have verified the login credentials and also tried both ports 587 and 25, but the issue remains unresolved. **However, ** I was able to send emails successfully using smtp-mail.outlook.com with an @outlook.com email address EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp-mail.outlook.com" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = "personal@outlook.com" EMAIL_HOST_PASSWORD = "App_password" I don't think this has anything to do with it but function that sends the email. def send_email_verification(user): site_url = "https://www.example.com" print("Trying to send email") if user.is_active: return else: print("sending email") confirmation_token = default_token_generator.make_token(user) # unique token activation_link = f"{site_url}/users/api/users/activate/{user.id}/{confirmation_token}" # activation link to be sent in email subject = "Verify your Email address" from_email = settings.EMAIL_HOST_USER to_email = user.email # Load the email template and render it with the activation link html_content = render_to_string('email_verification.html', … -
how does search engines identify data of website is exactly stored in the particular database and server
I'm working on a small Python project using Django, and I'm curious about how search engines can quickly identify a website's database and server and respond to end users in just a fraction of a second also i want to know that how data is transmitted -
Is it possible to host django website in the github?
i want to try django website to host in github. is it possible to host it? try it. try it, try it. still now i try it last 3 Days. what should i do for this. any other solution is there. any one reply me with right answer. -
Connect local django application to redis container
I have a django project in local machine + In the docker i have redis container and that is up. when i use docker ps i get this result: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ff39ad874428 redis "docker-entrypoint.s…" 52 minutes ago Up 50 minutes 0.0.0.0:6379->6379/tcp redis2 and this is my cache config in django setting.py: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://localhost:6379', # Adjust the host and port if needed # 'OPTIONS': { # 'CLIENT_CLASS': 'django_redis.client.DefaultClient', # } } } So when i cache in my view, Dosnt save any data. First, How can i check the connection from django to redis container? Second, How can i add new key from django into redis container? Thanks. -
Getting error "detail":"Authentication credentials were not provided."
I tried to get the username corresponding to the auth_token but getting this error. I followed the djoser's documentation ERROR: PS D:\test\testenv\test2> curl.exe -X POST http://127.0.0.1:8000/api/v1/users/ --data 'username=admin3&password=password@123' {"username":["A user with that username already exists."]} PS D:\test\testenv\test2> curl.exe -X POST http://127.0.0.1:8000/api/v1/token/login/ --data 'username=admin3&password=password@123' {"auth_token":"3d0ad33f20ea22e8131a170da2db7830a18b3757"} PS D:\test\testenv\test2> curl.exe -LX GET http://127.0.0.1:8000/api/v1/users/me/ -H 'Authorization: Token 3d0ad33f20ea22e8131a170da2db7830a18b3757' {"detail":"Authentication credentials were not provided."} PS D:\test\testenv\test2> curl.exe -LX GET http://127.0.0.1:8000/api/v1/users/ -H 'Authorization: Token 3d0ad33f20ea22e8131a170da2db7830a18b3757' {"detail":"Authentication credentials were not provided."} PS D:\test\testenv\test2> It should return me the token's corresponding details. -
Media files are not shown: open() "/home/shahriar/Amlak/real_estate/media/images/image1.jpg" failed (13: Permission denied) - Django Nginx
I'm trying to see my media files in my website, but I can't. Static files are OK but Media files, despite all my efforts are not visible. Here is nginx error log: 2023/10/17 11:59:33 [error] 48068#48068: *7 open() "/home/shahriar/Amlak/real_estate/media/images/ویلا-چمستان-1_uWh54BB.jpg" failed (13: Permi> 2023/10/17 11:59:33 [error] 48068#48068: *6 open() "/home/shahriar/Amlak/real_estate/media/images/IMG_20230828_214539_i6yw2Zc.jpg" failed (13:> 2023/10/17 11:59:33 [error] 48068#48068: *5 open() "/home/shahriar/Amlak/real_estate/media/images/image1.jpg" failed (13: Permission denied), > 2023/10/17 11:59:33 [error] 48068#48068: *4 open() "/home/shahriar/Amlak/real_estate/media/images/ویلا-چمستان-1_0kmP7E3.jpg" failed (13: Permi> 2023/10/17 11:59:33 [error] 48068#48068: *3 open() "/home/shahriar/Amlak/real_estate/media/images/455008604_479875.jpg" failed (13: Permission> My nginx configuration file for website: location /static { alias /var/www/real_estate/static/; } location /media { root /home/shahriar/Amlak/real_estate/; } settings.py: STATIC_URL = 'static/' STATIC_ROOT = '/var/www/real_estate/static/' STATICFILES_DIRS = [BASE_DIR/'static/',] # Default primary key field type # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Media Settings MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / 'media/' I tried giving permission to my media folder like this: sudo chown -R www-data:www-data /var/www/real_estate/static sudo chown -R www-data:www-data /home/shahriar/Amlak/real_estate/media I tried restarting nginx.service and gunicorn.service. The path to media files is correct, but the website seems to be unable to get them. -
Could not import 'backend.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: Type "Mutation" not found in the Schema
Im trying to merge two GraphQL outputs and I have this error when I try to load Could not import 'backend.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: Type "Mutation" not found in the Schema. I have two schemas within each corresponding apps from graphene_django import DjangoObjectType from careers import models import graphene class JobType(DjangoObjectType): class Meta: model = models.Job class CategoryType(DjangoObjectType): class Meta: model = models.Category class Query(graphene.ObjectType): all_jobs = graphene.List(JobType) job_by_slug = graphene.Field(CategoryType, slug=graphene.String()) def resolve_jobs_by_category(root, info, category): return ( models.Job.objects.prefetch_related("category") .select_related("title") .filter(category__name__iexact=category) ) schema = graphene.Schema(query=Query) and the 2nd on here: from django.contrib.auth import get_user_model from graphene_django import DjangoObjectType from blog import models import graphene class UserType(DjangoObjectType): class Meta: model = get_user_model() class AuthorType(DjangoObjectType): class Meta: model = models.Profile class PostType(DjangoObjectType): class Meta: model = models.Post class TagType(DjangoObjectType): class Meta: model = models.Tag class ImageType(DjangoObjectType): class Meta: model = models.UploadImage class Query(graphene.ObjectType): all_posts = graphene.List(PostType) author_by_username = graphene.Field(AuthorType, username=graphene.String()) post_by_slug = graphene.Field(PostType, slug=graphene.String()) posts_by_author = graphene.List(PostType, username=graphene.String()) posts_bt_tag = graphene.List(PostType, tag=graphene.String()) def resolve_all_posts(root, info): return ( models.Post.objects.prefetch_related("tags").select_related("author").all() ) def resolve_author_by_username(root, info, username): return models.Profile.objects.select_related("user").get( user__username=username ) def resolve_image(self, info): if self.image: self.image = info.context.build_absolute_uri(self.image_url) return self.image def resolve_post_by_slug(root, info, slug): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .get(slug=slug) ) def resolve_posts_by_author(root, info, … -
Nginx is breaking While showing images
I have high quality images which I want to show on my web page. But whenever am running with nginx the django project breaks after some time when pages are loading. I have checked all the file paths and images are loading in django without nginx Tried to run in django was running bbut whenever nginx is configured webpage is breaking -
A task using django/heroku scheduler do nothing
I have used heroku to deploy using python-django. Following heroku documentation, i installed scheduler, create a python scrypt(tarefas.py), but nothing happened. the log show status 0. this is the heroku help answer: Anuj Pandey 20 hours ago Hi Carlos, The status 0 signifies that the entire process is completed and everything worked fine. As logs also show your tarefas.py and python tarefa2.py are executing completely. The issue seems to be with the code you have pushed, this appears to be an issue that falls outside the nature of the Heroku Support policy. I recommend searching our Help Center or asking the community on Stack Overflow for more answers. Regards, Anuj Pandey tarefas.py: import smtplib import email.message import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ERP.settings') def EnviarEmailTeste(): texto = '<h1>Teste de agendamento de tarefas a cada 10 minutos</h1>' msg = email.message.Message() msg['Subject'] = 'Teste de agendamento de tarefas' msg['From'] = '*****' msg['To'] = '****' password = '****' msg.add_header('Content-Type','text/html') msg.set_payload(texto) s = smtplib.SMTP('smtp.gmail.com: 587') s.starttls() s.login(msg['From'],password) s.sendmail(msg['From'],[msg['To']],msg.as_string().encode(('utf-8'))) s.quit() context = 'email enviado com sucesso.' return context my heroku scheduler: Job Dyno Size Frequency Last Run Next Due $ python tarefas.py Standard-1X Every 10 minutes October 17, 2023 11:32 AM UTC October 17, 2023 11:42 AM UTC … -
Guest checkout business logic for server/database with Stripe
I am making an a simple app which allows users to post ads to the website for a fee, as in pay per post. No account is required, it is in essence a guest checkout by default. The issue I am dealing with is the order and best way to implement the business logic on the server side. My flow is as follows: (Front end) User fills out a form with ad details (Front end) User hits submit (Back end) Post request is processed, new database entry is created (Back end) User is redirected to Stripe checkout Payment fails or succeeds Notice how in this flow I create an object/entry in my database before any payment has been made. This already feels wrong because I feel the entry shouldn't exist unless it has been paid for. Because spammer could in theory fill my database with endless entries by filling the form and not completing payment. So if Stripe payment fails in step 5, I have a choice: delete the entry, or return the user to the form prefilled. Clearly, the later is the better option, however if the user never finishes or fixes the payment I will still have a … -
Python Request save cookie response in browser
i have a django web app that use request to post to my gofiber api in response it get a session cookie i need that session cookie in my js fetch in the frontend but my request does not set the cookie in the browser def login(request): email = "" password = "" if request.method == 'POST': session = requests.Session() email = request.POST['email_test'] password = request.POST['password'] email = "test@test.com" password = "Test" url = "http://localhost:8006/auth/login" myobj = {'email': email, "password": password} x = session.post(url, json=myobj) if x.status_code == 200: print(x.cookies) session_cookies = dict(x.cookies) request.session['session_id'] = session_cookies print("Session cookies: " + str(session_cookies)) print(session_cookies) return HttpResponseRedirect(reverse("index")) return HttpResponse("Login failed") return render(request, "webadmin/login.html", { "email": email, "password": password }) print(x.cookies) <RequestsCookieJar[<Cookie kronborg_id=3f6be328-c4e1-4faf-a26b-7b04bc48d006 for localhost.local/>]> print(session_cookies) {'kronborg_id': '3f6be328-c4e1-4faf-a26b-7b04bc48d006'} -
How can I combine three docker images running on different ports to a single docker image
I am trying to create a Docker setup with multiple services including Django, Next.js, and Nginx, where Nginx serves as a reverse proxy for both Django (backend) and Next.js (frontend) applications. I want it to work in such a way that these 3 images are combined into one image for deployment. I have tried to used the multi-staged docker build, but i can't get the configuration right. PROJECT FILES: ./schoolduo-backend/Dockerfile.prod: ########### # BUILDER # ########### # pull official base image FROM python:3.11.4-slim-buster as builder # set work directory WORKDIR /usr/src/schoolduo-backend # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install system dependencies RUN apt-get update && \ apt-get install -y --no-install-recommends gcc # lint RUN pip install --upgrade pip RUN pip install flake8 COPY . /usr/src/schoolduo-backend/ RUN flake8 --exclude env --ignore=E501,F401 . # install python dependencies COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/schoolduo-backend/wheels -r requirements.txt ######### # FINAL # ######### # pull official base image FROM python:3.11.4-slim-buster # create directory for the app user RUN mkdir -p /home/app # create the app user RUN addgroup --system app && adduser --system --group app # create the appropriate directories ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME RUN … -
How to create index condition on boolean field with `is`
When I create a composite index with condition like this class Meta: indexes = [ models.Index( name="test_boolean_idx", fields=["field1", "field2"], condition=Q(field2=False), ), ] the resulting SQL gives CREATE INDEX ON table (field1, field2) WHERE NOT field2; Trouble is this index is not used when filtering by SELECT * FROM table WHERE field2 IS false; only for SELECT * FROM table WHERE field2 = false; I can work around by creating an index manually with WHERE field2 is false Is there a way to create such an index condition with Django models? -
QuerySet when you have an instance
I have a query set which filters a resource based on whether a user has access to it or not: resources = Resource.objects.user_access(user).all() Let's say I have a single resource instance already. Should I then implement a property in my Resource model with the same logic as in my user_acesss Query Set. where I again check if they has access? Like this: resource.has_user_access(user) I suppose I'm conscious of the fact that I'm repeating the logic that checks if the user has access in two places. If I were to put that logic into its own method, I guess it would be a static method in the Resource class. -
Django routing integration with React
We have a Django React project. we are already in the step that when user enters home URL, the app will show(Django response the react project and the home page) and also my React Routing is working(im using React-router-dom for routing). i also know that react routing and Django routings are different and separately. now my problem is if someone(client) enters any other URL than homepage URL for example someone bookmarked a "example.com/shop" and so many others like this that they are not homepage URL, Django side question: how could django has to find out the client dont have react and send the application (my react app)to it in every URL. React side question: for example user in the example.com/shop and Django send the react to client but react how can find out whitch page is the rout we do R&D about the routing but everything is all about the homepage, but there is no other pages or when user bookmarked something else than homepage.... we also watches the courses for integration but they also working on just homepage... -
django.urls.exceptions.NoReverseMatch: 1 pattern(s) tried: ['link/edit/(?P<pk>[0-9]+)/\\Z']
I am trying to use Django with HTMX. My task is to do editable row in the link list with HTMX. When I click the edit button in the row, I am getting NoReverseMatch error. raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'link_update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['link/edit/(?P[0-9]+)/\Z'] [17/Oct/2023 12:54:42] "GET /link/edit/97/ HTTP/1.1" 500 118059 I've tried so many methods on stackoverflow but I didn't figure it out. Here my code is: # urls.py in my project urlpatterns = [ path('', home, name='home'), path('admin/', admin.site.urls), path("user/", include("user_profile.urls", namespace="user")), path("link/", include("link.urls", namespace='link')), ] # urls.py in my link app from django.urls import path from link.views import tag_view, category_view, delete_links, delete_link, get_row_view, LinkUpdateView, LinkyListView app_name = 'link' urlpatterns = [ path('edit/<int:pk>/', LinkUpdateView.as_view(), name='link_update'), path('edit/<int:pk>/get_row_view/', get_row_view, name='get_row_view'), path('tag/<slug:tag_slug>/', tag_view, name='tag_view'), path('category/<slug:category_slug>/', category_view, name='category_view'), path('delete/', delete_links, name='delete_links'), path('delete-item/<int:pk>/', delete_link, name='delete_link'), path('list', LinkyListView.as_view(), name='link_list_view'), ] # views.py in my link app def get_row_view(request, pk): link = LinkUrl.objects.get(pk=pk) context = dict( link=link, ) return render(request, 'link/row.html', context) class LinkUpdateView(UpdateView): model = LinkUrl form_class = LinkModelForm template_name = 'link/edit_link_form.html' def get_success_url(self): return reverse_lazy('link:link_update', kwargs={'pk': self.object.pk}) row.html <tr id="link_list_{{link.pk}}"> <td>{{ link.title }}</td> <td>{{ link.get_full_url }}</td> <td> <span class="p-1 border fs-12 rounded text-light bg-primary"> <a … -
Why can't my terminal use the command "django-admin"(my system is windows and I have added path to the environment)
My terminal and cmd cannot identify the command "django-admin" in any folders. However, when I use the terminal inside pyCharm, it functions normally. Can someone help me with the problem and explain why it happens? Thanks a lot. I have added paths to my environment. enter image description here But it didn't help. -
Uploading file directly to Google Cloud Document AI
I am trying to upload a file directly to Google Cloud Document AI for processing. I am receiving the error 400 Request contains an invalid argument. [field_violations { field: "raw_document.content" description: "Inline document content must be provided." My code: def upload(request): template_name = "upload.html" # if this is a POST request we need to process the form data if request.method == "POST": # create a form instance and populate it with data from the request: form = UploadReceiptForm(request.POST, request.FILES) if form.is_valid: docai_client = documentai.DocumentProcessorServiceClient( client_options=ClientOptions( api_endpoint=globals.GOOGLE_CLOUD_DOCUMENT_AI_ENDPOINT ) ) # The full resource name of the processor version, e.g.: # `projects/{project_id}/locations/{location}/processors/{processor_id}/processorVersions/{processor_version_id}` name = docai_client.processor_version_path( globals.GOOGLE_CLOUD_PROJECT_ID, globals.GOOGLE_CLOUD_DEFAULT_LOCATION, globals.GOOGLE_CLOUD_DEFAULT_PROCESSOR_ID, globals.GOOGLE_CLOUD_DEFAULT_PROCESSOR_VERSION_ID ) # Configure the process request image_content = request.FILES["file"].read() request = documentai.ProcessRequest( name=name, raw_document=documentai.RawDocument(content=image_content, mime_type="image/jpeg"), ) result = docai_client.process_document(request=request) # redirect to a new URL: return HttpResponseRedirect("/upload/") # if a GET (or any other method) we'll create a blank form else: form = UploadReceiptForm() return render(request,template_name, {"form": form}) Thanks in advance for the help! -
how to make query in django pytest test user
I have a django code which is for reset password and if user is authenticated the process goes on as change password. I write a test in pytest for this code, and i use a test user to auth and check change password stage, in code for process we need user national id and when user is already online we take national id from profile. so is provided national id in test user as well but the problem is that it's not wrking and my test user not return national id. does anybody has any idea whats problem? andis this any oher way to make test user for this test. views.py @method_decorator(csrf_protect, name='dispatch') class ResetPassword(APIView): permission_classes = (permissions.AllowAny, ) try: # read input nid = request.data.get('nationalId') #....take more input to conside stage based on them .... if not request.user.is_anonymous and request.user.is_authenticated: user = request.user nid = user.profile.identity_number tests.py @pytest.fixture def test_user_nid(): user = User.objects.create_user( username="8835246563", password="upass123", ) profile = Profile.objects.update(user=user, identity_number="8835246563") return user @pytest.mark.django_db class Test: def test_change_password_stages(self, api_client, test_user_nid): api_client.force_authenticate(user=test_user_nid) print("User ID:", test_user_nid2.id) print("User Profile Identity Number:", test_user_nid2.profile.identity_number) data = { "tfaCode": 12345 } response = api_client.post(self.url, data, format='json') # assert response.status_code == status.HTTP_200_OK response_data = response.json() print(">>>>", response_data) … -
Monthly Celery Beat task also runs after celery restart
I have a task that is set to run on the first day of every month at 05:00 using celery beat. It has been set as follows in settings.py: CELERY_BEAT_SCHEDULE = { 'generate_monthly_reports': { 'task': 'api.tasks_reports.generate_monthly_reports', 'schedule': crontab(minute=0, hour=5, day_of_month=1) }, } This works well and runs reliably. However, I have recently discovered that it is also run whenever Celery is restarted, e.g. when a server code update is made and celery restarted via supervisor. I am using Celery 5.2.6, Python 3.8 and Django 4.0.4. How can I prevent this task running when Celery is restarted please? -
Deploy python django project on cyberpanel at hostinger using openlitespeed
I am trying to Deploy python django project on cyberpanel at hostinger using openlitespeed. I have setup all things but i am facing the 503, service unavailable error, My WSGI Script is runnig fine when i test it alone in a different directory. docRoot $VH_ROOT/public_html vhDomain $VH_NAME vhAliases www.$VH_NAME adminEmails aristonvillagepizza@gmail.com enableGzip 1 enableIpGeo 1 index { useServer 0 indexFiles index.php, index.html } errorlog $VH_ROOT/logs/$VH_NAME.error_log { useServer 0 logLevel WARN rollingSize 10M } accesslog $VH_ROOT/logs/$VH_NAME.access_log { useServer 0 logFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"" logHeaders 5 rollingSize 10M keepDays 10 compressArchive 1 } scripthandler { add lsapi:arist7587 php } extprocessor arist7587 { type lsapi address UDS://tmp/lshttpd/arist7587.sock maxConns 10 env LSAPI_CHILDREN=10 initTimeout 600 retryTimeout 0 persistConn 1 pcKeepAliveTimeout 1 respBuffer 0 autoStart 1 path /usr/local/lsws/lsphp81/bin/lsphp extUser arist7587 extGroup arist7587 memSoftLimit 2047M memHardLimit 2047M procSoftLimit 400 procHardLimit 500 } phpIniOverride { } module cache { storagePath /usr/local/lsws/cachedata/$VH_NAME } rewrite { enable 1 autoLoadHtaccess 1 } context /.well-known/acme-challenge { location /usr/local/lsws/Example/html/.well-known/acme-challenge allowBrowse 1 rewrite { enable 0 } addDefaultCharset off phpIniOverride { } } vhssl { keyFile /etc/letsencrypt/live/aristonvillagepizza.uk/privkey.pem certFile /etc/letsencrypt/live/aristonvillagepizza.uk/fullchain.pem certChain 1 sslProtocol 24 enableECDHE 1 renegProtection 1 sslSessionCache 1 enableSpdy 15 enableStapling 1 ocspRespMaxAge 86400 } context / … -
Django proxy-model returning wrong ContentType
Let's say we have a model Company and subtype Client like so: class Company(models.Model): name = models.CharField(max_length=100) related_companies = models.ManyToManyField('self', symmetrical=True) is_customer = models.BooleanField(default=False) class ClientManager(Manager): def get_queryset(self): return QuerySet(self.model, using=self._db).filter(is_customer=True) class Client(Company): objects = ClientManager() class Meta: proxy = True Next you go into CLI, create an instance and fetch its content-type from django.contrib.contenttypes.models import ContentType In[38]: company = Company.objects.create(name='test', is_customer=True) In [39]: ContentType.objects.get_for_model(c) Out[39]: <ContentType: contacts | company> That returns the concrete model for the company class. So far so good. Next, according to the docs, the follows should return the Client content-type. In [40]: ContentType.objects.get_for_model(c, for_concrete_model=False) Out[40]: <ContentType: contacts | company> Yet, it does not. I'm still receiving the concrete model Company instead of Customer Do you see my mistake? -
Unable to generate Models using InspectDB
I am using Django inspectdb to auto generate models from an existing mongodb database deployed on the cloud. It was configured using NodeJS and now client wants to change it to Django. In my settings.py, I have: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'dbname', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'mongodb+srv://string' } } } When I run python manage.py inspectdb, I get the following error for each table: # The error was: 'NoneType' object is not table_name # Unable to inspect table 'table_name' I have the following packages installed in my virtualenv: Package Version ----------------- ------------ asgiref 3.7.2 Django 4.1.12 djongo 1.3.6 dnspython 2.4.2 pip 23.2.1 pymongo 3.12.3 pytz 2023.3.post1 setuptools 68.2.2 sqlparse 0.2.4 typing_extensions 4.8.0 wheel 0.41.2