Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python django-oauth-toolkit client_credentials allows anything to go through and doesn't add user to the token
I'm using django-oauth-toolkit and I can't figure out why when I use client_credentials, I can literally insert any username/password combo and they always return a token even if the username/password combo is nowhere in the database. This is my postman request body: On the admin portal, I don't even see the user selected under "user": How do I only allow valid username/password combos to return an access token and how do I attach a user to an access token? -
Can we send form data picked up by Javascript from a html doc to Django views.py file ? If so what are the methods?
I need to pickup the data entered in a form in a HTML document using javascript and perform some operations on it and then send it to Django in the back-end to store the data in the Database. What are the ways/methods by which I can do the above scenario? I heard that we can use an Ajax call to do the described problem, but is there any other easy/secure method to do it? -
Connect my Flutter Mobile App to backend from my laptop with same internet connections
ClientException with SocketException:connection failed(OS Error: Permissio Denied,errno = 13),address = 192.168.43.155, port = 8000, uri=http://192.168.43.155:8000/api/login/ im facing this when i tried to run flutter app from mobile and connect to backend from my laptop what im going to do? -
Django AssertionError GraphQL
I have an error on my GraphQL instance, I load the /graphql endpoint and it pops up with the below error. AssertionError: You need to pass a valid Django Model in AuthorType.Meta, received "None". My schema for each is as follows: class UserType(DjangoObjectType): class Meta: model = get_user_model() class AuthorType(DjangoObjectType): class Meta: models = models.Profile class PostType(DjangoObjectType): class Meta: model = models.Post class TagType(DjangoObjectType): class Meta: model = models.Tag I also have a Query within that schema: 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_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, username): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .filter(author__user__username=username) ) def resolve_posts_bt_tag(root, info, tag): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .filter(tags__name__iexact=tag) ) Here is the model for the blog posts: class Profile(models.Model): user = models.OneToOneField( get_user_model(), on_delete=models.PROTECT, ) website = models.URLField(blank=True) bio = models.CharField(max_length=240, blank=True) def __str__(self) -> str: return self.user.get_username() class Tag(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class Post(models.Model): class Meta: ordering = ["-publish_date"] title = models.CharField(max_length=255, unique=True) subtitle = models.CharField(max_length=255, blank=True) slug = models.SlugField(max_length=255, … -
Django export PDF directly from view
I'm wondering if it's somehow possible to process the PDF export directly in the main view, and have it triggered by a button click in the template. The reasoning is that in the main view (dispatcher_single) I have 300 lines of code of data manipulation (including charts) that I would like to export to PDF and would like to avoid having to copy/paste all this code from main view to the PDF export view. Main view with a bunch of calculations: views.py def dispatcher_single(request, pk): dispatcher = Dispatcher.objects.select_related("company", "location").get(id=pk) # data manipulation here (about 300 lines of code) context = { 'dispatcher': dispatcher 'bunch_of_other_data': data } return render(request, 'dispatchers/dispatcher-single.html', context) Another view for exporting to PDF: views.py from renderers import render_to_pdf def dispatcher_statement_form(request, pk): dispatcher = Dispatcher.objects.get(id=pk) context = { 'dispatcher': dispatcher, } response = renderers.render_to_pdf("pdf/statement_form.html", context) if response.status_code == 404: raise Http404("Statement form not found.") filename = "Statement_form.pdf" content = f"inline; filename={filename}" download = request.GET.get("download") if download: content = f"attachment; filename={filename}" response["Content-Disposition"] = content return response And the render function: renderers.py def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if pdf.err: return HttpResponse("Invalid PDF", status_code=400, content_type='text/plain') return HttpResponse(result.getvalue(), content_type='application/pdf') -
Why divs slide to the next row when setting margin, Bootstrap, Django
{% for plant in plants %} {% if forloop.counter0|divisibleby:3 %} <div class="row row-cols-3"> {% endif %} {% include 'included/_plant_cell.html' %} {% if forloop.counter|divisibleby:3 %} </div> {% endif %} {% endfor %} _plant_cell.html: <div class="plant-cell card col-md-4 m-1"> <div class="card-body"> <div class="card-text"> {{ plant.name }} </div> </div> </div> the following code results in rows that contain only two cards, and the third slides down to the next row (when margin m-1 is removed, then ok), so the general view is repeatedly row with two cards, row with one card. Expected to see rows with three cards in each. -
After submitting, data not visible on admin page
When I'm trying to submit my form, server gives me a successful GET and POST request, but when I come to the admin page it doesn't show me data from the Form. The problem is that I want to see submitted data on the admin page. I registered Model in admin.py, but still didn't help from django.contrib import admin from .models import Reservation # Register your models here. admin.site.register(Reservation) Here is my models.py from django.db import models # Create your models here. class Reservation(models.Model): name = models.CharField(max_length=100) phone_number = models.IntegerField() email = models.EmailField() reservation_date = models.DateField() reservation_slot = models.SmallIntegerField(default=10) def __str__(self): return self.email reservation.html where I trying to submit form {% extends 'base.html' %} {% load static %} {% block base%} <section> <article> <h1>Make a reservation</h1> <!--Begin row--> <div class="row"> <!--Begin col--> <div class="column"> {% csrf_token %} <form method="POST" id="form"> <!-- {% csrf_token %} --> <p> <label for="first_name">Name:</label> <input type="text" placeholder="Your Name" maxlength="200" required="" id="first_name"> </p> <p> <!-- Step 9: Part one --> <label for="reservation_date">Reservation date:</label> <input type="date" placeholder="Your reservation" maxlength="200" required="" id="reservation_date"> </p> <p> <label for="reservation_slot">Reservation time:</label> <select id="reservation_slot"> <option value="0" disabled>Select time</option> </select> </p> <button type="button" id="button">Reserve</button> </form> </div> <!--End col--> <!--Begin col--> <div class="column"> <h2>Bookings For <span … -
Poetry and Vercel issue
I have found out about Poetry recently, and I am amazed by how well it works compare to the regular pip and whatnot. But I am facing issues with when I try to host my Django app on Vercel. Since Vercel have no functionality of poetry I cannot host my django over there. I have tried chatgpt and the solution is to modify the vercel.json file which I did. { "build": { "env": { "POETRY_VERSION": "1.1.4" } }, "builds": [ { "src": "test/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } } ], "routes": [ { "src": "/(.*)", "dest": "test/wsgi.py" } ] } but then I got these errors. [ERROR] Runtime.ImportModuleError: Unable to import module 'vc__handler__python': No module named 'django' then I tried this solution text but when I followed this solution my app would not even deploy it would give error even the building part Error: Command failed: python3.9 -m poetry export --without-hashes -f requirements.txt --output requirements.txt and ImportError: urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'OpenSSL 1.0.2k-fips 26 Jan 2017'. See: https://github.com/urllib3/urllib3/issues/2168 so after exhausting everything that I could am here for help. -
multiple try/except , n etx one catch exception after first one handle it
I have 2 try except block, the second one trigger the first one exception i'm expecting that the first one handle the first exception and that the second one not trigger that exception the second try/catch block catch the exception generated in the first one unless i handle it, why ? can someone help me solve this issue ? try: if isinstance(request.data['name'],str): progetto.name = request.data['name'] progetto.save() else: raise TypeError('Validation error') except TypeError as te: print('type error catched error: ',te) errori.append({'name': str(te)}) except Exception as e: print('name catched error: ',e) errori.append({'name': str(e)}) try: progetto.expiration = request.data['expiration'] progetto.save() except Exception as ex: print('exp block catched error: ',ex) errori.append({'expiration': str(ex)}) -
Can't fill my custom user model in django with automatic script
Made a new custom django user model class UserProfile(User): phone_number = models.CharField(max_length=20, verbose_name='Номер телефона', unique=True) Trying to Automatize filling it wit information from API with this script: import requests import json from django.contrib.auth.models import User from tarifs.models import Software_Products, UserProfile url = "My API" headers = { "Content-Type": "application/json", "Authorization": "Basic ..." } subscribers = {} page = 0 size = 300 while True: data = {"page": page, "size": size} response = requests.post(url, data=json.dumps(data), headers=headers) data = json.loads(response.content) if not data.get('subscribers'): break for subscriber in data['subscribers']: code = subscriber['code'] name = subscriber['name'] subjects = subscriber.get('subjects', []) reg_numbers = subscriber.get('regNumbers', []) if reg_numbers: subscribers[name] = { 'code': code, 'name': name, 'subjects': subjects, 'reg_numbers': reg_numbers } page += 1 for name, reg_numbers_data in subscribers.items(): user_profile, created = UserProfile.objects.get_or_create(name=name) for reg_number in reg_numbers_data['reg_numbers']: software_product, created = Software_Products.objects.get_or_create( user_id=user_profile, reg_number=reg_number, defaults={'name': reg_numbers_data['name']} ) if not created: software_product.name = reg_numbers_data['name'] software_product.save() Running this script ends with this error: Traceback (most recent call last): File "c:\work\Bizstart\bizstart_django\bizstartprj\parse2.py", line 3, in from django.contrib.auth.models import User # Перенесите этот импорт в начало ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\work\bizstart\bizstart_django\bizstartenv\Lib\site-packages\django\contrib\auth\models.py", line 3, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\work\bizstart\bizstart_django\bizstartenv\Lib\site-packages\django\contrib\auth\base_user.py", line 49, in class AbstractBaseUser(models.Model): File "C:\work\bizstart\bizstart_django\bizstartenv\Lib\site-packages\django\db\models\base.py", line 127, in new app_config = apps.get_containing_app_config(module) … -
is there any solution to show data on django website
project in python and java language django website is used data store in database but not show on website and the software used is pycharm I just want to know the solution to show data on website which is store on database I tried alot of query -
Django MigrationAutodetector not detecting changes properly
I'm developing an app that must handle dynamic models creation using Django v. 4.2.6. I was inspired by the great work of Will Hardy looking at his repo dynamic-models, but unfortunately it uses APIs that are no longer valid, as django changed a lot since v.1.2. I was thinking the project in this way: The user creates a Model instance (and as many Field instances as its model needs - each Field has a foreign key to Model). When a Model or a Field instance are saved/deleted the migrations are made and then applied using signals, so the database contains the schemas and the columns needed to store data. I created a dummy app (dynamic_models) and a real app (api_v1) that handle the storage of the data structure. The api_v1.models contains a Field and a Model models. Currently I was exploring the idea of using a customized flow of the makemigrations command and then a customized flow of the migrate command, called by a function called by a post_save signal sent by Model. Here some code I already wrote: api_v1.models.py from dynamic_models.dynamic_models import DynamicModel, makemigrations class FieldType(models.IntegerChoices): CharField = 1 # Requeires max_length TextField = 2 IntegerField = 3 DecimalField … -
How to display actual field with dropdowns instead of showing id?
I have two models and two serializers models: class P4R(models.Model): p4r_id = models.AutoField(primary_key=True) psc_id = models.ForeignKey(BePsc, on_delete=models.CASCADE, verbose_name='PSC Name') vbb_identifier = models.CharField(max_length=100, verbose_name='VBB Identifier') maturity = models.CharField(max_length=100) capex_opex = models.CharField(max_length=100, verbose_name='CAPEX/OPEX') budget_item = models.ForeignKey(BudgetItem, on_delete=models.CASCADE) paying_interest = models.DecimalField(max_digits=10, decimal_places=2) created_by = models.CharField(max_length=100, default='Admin', null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return str(self.vbb_identifier) class P4RChangingFields(models.Model): p4r_variations_id = models.AutoField(primary_key=True) vbb_identifier = models.ForeignKey(P4R, on_delete=models.CASCADE, verbose_name='VBB Identifier') year_now = models.IntegerField(default=2023, verbose_name=f'Year {current_year}') year_1 = models.DecimalField(max_digits=35, decimal_places=25, verbose_name=f'Year {year_1_name}') year_2 = models.DecimalField(max_digits=35, decimal_places=25, verbose_name=f'Year {year_2_name}') year_3 = models.DecimalField(max_digits=35, decimal_places=25, verbose_name=f'Year {year_3_name}') year_4 = models.DecimalField(max_digits=35, decimal_places=25, verbose_name=f'Year {year_4_name}') year_5 = models.DecimalField(max_digits=35, decimal_places=25, verbose_name=f'Year {year_5_name}') created_by = models.CharField(max_length=100, default='Admin', null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Meta: db_table = 'P4R_VARIATIONS' serializers: class P4RSerializer(serializers.ModelSerializer): class Meta: model = P4R fields = '__all__' class P4RChangingFieldsSerializer(serializers.ModelSerializer): vbb_identifier = serializers.CharField(source='vbb_identifier.vbb_identifier') # vbb_identifier = serializers.SlugRelatedField(slug_field='vbb_identifier', read_only=True) class Meta: model = P4RChangingFields fields = '__all__' As you can see, vbb_identifier is the field that connects between the two table. when user create new row using P4R model, they will need to enter vbb_identifier in the form of strings ("ABC123"). the only relationship both table has is vbb_identifier and its one to many. one P4R object may have multiple P4RChangingFields object related to … -
How to log missing template variable, showing location and context in Django?
I am following this tutorial ("With a logging filter that raises exceptions") to catch all invalid variable names in Django templates. myproject/mysite/logging.py: import logging class MissingVariableError(Exception): """ A variable was missing from a template. Used as an alternative to django.template.base.VariableDoesNotExist, because that exception has some meaning within the template engine. """ class MissingVariableErrorFilter(logging.Filter): """ Take log messages from Django for missing template variables and turn them into exceptions. """ ignored_prefixes = ( "admin/", ) def filter(self, record): if record.msg.startswith("Exception while resolving variable "): variable_name, template_name = record.args if not template_name.startswith(self.ignored_prefixes): raise MissingVariableError( f"{variable_name!r} missing in {template_name!r}" ) from None return False myproject/settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { "missing_variable_error": { "()": "www.logging.MissingVariableErrorFilter", }, }, "handlers": { "console": { "class": "logging.StreamHandler", }, }, "root": { "handlers": ["console"], "level": "WARNING", }, "loggers": { "django": { "handlers": ["console"], "level": 'INFO', "propagate": False, }, "django.template": { "level": "DEBUG", "filters": ["missing_variable_error"], }, }, } When I load the main page I get this in the log Traceback (most recent call last): ... File "/install_dir/site/myproject/mysite/logging.py", line 27, in filter raise MissingVariableError( www.logging.MissingVariableError: 'exception_notes' missing in 'unknown' Problem 1: exception_notes does not appear in my site (see note below) Problem 2: this stack trace … -
Superuser active is turned to False, how can I login to my django admin
Superuser active is turned to False, how can I login to my django admin. I mistakenly turned my active to False as a superuser, now I can't login to my django admin. How can I get back superuser as active? I have tried login but couldn't access admin -
Error reversing django migrations with sql_safe_update mode set in MariaDB
I am running into issues when I try to reverse migrate one of the migrations in Django due to sql_safe_update mode is set in MariaDB. The exact sql statement it runs for reverse is: ALTER TABLE `user` DROP COLUMN `pin_code`; And the error that I get from django is: MySQLdb.OperationalError: (1175, 'You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column') Now my database is in inconsistent state because the column has been dropped and failed migration was not rolled back as MySQL DDL statements are not run in transaction. Now even with --fake it shows the same error. Is there a way to tell django to run migrations with sql_safe_update=0 only for duration of migrations? Note that I cannot turn off sql_safe_update globally as DB admins are adamant on not removing it globally. Also it is not entirely clear why DROP column requires a WHERE statement? -
Query sum with distant foreign key relations in Django
Let's say I have models like this: class Product(models.Model): ... class Item(models.Model): product = models.ForeignKey(Product, related_name="items") quantity = models.IntegerField() class Order(models.Model): item = models.ForeignKey(Item, related_name="orders") quantity = models.IntegerField() I now want to get a list of Product annotated with the field total_supply. "Total supply" is defined for each product as: (sum of all of a product's items' quantity) - (sum of quantity on all of the Order objects associated with one of the product's items.) Here is what I have tried: Product.objects.annotate(actual_supply=Sum("items__quantity") - Sum("items__orders__quantity")) I am getting unexpected results. How am I supposed to write such a query? Thank you -
How to define individual service name for each type of Opentelemetry auto instrumentation in a python application?
We are currently using Datadog for monitoring and observability in our application, and we have integrated OpenTelemetry for distributed tracing. We have encountered one main issue Span Separation: Currently, all the spans from our application are being exported to Datadog under a single service. However, we would like to separate them into different services based on the type of instrumentation used (e.g., Django, Elasticsearch, requests, etc.). Manage.py configure_opentelemetry() #Auto Instrumentation of Django, Psycopg2, Pymemcache, Elasticsearch, URLLib3, Requests DjangoInstrumentor().instrument(request_hook=fix_django_req) PymemcacheInstrumentor().instrument() RequestsInstrumentor().instrument() ElasticsearchInstrumentor().instrument() Psycopg2Instrumentor().instrument(enable_commenter=True, commenter_options={}) URLLib3Instrumentor().instrument() configure_opentelemetry method def configure_opentelemetry(): otlp_exporter = OTLPSpanExporter(endpoint=os.getenv("OTEL_COLLECTOR_URL"), insecure=True) # Set the global TracerProvider with the OTLP exporter trace.set_tracer_provider(TracerProvider(resource=Resource.create({SERVICE_NAME: os.getenv("OTEL_SERVICE_NAME"), "env": os.getenv('OTEL_ENV')}))) # Create a BatchSpanProcessor and add the exporter to it span_processor = BatchSpanProcessor(otlp_exporter) trace.get_tracer_provider().add_span_processor(span_processor) tracer = trace.get_tracer(__name__) Collector Config: receivers: otlp: protocols: grpc: http: processors: batch: # batch metrics before sending to reduce API usage send_batch_max_size: 100 send_batch_size: 10 timeout: 10s memory_limiter: # drop metrics if memory usage gets too high check_interval: 1s limit_percentage: 65 spike_limit_percentage: 20 resourcedetection: detectors: [env, gcp] timeout: 2s override: false transform: error_mode: ignore trace_statements: - context: span statements: - set(attributes["resource.name"], name) exporters: datadog: api: site: ${DD_SITE} key: ${DD_API_KEY} extensions: health_check: service: extensions: [health_check] pipelines: traces: receivers: [otlp] processors: [memory_limiter, resourcedetection, … -
Django simple ModelForm not showing on page (I'm using class based-views), what could be the problem?
I'm trying to build a form to use it as a filter for my project search page, but the {{form}} shows nothing. Here is how everything is set up: The model I'm trying to use from models.py class Exemplar(models.Model): class Meta: verbose_name_plural = 'Exemplares' tipoDeExemplar = models.ForeignKey(TipoDeExemplar, on_delete=models.SET_NULL, blank=True, null=True, verbose_name="Tipo De Exemplar") numeroDeRegistro = models.CharField(max_length=255, verbose_name="Número Do Registro") especie = models.ForeignKey(Especie, on_delete=models.CASCADE, null=True) dataDoRegistro = models.DateField(blank=True, null=True, verbose_name="Data Do Registro") estadoDoExemplar = models.CharField(blank=True, null=True, max_length=255, verbose_name="Estado do Exemplar") tipoDeMaterial = models.CharField(blank=True, null=True, max_length=255, verbose_name="Tipo De Material") procedencia = models.CharField(blank=True, null=True, max_length=255, verbose_name="Procedência") remetente = models.CharField(blank=True, null=True, max_length=255, verbose_name="Remetente") armario = models.CharField(blank=True, null=True, max_length=255, verbose_name="Armário") gaveta = models.CharField(blank=True, null=True, max_length=255, verbose_name="Gaveta") complemento = models.CharField(blank=True, null=True, max_length=255, verbose_name="Complemento") amostraDeOrigem = models.CharFie fotoDoExemplar = models.ImageField(null=True, blank=True, upload_to='imagens/', verbose_name="Foto Do Exemplar") slug = models.SlugField(max_length=255, unique=True) def __str__(self): return self.numeroDeRegistro My forms.py file (very short) from django.forms import ModelForm from acervo.models import Exemplar class ExemplarForm(ModelForm): class Meta: model = Exemplar fields = '__all__' My view on views.py (seems to be working since I can open the page) class BuscaView(ListView): model = Exemplar template_name = 'busca.html' form_class = ExemplarForm Piece of the HTML template where I try to use the Django ModelForm <form action="" method="post"> … -
Django When I choose an account from the account tree using the check box
Django When I choose an account from the account tree using the check box, the account and its details are displayed on same template template acc.html template acc1.html view.py models.py -
OAUTH2 Django problems with client_secret
I was updating an old non documented project, database, users, etc.. Suddenly it came a problem, the client_secret_id is not hashed, if I edited in /o/applications then it become hashed. Is there a simple way to hash every client_secret_id other than manually do it one by one, application per application? I found the library, but I don't have any idea where is the salt, or how to include it -
How to get static files to work in Django | Favicon not getting loaded but appears when entering that directory
I'm having trouble trying to get my static files to work, I've already tried different answers for a long time and I'm getting confused what's the problem. I was trying to load my css with debug turned off, but I think its normal for the css not to appear since django doesn't load static files with debug turned off. My problem was when trying to put a favicon into my test website. I also think in the future I'll have complications with JS, etc.. main.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Hello, Django</title> <!-- load staticfiles--> <link rel="stylesheet" href="{% static 'main.css' %}"> <link rel="shortcut icon" href="{% static "favicon.ico" %}}" type="image/png"> </head> <body> </body> </html> urls.py from django.urls import path from f1trackerapp import views from django.contrib.staticfiles.storage import staticfiles_storage from django.views.generic.base import RedirectView urlpatterns = [ path("", views.f1trackerapp, name="f1trackerapp"), path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('favicon.ico'))) ] settings.py (stackoverflow doesn't let me post full settings.py code) ... from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ... # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', … -
How do I make Django add the plural of category as categories instead of categorys
In my Django project I have a category tables however the plural is showing at categorys is there a way to force categories instead? I tried renaming the table but that did not work I also tried manually changing this by changing my model however I receive the same -
HTML does not recognize CSS file - Django
I recently started working on my first python + django project and I'm working on some visual things, but I noticed that the HTML isn't recognizing my CSS file. I follow the documentation about How to manage static files but nothing worked. So, this is my settings.py #app definition INSTALLED_APPS = [ #personalizacao #'grappelli', #Configuraçoes principais 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles' ] #statics configs STATIC_URL = "/static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', # 'django.contrib.staticfiles.finders.AppDirectoriesFinder', #causes verbose duplicate notifications in django 1.9 ) In my HTML I have {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}" /> And I can call the stuff that I have on the static/img folder with no problem So does anyone know what can it be? I don't know where to look anymore -
AWS EC2 Django Requests working from Public ipv4 address, but not Public ipv4 DNS address
Running a django project on an ubuntu 22.04 instance on a new account including a default VPC. Using a custom security group with 3 inbound rules: ipv6(http) on port 80, ipv4(http) on port 80, and ipv4(ssh) on port 22. Outbound rule is the same as default, ipv4(all) on all ports. No key pair was set. Running with gunicorn, nginx, and supervisor. sudo nginx -t shows no issues, supervisor err logs are empty. /var/log/nginx/access.log shows that the api is receiving requests from both sites with no difference in the logs besides codes 200 29 for the successful request from the public ipv4, and codes 404 197 for the failed request from the public ipv4 DNS. It's also worth noting that the public ipv4 DNS serves the default nginx page on the base url while the public ipv4 shows resource not found. There are no relevant errors in /var/log/nginx/error.log.