Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter two different columns values together in filter query Django?
I have two columns, For single amount value amount and for range amount values amount_min and amount_max amount amount_min amount_max 25000 0 0 0 100000 300000 Using the following queries, Why it's not showing any of the records ? Jobs.objects.filter(amount_min__gte = 100000, amount_min__lte = 100000, amount_max__gte = 300000, amount_max__lte = 300000,amount__range=(100000, 300000)) and Jobs.objects.filter(amount_min__gte = 10000, amount_min__lte = 10000, amount_max__gte = 50000, amount_max__lte = 50000,amount__range=(10000, 50000)) Can anyone please help me in this query ? -
How can I make themes inside my Django app which can be deployed as well?
What I want is to add a multiple sets of images(themes) and they randomly get allotted to a decision (which is a model in my app) as soon as I create one. I want to display the allotted image on the decision.html, it will always have the same image from then. I want to assign 2 colors and 1 image in each image_set(theme) and while the creation of decision, the decision randomly gets one image_set. It is like changing the color of some of the buttons on the decision.html based on the image that has been allocated to the decision which is currently being seen. And I myself will assign the images and colors of an image_set(not a CRUD setup for any user to upload), somewhere like what color which button will receive associated with the image. It is not that a user will upload images. I want to assign somewhere that image_set_1 has this image, and has 2 colors assigned with every image_set. Then to get image and color from the image_set, and the image_set will get the image from some folder and the same set of images to work in the deployed version as well. please suggest me … -
Django 'NoneType' object has no attribute '_prefetch_related_lookups' disappears after reboot
I am having an intermittent issue with my Django web app where the error above appears every few days on one of my forms. Restarting the webserver resolves the issue and I am at a loss of what is going on. I have other views with similar code that don't have the same problem. I am using django.db.backends.sqlite3 as the database. The form basically collects a bunch of data and on submission goes to another page to generate a PDF using the values entered. It's failing trying to bring up the form. views.py def generate_correspondence_form(request, file_id): file = File.objects.get(id=file_id) if request.method == 'POST': placeholderform = CorrespondencePlaceholderForm(request.POST) correspondenceform = GenerateCorrespondenceForm(request.POST) if correspondenceform.is_valid() and placeholderform.is_valid(): request.session['a'] = list(placeholderform.cleaned_data.get('a').values('id')) request.session['b'] = list(correspondenceform.cleaned_data.get('b').values('id')) request.session['c'] = correspondenceform.cleaned_data.get('c') request.session['d'] = correspondenceform.cleaned_data.get('d').id request.session['e'] = correspondenceform.cleaned_data.get('e') request.session['f'] = correspondenceform.cleaned_data.get('f') request.session['g'] = correspondenceform.cleaned_data.get('g') request.session['h'] = correspondenceform.cleaned_data.get('h') request.session['i'] = correspondenceform.cleaned_data.get('i') if correspondenceform.cleaned_data.get('j'): request.session['j'] = correspondenceform.cleaned_data.get('j').id if request.POST.get('submit_ashtml'): url = f"{reverse('logs:generate_correspondence', kwargs={'file_id': file_id})}?as=html" return redirect(url) else: return redirect('logs:generate_correspondence', file_id=file_id) else: placeholderform = CorrespondencePlaceholderForm() correspondenceform = GenerateCorrespondenceForm() placeholderform.fields['a'].queryset = A.objects.filter(target__file=file) correspondenceform.fields['b'].queryset = B.objects.filter(file=file) context = {'correspondenceform': correspondenceform, 'placeholderform': placeholderform, 'file': file} return render(request, 'logs/generatecorrespondenceform.html', context) -
Question from a total beginner, how do i run a django project on my browser using windows operating system?
I have trouble running a django project on my browser using windows operating system. I tried running the command "py -m manage runserver" on the terminal but instead this happens; Screenshot of the window -
No matching distribution found for django on Window 11
I am new to windows, have been a Macbook user for years. I need to setup an existing project on Windows 11. I have installed python, pip, pipenv and pyenv. I have activated a shell to run the following command: pipenv install --dev Result ERROR: No matching distribution found for django Seems pipenv can not find any of the distributions at all. Not just Django. How can I resolve this? -
Verify token coming from frontend in DJANGO using AUTH0
from django.contrib.auth.backends import BaseBackend from accounts.models import User from urllib.request import urlopen import json from authlib.jose import jwt from authlib.jose.errors import JoseError from authlib.oauth2.rfc7523 import JWTBearerTokenValidator from authlib.jose.rfc7517.jwk import JsonWebKey from authlib.oauth2.rfc6750 import BearerToken class Auth0JWTBearerTokenValidator(JWTBearerTokenValidator): def __init__(self, domain, audience): issuer = f"https://{domain}/" jsonurl = urlopen(f"{issuer}.well-known/jwks.json") public_key = JsonWebKey.import_key_set( json.loads(jsonurl.read()) ) super(Auth0JWTBearerTokenValidator, self).__init__( public_key ) self.claims_options = { "exp": {"essential": True}, "aud": {"essential": True, "value": audience}, "iss": {"essential": True, "value": issuer}, } def validate_token(self, token, scopes, request): # Overriding the validate_token method claims = super().validate_jwt(token) return claims class Auth0AuthenticationBackend(BaseBackend): def authenticate(self, request, token): domain = "domain" audience = "audience" validator = Auth0JWTBearerTokenValidator(domain, audience) try: # token_obj = BearerToken(token, None) claims = validator.validate_token(token, [], request) auth_id = claims["sub"] except JoseError: return None try: user = User.objects.get(auth_id=auth_id) except User.DoesNotExist: user = User.objects.create( auth_id=auth_id, name=claims["name"], email=claims["email"] ) return user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None So this is my authentication.py code in which I am creating a user in the backend to allow other models to be tied with the user. And I am trying to set up auth0 such that it receives the token from the frontend, and I have the permissionClasses =[isAuthenticated] on my views so it … -
Filter through 3 nested forloops in django
I am trying to filter through 3 nested forloops and having 2 problems. My first problem is that I cannot find a way to only show child loop objects in relations to parents loop object id. In my example below, I want to show all the B objects (child) for each A objects (parent). My second problem is that I want to filter the last loop and only show the latest child object in each parent category. I have seen a few solution on this forum calling set.all but no success for me. I think my problem here is that there is no direct relation between the model in loop 2 and 3, and I am not sure how to address the "indirect relation". Essentially I am trying the render the following: without filters | C| A| B| |:---- |:------:| -----:| | objectC1| objectA1| objectB1| |objectC1 | objectA1| objectB2|| |objectC1 | objectA2| objectB3|| with filters | C| A| B| |:---- |:------:| -----:| | objectC1| objectA1| objectB1| | | Two | objectA2|objectB3| class A(models.Model, HitCountMixin): name = models.CharField(verbose_name="Name",max_length=100, blank=True) class B(models.Model): user = models.ForeignKey(UserProfile, blank=True, null=True, on_delete=models.CASCADE) venue = models.ForeignKey(A, blank=True, null=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) class C(models.Model): title … -
Bootstrap’s cards. How to make fixed card size with many words in it. Django & CSS
I am using the Bootstrap's card to display my journals. It looks like this: Journal List However, when I insert a lot of word, the card size will be veryyyy long. Journal List With really long essay How to make it when there are long essays, it will shown like this: Today is a good day. I started my day with coding. However, I found out that I ... Make it like "..." This is the html code: <div class = "container mt-4 mb-4"> <div class="center_journal"> <div class="col"> <div class="row"> {% for journal in journals %} <div class="card d-flex flex-column col-4 " style="width: 36rem;"> <h5 class="card-title text-center mt-4"><a href="{% url 'journal_detail' journal.id %}" >{{ journal.title }}</a></h5> {% if journal.photo %} <img src="{{ journal.photo.url }}" class="card-img-top" alt="..."> {% endif %} <div class="card-body"> {% if journal.audio %} <audio controls> <source src="{{ journal.audio.url }}" type="audio/ogg"> <source src="{{ journal.audio.url }}" type="audio/mpeg"> <source src="{{ journal.audio.url }}" type="audio/wav"> Your browser does not support the audio element. </audio> {% endif %} <p class="card-content text-center">{{ journal.content }}</p> <p class="text-center font-weight-light">Created on {{ journal.date_created|date:'Y-m-d H:i' }}</p> {% if journal.favourite %} <div class="text-center font-weight-light"> <p>Added to Favourite!</p> </div> {% endif%} <!-- <div class="text-center"> <a href="{% url 'journal_detail' journal.id %}" ><button … -
Django save data accross several signals: m2m_changed
I need testers and engineers to be notified when they're added to a given a model like this: Class Foo(models.Model): engineer = models.ManyToManyField(User, related_name='foo_engineer') tester = models.ManyToManyField(User, related_name='foo_tester') ... Note that it's possible that a User could be both a tester and an engineer. So I have this: def personell_change(sender, **kwargs): if kwargs.get('action') == 'post_add': added = kwargs.get('pk_set') notify_added() m2m_changed.connect(personell_change, sender=Foo.engineer.through) m2m_changed.connect(personell_change, sender=Foo.tester.through) This works, but if the tester and the engineer were the same User, then notify_added() is run twice, which is not ideal. So the question: Is there any way to store the results of the signals until all of them have run? I suppose I could use a pre_save signal to build something to hold the values, and a post_save signal to act on them, but that seems like a bad idea. -
Can we create database, add configuration in settings file in Django testcase and after testcase run, drop database and remove configurations?
Actually, I have an API endpoint in Django, in which I am running a script that creates database on runtime and add configurations in settings file. When I wrote testcase for that endpoint, It throws the following error while tearing down the testcase. ERROR: tearDownClass (tenants.tests.test_apis.test_tenant_apis.TenantCreationTests) Traceback (most recent call last): File "/home/dev/Documents/MUSEAPI/muse-api/venv/lib/python3.8/site-packages/django/test/testcases.py", line 372, in _remove_databases_failures setattr(connection, name, method.wrapped) AttributeError: 'function' object has no attribute 'wrapped' Below is the script, I am using for database configuration import json import environ import psycopg2 from django.conf import settings from django.core.management import call_command env = environ.Env( DEBUG=(bool, False) ) environ.Env.read_env() def configure_db_script(db_name): db_configuration = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': db_name, 'USER': env('DATABASE_USER'), 'PASSWORD': env('DATABASE_PASSWORD'), 'HOST': env('DATABASE_HOST'), 'PORT': env('DATABASE_PORT'), } db_configuration1 = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': db_name, 'USER': env('DATABASE_USER'), 'PASSWORD': env('DATABASE_PASSWORD'), 'HOST': env('DATABASE_HOST'), 'PORT': env('DATABASE_PORT'), 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'CONN_HEALTH_CHECKS': False, 'OPTIONS': {}, 'TIME_ZONE': None, 'TEST': { 'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': None } } default_connection = psycopg2.connect( database='postgres', user=env('DATABASE_USER'), password=env('DATABASE_PASSWORD'), host=env('DATABASE_HOST'), port=env('DATABASE_PORT'), ) settings.DATABASES[db_name] = db_configuration1 with default_connection.cursor() as cursor: default_connection.autocommit = True cursor.execute(f'CREATE DATABASE {db_name}') with open('settings.py', 'r') as f: data = f.readlines() with open('settings.py', 'w') as f: for line in data: if line.startswith('DATABASES'): db_json = … -
Issue with @login_required function in Django
I'm receiving an error when trying to use the login_required function. I'm receiving a TemplateDoesNotExist at /accounts/login/ registration/login.html Error. While I have no directory Registration, I have my templates in a folder, templates. I have a login.html template which works fine for the login page. This is the view`I'm using the login_required function on @login_required(login_url='signin') def buy_crypto(request): if request.method == 'POST': currency = request.POST.get('currency') amount = Decimal(request.POST.get('amount')) price_per_unit = Decimal(request.POST.get('price_per_unit')) purchase = CryptoPurchase(user=request.user, currency=currency, amount=amount, price_per_unit=price_per_unit) purchase.save() return redirect('index') else: return render(request, 'buy_crypto.html') My url patterns for User Authentication are in a seperate app in the same project. This app is called accounts. Here's the accounts/urls.py file from django.urls import path from cryptoapp import views from .views import signupView, signinView, signoutView urlpatterns = [ path('create/', signupView, name='signup'), path('login/', signinView, name='signin'), path('signout/', signoutView, name='signout'), ] If you need any further code please let me know ! Any help would be greatly appreciated ! -
best realtime Web framework
Which backend framework is best suited for sending location data from mobile app to website in realtime. I am a beginner in web development and trying to build a real time system, I was told that django is good for learning curve , but node js is good for realtime system, please help me in suggesting the correct framework, -
Django QR code send inline via email is not showing in body
I am trying to send a QR Code to email and have it display inline within the email body. The email is sent successfully, The attachment currently works and displays as expected but the png within the body is showing as a ? and looks like this: In my view I have the following function defined. def send_qr_code_email(to_email, qr_code_data): # Generate QR code image qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr.add_data(qr_code_data) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white") # Convert image to bytes and attach it to the email message buffer = BytesIO() img.save(buffer, 'PNG') image_data = buffer.getvalue() image_filename = 'qr_code.png' data_uri = 'data:image/png;base64,' + base64.b64encode(buffer.getvalue()).decode('ascii') src = 'data:image/png;base64,{0}'.format(data_uri) email = EmailMessage( 'QR Code', render_to_string('Templates/email.html', {'qr_code_data': qr_code_data, 'src': src}), settings.DEFAULT_FROM_EMAIL, [to_email], reply_to=[settings.DEFAULT_FROM_EMAIL], ) email.content_subtype = "html" email.attach(image_filename, image_data, 'image/png') # Send the email email.send(fail_silently=False) and this is my email.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>QR Code</title> <style> .qr-code-container { display: inline-block; border: 1px solid #ccc; padding: 10px; background-color: #fff; box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1); } .qr-code-container img { display: block; margin: 0 auto; max-width: 100%; } .qr-code-container p { margin: 10px 0; font-size: 14px; line-height: 1.5; } </style> </head> <body> <div class="qr-code-container"> <p>Here is your QR code:</p> … -
How can i use function from another function in Django views.py?
there is global parameter sentence, ascii_sentence, cearsar_sentence, caesar_shift here is my views.py def random_string(request): global sentence sentence = " ".join(random.sample(words.words(),random.randint(7,10))) cearsar_sentence = caesar_encryp(sentence) return render(request, 'caesar.html',{'sentence':sentence},{'cearsar_sentence':cearsar_sentence}) def caesar_encryp(sentence): (blah blah) return ceasar_sentence while i call caesar_encryp in random_string. somthing unknown problem occurred. when i click ramdom_string button. there's no error message. just my code script showed in web page. but when i delete all the 'cearsar' codes. i does work well. so i'm pretty sure function in function use is wrong. how can i use function caesar_encryp in random_string? i saw similar question in stackoverflow. and the answer said Django view have to need request so i've tried the bottom code def random_string(request): cearsar_sentence = caesar_encryp(request) return render(request, 'caesar.html',{'sentence':sentence},{'cearsar_sentence':cearsar_sentence}) def caesar_encryp(request): (blah blah) return ceasar_sentence but also doesn't work. please help me. -
Adding to the Django registration form confirmation of registration by mail and phone number
Good afternoon, please tell me how to add registration confirmation points to my Django registration by phone number and by mail. Code and sequence below: The essence should be as follows: Filling out the registration form => Sending the code to the mail and sending the code to the phone number => Redirecting from the registration page to the page for entering the code from the mail => If the code does not fit, redirecting to the same page for entering the code from the mail , but with an error that the code is not suitable, if the code is suitable, then redirect to the page for entering the phone number => If the code is suitable, then redirect to the main page, if not, then redirect to the page to enter the code from the phone number only with a warning that the code is not suitable views.py: from django.shortcuts import render, redirect from .forms import CustomUserCreationForm from django.contrib.auth import login, authenticate def register(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('home') else: form = CustomUserCreationForm() return render(request, 'account/registration.html', {'form': form}) models.py: from django.db import models from django.contrib.auth.models import AbstractUser … -
Django - k8s - django.db.utils.OperationalError - redis.exceptions.ConnectionError - requests.exceptions.ConnectionError
I'm running a django + postgrsq/pgbouncer + redis project on Kuerbenetes (OVH public cloud) Each on their own pod and I sometimes encounter this kind of error django.db.utils.OperationalError: could not translate host name "pgbouncer" to address: Try again redis.exceptions.ConnectionError: Error -3 connecting to redis:6379. Try again. requests.exceptions.ConnectionError: HTTPConnectionPool As if Django pod sometimes lost connection with the other pods (redis / pgbouncer or other services we use) I mainly happens if I send concurrency requests (not a lot) and it is very random Pods are declared as type: ClusterIP on the default namespace and I access them from Django using their service name I put below the config for Redis/Django-rq as an example but not sure it will help as it happens for any other services used by Django. Django settings.py RQ_QUEUES = { 'default': { 'HOST': 'redis', 'PORT': 6379, 'DB': 0, }, } redis yaml file apiVersion: v1 kind: Service metadata: name: redis labels: app: redis spec: type: ClusterIP ports: - port: 6379 targetPort: 6379 protocol: TCP name: http selector: app: redis --- apiVersion: apps/v1 kind: Deployment metadata: name: redis labels: app: redis spec: selector: matchLabels: app: redis template: metadata: labels: app: redis spec: restartPolicy: Always containers: - name: … -
Python/Django - Stream operation responses as received in one StreamingHttpResponse
I am making a number of calls to boto3 head_object operation in a for loop, after getting the list of keys from a list_objects_v2 call. I am wondering, is there anyway to return the json chunk from each head_object call as soon as I get it, as part of a single overall StreamingHttpResponse object? streamed_response = StreamingHttpResponse([]) keys = s3.list_objects_v2(Bucket=bucket) for key in keys['Contents']: metadata = s3.head_object(Bucket=bucket, Key=key['Key'])['Metadata'] # Add to streamed_response and return Is there a way to add the each metadata response to streamed_response and immediately return that chunk of json? -
using One databse in two different projects
I have create a custom admin panel in Django, where admin is able to register a new user, now I want that i should use that same database in user panel and login user by checking that user table in the database user cannot register himself from the user panel he has to send his detail to the admin and then admin will provide him login credentials i was mention that same database in my user pane setting.py I tried to makemigrations for the same but i got some error's over there -
How to set an advanced one time sms code in Django app
I have sms autentication in my Django app. I works right. But I want to use a recomendations from https://github.com/WICG/sms-one-time-codes So, instead of 4 digits code I want user to get smth like this: https://example.com, 747723, 747723 is your ExampleCo authentication code ** "https://example.com" is the origin the code is associated with, "747723" is the code, and "747723 is your ExampleCo authentication code.\n\n" is human-readable explanatory text. services.py from pyotp import HOTP from django.db.models import F from types import SimpleNamespace fake_response = SimpleNamespace(status_code=200, code=0) def send_sms(phone: int, totp_code: str) -> int: data = { "api_id": settings.SMS_API_KEY, "to": phone, "text": totp_code, "from": "my_django_app.ru", } if not settings.AUTH_CODE_TO_SMS: response = fake_response else: response = requests.post("https://sms-sender.com", data) return response.status_code def make_totp(user: User) -> str: totp = HOTP(user.otp_secret, digits=4) totp_code = totp.at(user.otp_counter) return totp_code def totp_verify(user: User, totp_code: str, verify=None) -> bool: if user: totp = HOTP(user.otp_secret, digits=4) verify = totp.verify(otp=totp_code, counter=user.otp_counter) if verify: user.otp_counter = F("otp_counter") + 1 user.save() return verify Any suggestions how to solve this problem? -
Django Ajax updated Table loosing sortable function
I'm using this plugin to make my HTML table sortable and it works great. <script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script> You can call it by adding sortable in the table class <table id='myTable' class="table table-striped table-hover table-bordered fixed_header sortable"> But when I'm updating the table with AJAX after filtering, the table looses the sortable functionality. Do I have to re-import the script somewhere ? I have tried to place it in my home.html page and of course in my filter.html page which is rendered after the Ajax call. Thanks -
Django form.is_valid() False
I'm trying to create custom user authentication using any of email/phone to login. When I use email it goes fine, but when I'm trying to enter with phone number nothing happens. Error appears in views.py (form is not valid): def login_request(request): user = request.user if user.is_authenticated: return redirect("account:home") if request.method == "POST": form = AccountAuthenticationForm(request.POST) print('line 28 views', request.POST) **print('line 29 views', form.is_valid()) ** if form.is_valid(): email = request.POST['email'] print('line 31 email:', email) password = request.POST['password'] user = authenticate(username=email, password=password) #or authenticate(phone=email, password=password) if user: login(request, user) print('fine') return redirect("account:home") else: print(user, 'line38') form = AccountAuthenticationForm() return render(request, "account/login.html", {"login_form": form}) models.py class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("email address"), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) first_name = models.CharField(max_length=20, null=True, blank=True) last_name = models.CharField(max_length=20, null=True, blank=True) phone = PhoneNumberField(unique=True, null=True, blank=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email forms.py class AccountAuthenticationForm(forms.ModelForm): password = forms.CharField(label='Password', widget=forms.PasswordInput) email = forms.CharField(label='Email or phone number') class Meta: model = CustomUser fields = ('email', 'password',) def clean(self): if self.is_valid(): email = self.cleaned_data['email'] password = self.cleaned_data['password'] print('line 48', email, password) if not authenticate(username=email, password=password): raise forms.ValidationError("Invalid login") backends.py class EmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: … -
How to cancel validation check in standard Django registration view?
Good afternoon, please tell me how to cancel the standard form validation in the Django registration view, the is_valid method is responsible for this. ` from django.shortcuts import render, redirect from .forms import CustomUserCreationForm from django.contrib.auth import login, authenticate def register(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('home') else: form = CustomUserCreationForm() return render(request, 'account/registration.html', {'form': form})` I tried to remove the condition with it, so that in any case the data would be saved, but it gives an error:Exception Type: ValueError at /account/registration/ Exception Value: The CustomUser could not be created because the data didn't validate. -
docker-compose Django to access postgresql from localhost
I've a django app running with docker-compose and want it to access postgres installed on localhost here's the steps I followed: 1- added host all all 172.17.0.1/16 md5 to pg_hba.conf 2- changed listen_addresses to * in postgresql.conf 3- changed db_host to host.docker.internal 4- in docker-compose.yml added extra_hosts to the service so it looks like this services: web: extra_hosts: - "host.docker.internal:host-gateway" 5- restarted postgresql sudo systemctl restart postgresql still getting this error could not connect to server: Connection timed out Is the server running on host "host.docker.internal" (172.17.0.1) and accepting TCP/IP connections on port 5432? what am I doing wrong? -
Django project: Spam bots spam all over my Sentry.io Account (Invalid HTTP_HOST header)
I have a django project running in production with gunicorn. It is connected to sentry.io for comfortable error logging. There are a lot of spambots causing Invalid HTTP_HOST header, because they try to access it by ip, which is not allowed by django`s ALLOWED_HOSTS setting. Those Spam Bots fill up my sentry plan limits, and after a while other errors are not logged anymore. What would be a simple and elegant solution to this? I already thought about some, but they all have caveats: Filter out requests with wrong hosts in an earlier stage, e.g. the nginx - Good idea, but I would like to be able to configure allowed hosts in django settings Catch Invalid HTTP_HOST header error in django and not send to sentry: Good idea, but then I do not have invalid http host header error handling at all in sentry I would like to log one error per host and url per day or something like that - But then I have to code a custom ratelimiter, which persists infos. Seems like a complex solution What are your thought on this. Do you have other ideas? What would be the most elegant and less comlicated solution? -
django-extensions graph_models -a -I options doesn’t work
I’m using django3 and django-extensions to do a DB schema following this instructions https://medium.com/@yathomasi1/1-using-django-extensions-to-visualize-the-database-diagram-in-django-application-c5fa7e710e16. The thing is, it works when I use all the database and specifics apps but it doesn’t when I use specific modules. How can I solve this? I’m working ond django 3.2, pygraphviz 1.10 and django_extensions 3.2.1