Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to correctly raise the desired error or override the error in the class?
In my code for validating a token, for any error or invalid token, I always gives an error 500. I need to get an error 401, or 403. Here is part of the code. class AzureVerifyTokenError(Exception): pass class InvalidAuthorizationToken(AzureVerifyTokenError): def __init__(self, details=''): super().__init__(f'Invalid authorization token: {details}') def verify_jwt(*, token, valid_audiences, jwks_uri, issuer, verify=True): public_key = get_public_key(token=token, jwks_uri=jwks_uri) try: decoded = jwt.decode( token, public_key, verify=verify, algorithms=['RS256'], audience=valid_audiences, issuer=issuer, ) except jwt.exceptions.PyJWTError as exc: raise InvalidAuthorizationToken(exc.__class__.__name__) else: return decoded What I already tried: In the part where there is a try, I tried to return 401. from rest_framework import status from rest_framework.response import Response ..... except jwt.exceptions.PyJWTError: return Response(status=status.HTTP_401_UNAUTHORIZED) ..... But this obviously doesn't work. Or I don’t import what I need, or I don’t use what I need. Am I doing something wrong, or am I missing something. I even think it should be easy, but I'm completely lost. Perhaps the class AzureVerifyTokenError(Exception): pass is empty for a reason and I can set error there, but how? Any hints and examples will help me. Thank you. -
Django redirect to another view not working, url redirect is though
I have a view that I just want to redirect to another view for test purposes. When I hardcode the URL it works. def testDirect(request): return HttpResponse("redirected to correct pagge") def randomQuestion(request): random_question = Question.objects.order_by('?')[0] return redirect("/polls/testDirect") However, what I really want to do is call it by it's view name. When I look at the docs it gives me this example below: By passing the name of a view and optionally some positional or keyword arguments; the URL will be reverse resolved using the reverse() method: def my_view(request): ... return redirect('some-view-name', foo='bar') But when I try it like that I get the following error def randomQuestion(request): random_question = Question.objects.order_by('?')[0] return redirect('testDirect') Not sure what I am doing wrong -
Django socketio client connects but returns 404 not found
here is my django server.py file import socketio import eventlet SOCKET_PORT = 8000 sio = socketio.Server() app = socketio.WSGIApp(sio) @sio.event def connect(sid, environ): print(sid, 'connected') @sio.event def disconnect(sid): print(sid, 'disconnected') @sio.event def test(sid, data): print(data) def initSocket(request): eventlet.wsgi.server(eventlet.listen(('', SOCKET_PORT)), app) and this is my client.py file import socketio client = socketio.Client() client.connect('http://localhost:8000') client.emit('test', 'hello world') this is wsgi.py file from django.core.wsgi import get_wsgi_application import os import eventlet import eventlet.wsgi os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'b2b_backend.settings') application = get_wsgi_application() eventlet.wsgi.server(eventlet.listen(('', 8000)), application) and finally urls.py file from webSocket.views import initSocket urlpatterns = [ path('', initSocket) ] this is the output of the server when I launch the client.py file from cmd. Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. (22588) wsgi starting up on http://0.0.0.0:8000 (22588) accepted ('127.0.0.1', 58933) Not Found: /socket.io/ 127.0.0.1 - - [29/Jun/2022 19:00:08] "GET /socket.io/ transport=polling&EIO=4&t=1656518406.600064 HTTP/1.1" 404 3092 0.010074 when the django server starts at port 8000, it will also start the socketio server on the same port by calling the initSocket method, then I start the client.py file from cmd (I'm using cmd for testing), all it should do is connect to the server and emit an event. All I'm trying to do is get the clients … -
Django - tests not discovered after moving code to another directory
When my app layout was project/ ├── app1/ │ ├── __init__.py │ ├── tests.py ├── app2/ ├── Dockerfile ... └── manage.py running python manage.py test worked just fine. Then code was moved to src/ dir, i.e. project/ ├── src │ ├── app1/ │ │ ├── __init__.py │ │ ├── tests.py │ ├── app2/ │ ... │ └── manage.py ├── Dockerfile ... and now no tests are discovered root@650001aeb6b5:/app# python src/manage.py test Found 0 test(s). System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK I have tried using the -t option but that didn't help root@650001aeb6b5:/app# python src/manage.py test -t src ... ImportError: Start directory is not importable: '/app' Any idea how to make this work? My guess is test discovery configuration should be updated but I have no idea how to do that. -
Django Ajax posting duplicate values to the view
Im trying to post the value of a html item(the id of the item) to the view so it can add the item to the cart, however it always posts the value of the last item printed by the django {% for %} even though the html source says the values are different here is my html <div class="container"> <div class="row row-cols-2 row-cols-md-3" data-masonry='{"percentPosition": true }'> {% for product in products %} <div class="col mb-4"> <div class="card h-100"> {% if product.image %} <img src="{{ product.image.url }}" class="card-img-top" alt="{{ product.description }}"> {% endif %} <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.description|slice:":100" }}...</p> <p class="card-text">${{ product.price }}</p> <p> <a class="btn btn-dark gap-2 mb-1" href="{{ product.get_absolute_url }}">View Item</a> <button class="btn btn-outline-success" id="add-to-cart" value="{{ product.id }}">Add to Cart</button> </p> {% if product.in_stock == False %} <p> Item is currently out of stock </p> {% endif %} </div> </div> </div> {% endfor %} </div> </div> Here is the Ajax $(document).on('click', '#add-to-cart', function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "add_to_cart" %}', data: { productid: $('#add-to-cart').val(), csrfmiddlewaretoken: '{{ csrf_token }}', action: 'post' }, success: function(json){ }, error: function(xhr, errmsg, err) { } }); }) Here is my view def CartAddView(request): cart = Cart(request) … -
Django validate ModelInlines in Parent Model
Suppose we have 2 django models: class File: # Comma separated list of column names unique_columns = models.CharField(max_length=200) class Column: file = models.ForeignKey(File, on_delete=models.CASCADE) name = models.CharField(max_length=50) In admin.py class ColumnInline(nested_admin.NestedTabularInline): model = Column class FileAdmin(admin.ModelAdmin): inlines = [ColumnInLine] What I want to achieve When saving these models in the Admin page I want to validate whether the Files' unique_columns are also set as Columns related to this File (by validating a related object with that name exists) What I tried Obviously, a clean() method on File won't work as it's saved before Column. Overriding save_formset on FileAdmin, however I don't fully understand how to access the Column forms Question How to achieve this? Is it possible by using a custom form? Or can I override save_formset and do the validation I want? As a more general question: What is a good way to do such validations where validating one form depends on forms of other objects? -
Nested function working but returning messages in Django
I have a function called inside another one. The functions are working properly but, while using a validator to raise some error in case of wrong entries by the users, the validator works but is calling either the success and the error message. I post some code for better explanation. utils.py def add_flight_function(request): try: aircraft_maintenance_type = AircraftMaintenanceType.objects.first() except: aircraft_maintenance_type = None aircraft = request.POST.get('aircraft') adep = request.POST.get('adep') ades = request.POST.get('ades') date = request.POST.get('date') atd = request.POST.get('atd') ata = request.POST.get('ata') function_type_obj = request.POST.get('function_type') function_type_obj = FunctionType.objects.get(id=function_type_obj) operational_condition = request.POST.get('operational_condition') student = request.POST.get('student') instructor = request.POST.get('instructor') night = request.POST.get('night') note = request.POST.get('note') aircraft_type = Aircraft.objects.get( id=aircraft).aircraft_type.abbreviation if aircraft_maintenance_type.is_tacho == True: atd_tacho = request.POST.get('atd_tacho') ata_tacho = request.POST.get('ata_tacho') if float(ata_tacho) <= float(atd_tacho): messages.error( request, "ATA Tacho cannot be lower than ATD Tacho") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) is_valid_flight, error_message = flight_validator( request, ata, atd, function_type_obj.name, instructor) if not is_valid_flight: messages.error(request, error_message) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: is_valid_flight, error_message = flight_validator( request, ata, atd, function_type_obj.name, instructor) if not is_valid_flight: messages.error(request, error_message) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) log_entry = LogEntry.objects.create(aircraft_id=aircraft, adep_id=adep, ades_id=ades, date=date, atd=atd, ata=ata, function_type_id=function_type_obj.id, student_id=student, instructor_id=instructor, operational_condition_id=operational_condition, note=note) if night == 'on': log_entry.night_flight = True # if function_type_obj.name == 'Dual Command': # instructor_flight_payment = InstructorFlightPayment(log_entry=log_entry, instructor_id=instructor) # instructor_flight_payment.save() if function_type_obj.name == 'Single … -
Div spacing issue
I would like the lines to be much closer to each other, but margin and height are not working <h4>TITLE:</h4> <div style="width: 290px; display: table-cell;"> <h4>AAA</h4> </div> <div style="display: table-cell;"> <h4>€ 123</h4> </div> <br> <div style="width: 290px; display: table-cell;"> <h4>BBB</h4> </div> <div style="display: table-cell;"> <h4>€ 123</h4> </div> Result: There is almost a full line size between AAA and BBB. That's the issue. -
Are there "N + 1 problems" in "formfield_for_foreignkey()"? (Django)
I overrided formfield_for_foreignkey() to display the combination text of foreign key and its parent to Django Admin as shown below: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): formfield = super().formfield_for_foreignkey(db_field, request, **kwargs) if db_field.name == "my_field": formfield.label_from_instance = lambda obj: f'{obj} ({obj.my_parent})' return formfield Then, with "print()", I checked how many time "formfield_for_foreignkey()" and "if block" in "formfield_for_foreignkey()" are called as shown below: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): formfield = super().formfield_for_foreignkey(db_field, request, **kwargs) print("formfield_for_foreignkey") # Called "18 times" if db_field.name == "my_field": print("if block") # Called "9 times" formfield.label_from_instance = lambda obj: f'{obj} ({obj.my_parent})' return formfield As a result, print("formfield_for_foreignkey") is called 18 times which means "formfield_for_foreignkey()" is called 18 times. And print("if block") is called 9 times which means "if block" in "formfield_for_foreignkey()" is called 9 times. My questions: Is it "N + 1 problem" that: "formfield_for_foreignkey()" itself is called 18 times? "if block" itself is called 9 times? "{obj}" in "if block" is called 9 times? "{obj.my_parent}" in "if block" is called 9 times? -
pass parameters to an modal django?
I'm starting to program with python and django. I'm trying to implement the modal in my web page. I have already achieved the implementation of modals for the creation of objects, but I have a problem updating or deleting, since they require sending a parameter. total_alumnos.html <div class="table-responsive"> <h5>Alumos de Secundaria</h5> <form method="get" class="forms-sample"> <label for="as" >Apellido Paterno:&nbsp;</label>{{filtro.form.apellido_p}} <button class="btn btn-info" type="submit"><i class="fa-solid fa-magnifying-glass"></i>&nbsp; Buscar</button> </form> <br> <table style="text-align:center;" class="table table-bordered table-striped table-contextual "> <tr class="table-info"> <th>Usuario</th> <th>Nombre</th> <th>Apellidos</th> <th>Correo</th> <th>Grado</th> <th>Año</th> <th>Salon</th> <th>Asignar</th> </tr> {% for alumno in alumno %} <tr> <td class="py-1"> <img src="{{alumno.profile_pic.url}}" alt="image" /> </td> <td>{{alumno.nombre }}</td> <td>{{alumno.apellido_p }} {{ alumno.apellido_m }}</td> <td>{{alumno.email }}</td> <td>{{alumno.aula.grado }}</td> <td>{{alumno.aula.año }}</td> <td>{{alumno.aula.salon }}</td> <td><a class="btn btn-sm btn-info btn-rounded" href="{% url 'asignar_alumno' alumno.id %}" ><i class="fa-solid fa-circle-plus"></i>&nbsp;Asignar</a></td> <td><button type="button" data-bs-toggle="modal" data-bs-target="#asignarModal" class="btn btn-info" ><i class="fa-solid fa-circle-plus"></i>Asignar</button></i></td> </tr> {% endfor %} </table> asignar_alumno.html <div class="modal fade" id="asignarModal" tabindex="-1" role="dialog" aria-labelledby="asignarModal" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Agregar Curso</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form method='POST'action="" enctype="multipart/form-data" > {% csrf_token %} <div class="modal-body"> {{aula_form.aula}} </div> <div class="modal-footer"> <a class="btn btn-warning" href="{% url 'total_alumnos' %}">Cancelar</a> <input class="btn btn-primary" type="submit" name="Submit" value="Asignar Aula"> </div> </form> </div> </div> … -
Create a history record in Django for every UPDATE of a class instance
I have a model in Django that is used to create an item of stock class Item(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) description = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='item') amount = models.IntegerField(default=0, blank=False) place = models.ForeignKey(Place, on_delete=models.CASCADE, related_name='place') issue_amount = models.IntegerField(default=0, blank=True) receive_amount = models.IntegerField(default=0, blank=True) The item amount will be updated everytime an item is issued by adding or subtracting the issue or receive amount in a views function that alters the instance amount and calls save on that instance. I want to be able to keep a record of every update and make this information available to both my frontend and to an admin model. I found this tutorial in which the poster creates a separate model with the same field values as Item and then writes SQL commands directly to the database to create a TRIGGER that saves each Item field on every update: https://www.youtube.com/watch?v=d26DUXynf8s Is there a way I can replicate this same behaviour using Django? -
Django query_set order_by default field if ordering field is an empty string
I have a query_set that I want to order by Lower('title'). However, for some elements, title is blank (blank=True). So, when I sort, those elements are rightfully are on top. However, all elements, no matter what, have a default_title. So, I want to use an element's default_title in the sorting if title is blank. -
how to connect my project with zoho books via api in Django
I was trying to integrate my Django project ZohoBooks via API. So I got stuck while generating the AuthToken or Code. how to create an invoice on Zoho books automatically, when the Order objects are created in my Django project. please help!!!! thanks in advance -
Django Celery Redis
I have this error A rediss:// URL must have parameter ssl_cert_reqs and this must be set to CERT_REQUIRED, CERT_OPTIONAL, or CERT_NONE settings CELERY_BROKER_URL = os.environ.get('REDIS_URL', "redis://localhost:6379") CELERY_RESULT_BACKEND = os.environ.get('REDIS_URL', "redis://localhost:6379") CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' celery.py from __future__ import absolute_import, unicode_literals from celery import Celery import os, ssl os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproj.settings') app = Celery( 'myproj', broker_use_ssl = { 'ssl_cert_reqs': ssl.CERT_NONE }) app.config_from_object('django.conf:settings', namespace="CELERY") app.autodiscover_tasks() I changed the value of ssl_cert_reqs to different value 'none', 'cert_required', ..., but nothing, always the same error when I use rediss:// instead of redis://. -
How do I access exception traceback during graphene-django request?
I'm using graphene-django v2.15.0 because that's the latest stable release, which pulls in graphene v2.1.9. Any time an exception is raised during a graphql request, all I get to see is the HTTP response body which looks something like: {"errors":[{"message":"this is my exception","locations":[{"line":1,"column":3}],"path":["hello"]}],"data":{"hello":null}} Just the message, not the traceback, and some useless location information that has nothing to do with the cause. I've spent an hour googling things like "graphene-django errors traceback", and I found tons of results - but all of them were people trying to silence errors and tracebacks, not access them! Am I in the wrong timeline? Did I get Mandela'd? What the hell is going on? BTW - I already tried the following based on a suggestion I found, but it had zero effect on behavior, either in the response or in the console where I have ./manage.py runserver going. import logging ; logging.getLogger("graphql.execution.utils").setLevel(logging.DEBUG) I've also tried looking through graphene and graphene-django docs for settings to flip with no success. -
Get data from second api call based on data coming from the first api (python/django)
I am making a simple web application in pycharm (python/django) that displays data that it picks up from growstuff.org. The main page displays all the crops based on what it finds on growstuff.org/crops.json like the plant's name,scientific name and description. However, info of the plants themselves (like spread,height,days to harvest,sun requirements) are contained in growstuf.org/crops/ID.json. I have already managed to get the data from crops.json and display it on the website,however i can't combine the two files to display the full info i need. How can I make the second call based on the first one's data? views.py apidata = requests.get('https://www.growstuff.org/crops').json() #cropdata = requests.get(f"https://www.growstuff.org/crops/{}.json").json() return render(request, 'index.html', {'apidata':apidata}) index.html <table Width="70%" Height="180px"> <thead> <tr style="font-family:asul; "> <td>Crop</td> <td>Name</td> <td>Scientific Name</td> <td>Description</td> <td>Suniness</td> <td>Companions</td> </tr> </thead> <tbody id="myTable"> {% for i in apidata %} <tr> <td><img src="{{i.thumbnail_url}}" style=" border: 1px solid #ddd; border-radius: 4px; padding: 5px; width: 150px;"></td> <td><h4>{{i.name}}</h4></td> <td><h4>{{i.scientific_name}}</h4></td> <td><h4>"{{i.description}}"</h4></td> {% for j in cropdata %} <td><h4>{{i.j.sun_requirements}}</h4></td> <td><h4>{{i.j.relationships}}</h4></td> {% endfor %} </tr> {% endfor %} </tbody> </table> -
orator migrate command not working in django
When i'm running orator migrate command then with giving config path like orator migrate -c db.py Then the result is comming Command Cancelled! I have installed orator in django Orato 0.9 Python 3.9.7 django 4.0.5 I create a migration and model in the mean project that you can see my code and set the connection but when I'm running migrate command db connection from orator import DatabaseManager, Schema import environ env = environ.Env() environ.Env.read_env() databases = { 'mysql': { 'driver': 'mysql', 'host': 'localhost', 'database': env('DB_DATABASE'), 'user': env('DB_USERNAME'), 'password': env('DB_PASSWORD'), 'prefix': '' } } db = DatabaseManager(databases) schema = Schema(db) migration file from orator.migrations import Migration class CreateProductsable(Migration): def up(self): """ Run the migrations. """ with self.schema.create('products') as table: table.increments('id') table.integer('category_id').unsigned() table.timestamps() table.foreign('category_id').references('id').on('jobs').on_delete('cascade') def down(self): """ Revert the migrations. """ self.schema.drop('products') model file class Product(Model): __table__ = 'products' -
Django adding new courses by users in Learning Management System app from UI
On my app, I can add new courses from Django Admin Panel Only by using the model in Django Admin Panel. Picture 1 - Django Admin Panel Picture 2 - Adding New Course from Admin Panel I want to automate this whole process. I want to create a form where users can fill out the form and submit their Course using UI. And That course will automatically be added to the Courses. So, to achieve my goal, what are the necessary steps I should take? For a better understanding of my problem here is the GitHub repo link to my project. GitHub Repo of My Project -
Django view to download a file from server
I have a views.py that: creates some .xlsx files select the correct .zip and place the file inside After that, I want this .zip to be automatically downloaded. I did some research and tested some codes but none worked. I created a "temp" folder in the root of the app where the created files are stored. simplified view.py def generate_ws(request,cource,ca_id): ca = get_object_or_404(CreditAnalysis,pk=ca_id) ca_owners = CAOwner.objects.filter(ca_operation=ca) mo_farms = MOFarm.objects.filter(ca_operation=ca) misses = [] generate_owner_mo(ca_owner,misses,city) zip_name = 'temp/MOs - ' + str(ca_owner.owner) + '.zip' zf = zipfile.ZipFile(zip_name,'w') zf.close() generate_farm_mo(mo_farm,misses,city) generate_production_mo(ca,misses,city,production_city,pks) files = glob.glob('temp/*.xlsx') for file in files: file_key = file.split('.')[0] file_key=file_key.split(' - ') for ca_owner in ca_owners: zip_name = 'temp/MOs - ' + str(ca_owner.owner) + '.zip' if str(ca_owner.owner) in file_key: zf = zipfile.ZipFile(zip_name,'a') new_file_name = file[5:] zf.write(file,new_file_name) zf.close() break for file in files: if file[5:8]=='MOs': download_mo(request,file) misses = list(set(misses)) return render(request,'generate_mo.html',{'misses':misses,}) download_mo def download_mo(request,file): path_to_file = os.path.realpath(file) with open(path_to_file,'rb') as fh: response = HttpResponse(fh.read()) file_name = file[5:] response['Content-Disposition'] = 'inline; filename=' + file_name return response Everything works correctly except the download which never starts -
How to use opencv-python for Java blob in Django
I'm building a Django website. My users can record a video and then others can see these videos. The recording is done with javascript: const mimeType = 'video/mp4'; shouldStop = false; const constraints = { audio: { echoCancellation: true, noiseSuppression: true, }, // audio: true, video: { width: 480, height: 480, facingMode: 'user', }, }; const stream = await navigator.mediaDevices.getUserMedia(constraints); const blob = new Blob(recordedChunks, { type: mimeType }); And the sent to a django view: let response = await fetch("/send-video/", { method: "post", body: blob, headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', "X-CSRFToken":csrftoken, }, }).then( ... ) In my views if request.method == 'POST': user = request.user file_name = f"{user}.mp4" if (len(sys.argv) >= 2 and sys.argv[1] == 'runserver'): file_path = file_name else: file_path = f"{your_media_root}temp/{file_name}" webm_bytes = bytes(request.body) video_file = open(file_path, "wb") video_file.write(webm_bytes) if mimetypes.guess_type(file_path)[0].startswith('video/mp4'): print(mimetypes.guess_type(file_path)) video_file.close() else: video_file.write(b"") video_file.close() I like to understand how I can use opencv-python instead of raw file saving. How can I implement this ? -
Handling different SSO implementations in Django webapp
I am not very experienced in SSO so please forgive me if my question sounds silly. I have a Django webapp which currently uses the embedded model-based Django authentication. This application of mine is meant to work in different companies where different authentication/authorization systems are used (Microsoft AD, Google, Oracle, etc.). So I want to implement SSO in my webapp but without knowing which implementation will be used. My question would be if there is a Python SSO library that can handle different SSO implementations? Naturally that would be fine if there were separate config parameters per SSO engine. Or do I have to use different libraries per SSO implementations? Thank you! -
Django Postgres makemigrations only Autofield at 0001_initial.py
Python 3.10.4 Django 4.0.5 PostgreSQL 14 When I start "python manage.py makemigrations" i got the file "0001_initial.py" but all Fields, except autofields, are missing. models.py from django.db import models # Create your models here. class Username(models.Model): #id = models.AutoField(primary_key=True) username: models.CharField(max_length=100) class Carrier(models.Model): #id = models.AutoField(primary_key=True) carriername: models.CharField(max_length=100) desc: models.TextField() 0001_initial.py # Generated by Django 4.0.5 on 2022-06-29 13:18 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Carrier', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.CreateModel( name='Username', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), ] -
Mysql-python for upgraded Django
I'm upgrading a system from Django 1.11.16 Debian 9.6 Python 2.7.13 mysql-server 5.5.9999+default to Django 4.0.5 Debian 11.1 Python 3.9.2 mariadb-server 10.5.15 . My plan is to make a dump from the existing database and use it in the new server within the very new, upgraded environment. With Django 1.11.16 I used MySQL-python==1.2.5 as a connector to the database. My question is what package with what version do You advise to use for the same purpose with the given set of versions? -
Not all stylesheets are loaded
There are 2 stylesheets. One is under the project folder (created for base.html) and another is inside the app folder (for applist.html). collectstatic command did collect both the stylesheets and put inside the STATIC_ROOT folder 'assets'. But when runserver is on, the app's stylesheet isn't loaded only the base.html's stylesheet got loaded and working. base.html {% load static %} <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title> {% block title %} {% endblock %} </title> <!-- Add additional CSS in static file --> <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> </head> <body> {% block content %}{% endblock %} </body> </html> applist.html <!DOCTYPE html> {% extends "base.html" %} <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> {% load static %} <meta charset="utf-8" /> <title>List</title> <!-- Add additional CSS in static file --> <link rel="stylesheet" type="text/css" href="{% static 'css/dstyles.css' %}"> </head> {% block content %} <body> <h2>Testing for stylesheet linking</h2> </body> {% endblock content %} </html> folder structure is like, Dev_ static css styles.css app static css dstyles.css assets static css styles.css dstyles.css The base.html's styles are working whereas app's stylesheet is not working. I did F12 and checked to see only style.css got loaded and dstyles.css didn't appear. attaching … -
Connecting Django on Ubuntu EC2 to AWS RDS MySQL: pymysql tries to connect to localhost instead of foreign server
I am in the process of deploying a Django project on an Ubuntu EC2. It should connect to a MySQL server on AWS RDS. The project works fine on the built-in Django development server you start with runserver and it also connects to the RDS instance properly there. However, if I try running it in production, it throws a 500 Internal Server Error that creates the following output in the error log: mod_wsgi (pid=18656): Exception occurred processing WSGI script '/home/ubuntu/mysite/mysite/wsgi.py'. Traceback (most recent call last): File "/home/ubuntu/mysite/mysite_venv/lib/python3.8/site-packages/pymysql/connections.py", line 613, in connect sock = socket.create_connection( File "/usr/lib/python3.8/socket.py", line 808, in create_connection raise err File "/usr/lib/python3.8/socket.py", line 796, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: ... pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)") This socket error occurs both with my custom views and with the mydomain.com/admin view. The relevant snippet of views.py looks like this: # get environment variables db_host = os.environ.get('DB_HOST') db_user = os.environ.get('DB_USER') db_pass = os.environ.get('DB_PASS') # connect to db conn = pymysql.connect(host=db_host, user=db_user, password=db_pass) c = conn.cursor() c.execute('''USE mysitedatabase''') The file is generally executed properly, log statements I inserted as a test before …