Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CORS error in label studio on setting host and port
I am trying to run label-studio in my local server and do a reverse proxy. However following the website https://labelstud.io/guide/start#Run-Label-Studio-with-HTTPS I can run the label-studio but on sign-in and login-in I am getting CORS error. [2024-02-04 16:07:29,509] [django.security.csrf::log_response::224] [WARNING] Forbidden (CSRF cookie not set. -
Django JWT Changed but still valid
I have a project of mine in which I was veriyfing the authenticity of token, generated by library rest_framework_simplejwt. While playing around token I changed last character from 8 to 9 and it worked. I am not able to understand why and how it happened. My original token: { "token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzA3MDY0NTc1LCJpYXQiOjE3MDcwNjA5NzUsImp0aSI6IjBhNDEyY2M5NjIwYjQxYzJhZDI5NzFhNzZkZGJhOGJhIiwidXNlcl9pZCI6NH0.jvylGlq3qkJPhvBkhbsqFPakwyMS7BBDwB-bMIAzWq8" } Tweaked yet valid token: { "token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzA3MDY0NTc1LCJpYXQiOjE3MDcwNjA5NzUsImp0aSI6IjBhNDEyY2M5NjIwYjQxYzJhZDI5NzFhNzZkZGJhOGJhIiwidXNlcl9pZCI6NH0.jvylGlq3qkJPhvBkhbsqFPakwyMS7BBDwB-bMIAzWq9" } Focus on last character of token. Any opinions? -
Django pass error exception to error views handler
urls.py handler500 = 'main.views_error.view_error_500' main/views_error.py def view_error_500(request, exception=None): print("APP: view_error_500") print(exception) return render(request,"error/500.html", status=500) So when i'm asking for page with error look like Exception does not pass to views: APP: view_error_500 None 2024-02-04 18:24:58,641 - django.request 241 - ERROR - Internal Server Error: /office/order_14841/ Traceback (most recent call last): File "/usr/local/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapper_view return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapper_view return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/code/main/views_admin.py", line 1453, in admin_orders_edit order = Company_Orders.objects.get(id=kwargs["order_id"]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/db/models/query.py", line 647, in get raise self.model.DoesNotExist( main.models.Company_Orders.DoesNotExist: Company_Orders matching query does not exist. Like there is no view_error_500 handler, but i'm sure So the question is: is there and way to get error informations to my handler so i can work with error? -
Django fails to update environment variable from wsgi.py
I have a Django application that uses Apache in production. I store the Django secret key value in an external file, from which the key gets applied on startup. I let Apache know the location of the file using SetEnv directive in my application config file: SetEnv DJANGO_KEY_LOC /data/www/ref/.myKey I've written a function in wsgi.py to get the path from the Apache env variable and apply the key value inside to the SECRET_KEY setting in settings.py. If the code doesn't find that variable it pulls the location from an os env variable I use for dev DJANGO_KEY='/data/www/ref/.myKey: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myApp.settings') os.environ['DJANGO_SETTINGS_MODULE'] = 'myApp.settings' _application = get_wsgi_application() def application(environ, start_response): try: # DJANGO_KEY_LOC set in Apache conf for prod. file_loc = environ['DJANGO_KEY_LOC'] with open(file_loc, 'r') as f: os.environ['SECRET_KEY'] = f.read() except KeyError: # if key missing in environ try dev settings print('running in dev environment...') dev_file_loc = os.getenv('DJANGO_KEY') with open(dev_file_loc, 'r') as f: os.environ['SECRET_KEY'] = f.read() return _application(environ, start_response) The function retrieves the key values just fine, but fails to set os.environ['SECRET_KEY']. The code in settings.py is SECRET_KEY = os.environ['SECRET_KEY']. The app fails to load unless I supply a dummy value for SECRET_KEY beforehand, but the … -
Django: reset passowrd in updateview
I am new to Django and try to change/reset the passowrd of an user. Is it possible to change/set the password of an user in updateview? Or ist there a function available to serialize an input and save to the password field of the user model? Thanks in advance Ben -
Django built-in LogoutView is always 'GET'
First stuck with "Method Not Allowed (GET): /logout/", found answer, changed template so method is 'POST'(tried 'post'), but now despite it I'm still getting "Method Not Allowed (GET): /logout/", since method is still 'GET'. Same happens when LogoutView.as_view() is empty. urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('', include('blog.urls')), ] full html file(/users/templates/users/logout.html) <form method="POST" > {% csrf_token %} <button type="submit">logout</button> </form> command prompt when I'm going to http://localhost:8000/logout/ Method Not Allowed (GET): /logout/ Method Not Allowed: /logout/ [04/Feb/2024 17:30:07] "GET /logout/ HTTP/1.1" 405 0 Method Not Allowed (GET): /logout/ Method Not Allowed: /logout/ [04/Feb/2024 17:30:08] "GET /logout/ HTTP/1.1" 405 0 Can I change method to 'POST' instead of 'GET' with built-in LogoutView? Tried to find answers for "Method Not Allowed (GET): /logout/", but all I got was to change form method to 'POST', but I'm still getting 'GET' method. -
badly formed hexadecimal UUID string
from django.db import models import uuid # Create your models here. class Project(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) demo_link = models.CharField(max_length=2000, null=True, blank=True) source_link = models.CharField(max_length=2000, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=True) I have tried to change uuid and editable argument but it's not working at all. -
getting weird login page for django adming
I am getting this weird login page for Django admin after deploying on server. In my local project everything is looking fine. I checked already if there is any css failing but everything seems fine. if anyone have any idea about this please help me to get rid of it. -
Problems with user login in the system
i have created two custom forms based on UserCreationForm and AuthenticationForm. After registering a user, I want to log him in immediately, and I succeeded. But when I just want to log in, the error {'invalid_login': 'Please enter a correct %(username)s and password. Note that both fields may be case-sensitive.', 'inactive': 'This account is inactive.'} even if all the entered data is correct. models.py class User(AbstractUser): profile_image = models.ImageField(upload_to='accounts/images', default='default/user.jpg', blank=True, null=True) address = models.CharField(max_length=130, null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) def __str__(self) -> str: return f"{self.username}, {self.email}" forms.py class LoginForm(AuthenticationForm): class Meta: model = User fields = ['username', 'password'] labels = { 'username': "Username", 'password': 'Password' } views.py class LoginView(View): def get(self, request): form = LoginForm() return render(request, 'accounts/login.html', {'form': form}) def post(self, request): form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) print(f"User {username} login successfully.") return redirect('blog:index') print(f"Form errors: {form.error_messages}") return render(request, 'accounts/login.html', {'form': form}) template login.html {% extends 'base.html' %} {% block title %} Login user {% endblock %} {% block content %} <div> <form action="" method="post"> {% csrf_token %} {{ form }} <br> <button type="submit">Log in</button> </form> </div> {% endblock %} -
How do I fix my link in modal class on Bootstrap 5?
I have a template to show posts and each post has post.id. Also there is a button to open modal and "yes" button must delete post with post.id that I clicked. But when I do this it deleting the first post on current page instead of the right one I clicked before. ... <div class="col-md-9"> {% for post in page %} <div class="card-body"> <p class="card-text p-2"> <a class="link text-dark" href="/profile/{{post.author.username}}/"><strong class="d-block text-dark">@{{profile_user.username}}</strong> </a> {{post.text}} {% load thumbnail %} {% thumbnail post.image "960x339" crop="center" upscale=True as im %} <img class="card-img" src="{{ im.url }}"> {% endthumbnail %} </p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <a class="btn btn-sm text-muted" href="/profile/{{profile_user.username}}/{{post.id}}/" role="button"> ... </a> {% if user.username == profile_user.username %} <a class="btn btn-sm text-muted" href="/profile/{{profile_user.username}}/{{post.id}}/edit" role="button">...</a> <!-- Button trigger modal --> <button type="button" class="btn btn-sm text-muted" data-bs-toggle="modal" data-bs-target="#exampleModal"> ... </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Delete post?</h1> <button type="button" class="btn btn-sm text-muted" data-bs-dismiss="modal" aria-label="Close">...</button> </div> <div class="modal-footer"> <button type="button" class="btn btn secondary" data-bs-dismiss="modal">NO</button> <a role="button" class="btn btn-primary" href="/profile/{{profile_user.username}}/{{post.id}}/delete">YES</a> <!-- TODO Fix id problem--> </div> </div> </div> </div> {% endif %} </div> <small class="text-muted">{{post.pub_date}}</small> </div> </div> {% endfor %} ... I … -
No handlers could be found for logger "cuckoo"
Error I am running the Cocosandbox project. But I get this error when running Coco command Oops! Cuckoo failed in an unhandled exception! Sometimes bugs are already fixed in the development release, it is therefore recommended to retry with the latest development release available https://github.com/cuckoosandbox/cuckoo If the error persists please open a new issue at https://github.com/cuckoosandbox/cuckoo/issues === Exception details === Cuckoo version: 2.0.7 OS version: posix OS release: Ubuntu 22.04 jammy Python version: 2.7.18 Python implementation: CPython Machine arch: x86_64 Modules: alembic:1.0.10 androguard:3.0.1 argparse:1.2.1 attrs:21.4.0 beautifulsoup4:4.5.3 capstone:3.0.5rc2 cffi:1.15.1 chardet:2.3.0 click:6.6 colorama:0.3.7 configparser:4.0.2 contextlib2:0.6.0.post1 cryptography:3.3.2 cuckoo:2.0.7 django-extensions:1.6.7 django:1.8.4 dpkt:1.8.7 ecdsa:0.18.0 egghatch:0.2.3 elasticsearch:5.3.0 enum34:1.1.10 flask-sqlalchemy:2.4.0 flask:0.12.2 functools32:3.2.3.post2 future:0.18.3 gevent:1.2.2 greenlet:2.0.2 httpreplay:0.2.6 idna:2.10 importlib-metadata:2.1.3 ipaddress:1.0.23 itsdangerous:1.1.0 jinja2:2.9.6 jsbeautifier:1.6.2 jsonschema:3.2.0 mako:1.1.6 markupsafe:1.1.1 olefile:0.43 oletools:0.51 pathlib2:2.3.7.post1 peepdf:0.4.2 pefile2:1.2.11 pillow:3.2.0 pip:20.3.4 pycparser:2.21 pycrypto:2.6.1 pyelftools:0.24 pyguacamole:0.6 pymisp:2.4.106 pymongo:3.0.3 pyopenssl:21.0.0 pyrsistent:0.16.1 python-dateutil:2.4.2 python-editor:1.0.4 python-magic:0.4.12 python:2.7.18 pythonaes:1.0 requests:2.13.0 roach:0.1.2 scandir:1.10.0 scapy:2.3.2 setuptools:44.1.1 sflock:0.3.10 six:1.16.0 sqlalchemy:1.3.3 tlslite-ng:0.6.0 typing:3.10.0.0 unicorn:1.0.1 urllib3:1.26.18 wakeonlan:0.2.2 werkzeug:1.0.1 wheel:0.37.1 wsgiref:0.1.2 yara-python:3.6.3 zipp:1.2.0 No handlers could be found for logger "cuckoo" -
Django TypeError: fromisoformat: argument must be str
enter image description here class UserConfirmation(BaseModel): TYPE_CHOICES = ( (VIA_PHONE, VIA_PHONE), (VIA_EMAIL, VIA_EMAIL) ) code = models.CharField(max_length=4) verify_type = models.CharField(max_length=31, choices=TYPE_CHOICES) user = models.ForeignKey('users.User', models.CASCADE, related_name='verify_codes', db_constraint=False) expiration_time = models.TimeField(null=True) is_confirmed = models.BooleanField(default=False) def __str__(self): return str(self.user.__str__()) def save(self, *args, **kwargs): if not self.pk: if self.verify_type == VIA_EMAIL: self.expiration_tme = datetime.now() + timedelta(minutes=EMAIL_EXPIRE) else: self.expiration_tme = datetime.now() + timedelta(minutes=PHONE_EXPIRE) super(UserConfirmation, self).save(*args, **kwargs) -
Django single login page for both rest_framework and admin console
I am making a Django application which uses rest_frameworks (under urlpattern '/api') and the admin console (for user and group management, under urlpattern '/admin'). Currently they both have their own login page. I want both of them to use the same login page (a single login URL), and if the user successfully logs in, then if it is a superuser redirect to the admin console, and if not a superuser then redirect to '/foo'. I know you can insert a url pattern above the admin.site.urls to override its login (and logout) url patterns, but I want the login page to be '/login' not '/admin/login'. -
TemplateDoesNotExist at /home/ internal server error Django
my html file isn't displaying. folder path: D:\New folder\core\core\home View.py file in home app D:\New folder\core\core\home urls.py file in home app D:\New folder\core\core urls.py file in core project D:\New folder\core\core Settings.py file in core project index.html file in template which is in template file Tried every step help me solving this -
How to efficiently integrate Django and Azure with a Machine Learning pipeline for data analysis?
What is Django? What is the Python libraries & dependencies of Django? How Django can be use to deploy machine learning models into cloud? I'm trying to get the answers accurately and resolve my doubts. I'm currently working on a data analysis project using Django for web development and I'm struggling to efficiently integrate Django's and Azure with my machine learning pipeline. Specifically, I'm facing challenges in seamlessly connecting my Django models to the data preprocessing, feature engineering, and model training steps of the machine learning workflow. -
Django Admin: Filtering Products Based on Parent and Child Collections
I'm using a self-referential relationship in my Django Collection model, and I want to modify the admin to filter products based on the collection. Currently, when the client filters products by a specific collection, it only shows products directly associated with that collection and not its child collections. I've modified the get_search_results function in the admin, but the generated query seems to append my filter with an AND condition instead of using OR. `Here's the current implementation of the get_search_results function: def get_search_results(self, request, queryset, search_term): collection_filter = request.GET.get('collection__id__exact') if collection_filter: try: collection_id = int(collection_filter) collection_q = Q(collection_id=collection_id) | Q(collection__parent_id=collection_id) queryset = queryset.filter(collection_q) print(queryset.query) except ValueError: pass print(queryset.query) return queryset, False enter code her` print result : SELECT "shop_product"."id", "shop_product"."created_at", "shop_product"."updated_at", "shop_product"."deleted_at", "shop_product"."unit_price", "shop_product"."inventory", "shop_product"."min_inventory", "shop_product"."collection_id", "shop_product"."promotions_id", "shop_product"."discount_id", "shop_collection"."id", "shop_collection"."created_at", "shop_collection"."updated_at", "shop_collection"."deleted_at", "shop_collection"."parent_id" FROM "shop_product" INNER JOIN "shop_collection" ON ("shop_product"."collection_id" = "shop_collection"."id") LEFT OUTER JOIN "shop_product_translation" ON ("shop_product"."id" = "shop_product_translation"."master_id") WHERE ("shop_product"."collection_id" = 2 AND ("shop_product"."collection_id" = 2 OR "shop_collection"."parent_id" = 2)) ORDER BY "shop_product_translation"."title" ASC, "shop_product"."id" DESC The resulting query appears to use AND conditions, which might be the reason for not including child collection products. How can I modify this to use OR conditions instead and ensure that … -
Reason: CORS header ‘Access-Control-Allow-Origin’ missing Error in django
I was struggling with CORS lately in my django project. I followed all needed steps like installing django-cors-headers and here is my settings.py: INSTALLED_APPS = [ 'rest_framework', # dasti ezafe shod 'rest_framework_simplejwt', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'carat', # dasti ezafe shod 'data', 'price', 'users', 'marketplace' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = ( 'https://example.com', 'https://web.example.com', ) We build flutter web app and deployed in web.mydomain.com. from the beginning I faced with CORS errors but once I input those settings they all disappeared except one error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/media/images/image0_WEEP09I.png. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200. I see this error in console tab of the inspector in firefox. Here is a part of my server response: HTTP/2 200 OK Content-Type: application/json Vary: Accept, origin,Accept-Encoding Allow: GET, HEAD, OPTIONS X-Frame-Options: DENY X-Content-Type-Options: nosniff Referrer-Policy: same-origin Cross-Origin-Opener-Policy: same-origin Access-Control-Allow-Origin: https://web.example.com Access-Control-Allow-Credentials: true Content-Length: 1884 Date: Sat, 03 Feb 2024 22:01:07 GMT Alt-Svc: h3=":443"; ma=2592000, h3-29=":443"; ma=2592000, h3-Q050=":443"; ma=2592000, h3-Q046=":443"; ma=2592000, h3-Q043=":443"; ma=2592000, quic=":443"; ma=2592000; v="43,46 ` I am really confused, anyone can guide me how to fix it? I added … -
Subprocess readline gets stuck
I am trying to build a terminal that works based on user input. I managed to get the output but readline() hangs after the output is generated. Is there anyway to stop readline after the user command executes. I have added a small example function to demonstrate the issue: def communicate_with_subprocess(process, command): try: # Send the command to the subprocess process.stdin.write(command + '\n') process.stdin.flush() lines = [] # Read the output from the subprocess for _line in iter(process.stdout.readline, b''): if _line == '': break lines.append(_line) return lines except Exception as e: print(f"Error executing command '{command}': {e}") return None # Example usage: subprocess_instance = subprocess.Popen(["/bin/bash"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) try: while True: user_input = input("Enter a command (type 'exit' to quit): ") if user_input.lower() == 'exit': print("Exiting...") break output = communicate_with_subprocess(subprocess_instance, user_input) print("Output:", output) finally: subprocess_instance.terminate() subprocess_instance.wait() The goal is to integrate it into a Django web application so if there any alternative solution that doesn't involve subprocess, that works too. -
Best solution for a limited number of dynamic model fields in Django app
I'm using Django to build an app for outdoor professionals (educators, guides) to keep track of their experience. Basically a logbook but eventually with features like collaboration, mapping, and reporting. You can see what I have so far here Currently working on the Experience model. An Experience will have standard attributes like where did you go, when, was it a professional trip or your own personal recreation, who were your clients? But it should also have attributes specific to each outdoor pursuit. For paddling, canoes, kayaks, etc. For whitewater, what grade (1, 2, 3..)? For climbing, what grade (5.10, 5.11..) and how many pitches? I'll build in many of these attributes, but I also want the app to be flexible enough that users can add their own sport (e.g., barefoot snow skiing) and create fields based on what an employer would need to know about their experiences in that sport. Many of the posts on dynamic model fields in Django are several years old. For example, this mentions EAV but says there's no clear leader for an implementation. Today Django EAV 2 seems to be pretty strong? Apparently there are still efficiency concerns compared to JSON? Given that most of … -
How to display dates?
I would like to use a loop to create columns and display forward dates in them. The code below displays everything correctly in the console, but I don't know how to display it to the user. list=[1,2,3,4,5,6] for l in list: date = datetime.date.today() next_date=date+timedelta(days=l) print(next_date) {% for l in l %} <p>{{ l }} - {{next_date}}</p> {% endfor %} Displays six numbered rows but each has the same date, and I would like to do from today's date to the date in 6 days. I tried this method but I get an error: 'datetime.date' object is not iterable' {% for l in next_data %} <p>{{ l }} </p> {% endfor %} -
Appending object To StructBlock inside StreamField Wagtail
trying to create new task dynamically in my project on wagtail using StreamField and StructBlock but without success. Please help me, I'm losing my mind over this. The user sets some parameters in the template and then supposed to create a new task... I tried three different options but this came out. I have with and without json.dumps and converting it into a StreamField or StructBlock Really losing my mind😀 this is my code: models.py: tasks = StreamField([ ("task", blocks.StructBlock([ ("name", blocks.CharBlock(required=True, max_length=150)), ("description", blocks.RichTextBlock(required=False)), ("image", ImageChooserBlock(required=False)), ("subtasks", blocks.ListBlock(blocks.StructBlock([ ("name", blocks.CharBlock(required=True, max_length=150)), ("description", blocks.RichTextBlock(required=False)), ]))) ])) ],null=True,blank=True,use_json_field=True) views: def create_task(request, project_id): # create a new task project = Project.objects.get(pk=project_id) # new_task = { # "name": request.POST["task_name"], # "description": str(request.POST["task_description"]), # "image": None, # "subtasks": [], # } # project.tasks.append(json.dumps(new_task)) # \Lib\site-packages\wagtail\blocks\stream_block.py", line 610, in _construct_stream_child # type_name, value = item # ^^^^^^^^^^^^^^^^ # ValueError: too many values to unpack (expected 2) # new_task = ('task',{ # "name": request.POST["task_name"], # "description": str(request.POST["task_description"]), # "image": None, # "subtasks": [], # }) # project.tasks.append(json.dumps(new_task)) # \Lib\site-packages\wagtail\blocks\stream_block.py", line 610, in _construct_stream_child # type_name, value = item # ^^^^^^^^^^^^^^^^ # ValueError: too many values to unpack (expected 2) new_task = { 'type': 'task', 'value': { … -
ModuleNotFoundError: No module named 'xppSite' when gunicorn and application are configured in different locations
I am getting this error and suspect failure could be due to my folder structure. That means virtual env folder is at: WorkingDirectory=/home/xxxx/xxagent ExecStart=/home/xxxx/xxagent/virtualenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ xppSite.wsgi:application and application files are at different location: /home/xxxx/xxagent/workspace/deploy/xppSite/wsgi.py In such situation, how do I fix this error: Feb 03 05:52:30 ubuntu-sfo3-01 gunicorn[99254]: File "<frozen importlib._bootstrap>", line 1176, in _find_and_load Feb 03 05:52:30 ubuntu-sfo3-01 gunicorn[99254]: File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked Feb 03 05:52:30 ubuntu-sfo3-01 gunicorn[99254]: ModuleNotFoundError: No module named 'xppSite' Feb 03 05:52:30 ubuntu-sfo3-01 gunicorn[99254]: [2024-02-03 05:52:30 +0000] [99254] [INFO] Worker exiting (pid: 99254) Feb 03 05:52:30 ubuntu-sfo3-01 gunicorn[99252]: [2024-02-03 05:52:30 +0000] [99252] [ERROR] Worker (pid:99253) exited with code 3 Feb 03 05:52:30 ubuntu-sfo3-01 gunicorn[99252]: [2024-02-03 05:52:30 +0000] [99252] [ERROR] Worker (pid:99254) was sent SIGTERM! Feb 03 05:52:30 ubuntu-sfo3-01 gunicorn[99252]: [2024-02-03 05:52:30 +0000] [99252] [ERROR] Shutting down: Master Feb 03 05:52:30 ubuntu-sfo3-01 gunicorn[99252]: [2024-02-03 05:52:30 +0000] [99252] [ERROR] Reason: Worker failed to boot. Feb 03 05:52:30 ubuntu-sfo3-01 systemd[1]: gunicorn.service: Main process exited, code=exited, status=3/NOTIMPLEMENTED Feb 03 05:52:30 ubuntu-sfo3-01 systemd[1]: gunicorn.service: Failed with result 'exit-code'. Thanks in advancestrong text -
SSL Certificate with Squarespace as DNS, Heroku as server, and QuotaGuard Static as static IP address provider: CN and Hostname mismatch
Squarespace is saying my SSL certificate is unavailable and Google Search also returns http instead of https, even though my site is able to use https and is flagged as secure by every browser I've tested: https://www.bencritt.net This is definitely related to how my website hosting is set up. My website is hosted on Heroku because it's a Django site and Squareqpace doesn't support hosting for sites developed with that framework. Heroku, unfortunately, uses dynamic IP addresses. So, my server's IP address is constantly changing. This makes setting up A records difficult. I have to run a third party service called QuotaGuard Static on my Heroku server that provides me with two static IP addresses. I use these two IP addresses for my A records in my DNS settings in Squarespace. At some point in the daisy-chain, the SSL is getting obscured and making Squarespace and Google both think I don't have it. Do you know how I can get both Squarespace and Google Search to recognize my website's SSL? I've tried adding schema to my website's code that specifies https in an attempt to force Google Search to return the https version of my site in Search results. I've … -
Django return render to datatable from edit view (or refhesh page to show uptated datatable)
I have a template that shows me a datatable, for each record a button that edits/delete the record through a form, sends it to a view and saves it. I need it to return me to the same template that has the table with the updated data. Currently it redirects me to the template but without showing me the datatable With return redirect it returns me to the original page without showing me anything With return render it shows me the datatable, but it changes the URL What am I doing wrong? Sorry for my English, I'm a junior View def delete_itemresumen(request, id): if request.method == "POST": ..... ..... ..... coleccion = Auxiliarresumen.objects.filter( Q(mes__icontains=mes) & Q(anio__icontains=anio) & Q(codcuentabanco=codban) ).distinct() form = RegistroBuscarResumen(initial={'accion':'buscar', 'id_codcuentabanco':codban, 'id_periodo':camp2}) return redirect("/bancos/procesarresumen") #or return render(request, 'bancos/procesarresumen.html', {'form': form, 'colecc': coleccion}) And HTML {% if colecc %} <table id="Listaitems" class="table table-hover table-sm text-left" style="white-space: nowrap; overflow-x: auto;" > <thead class="thead-light"> <tr> <th scope="col">Fecha</th> <th scope="col">Concepto</th> <th scope="col">Subconcepto</th> <th scope="col">Observacion</th> <th scope="col">Importe</th> <th scope="col">C/D</th> <th scope="col">Acciones</th> </tr> </thead> <tbody center> {% for col_obj in colecc %} <tr> <!-- <td<th scope="row">{{col_obj.fecha}}</th> --> <td class="h5 small">{{col_obj.fecha}}</td> <td class="h5 small">{{col_obj.codsubconcepto.codconcepto.descripcion}}</td> <td class="h5 small">{{col_obj.codsubconcepto.descripcion}}</td> <td class="h5 small">{{col_obj.descripcion}}</td> <td class="h5 small">{{col_obj.importe}}</td> <td class="h5 … -
Caddy Docker compose breaks when adding internal network
I'm Dockerizing my Django web application that uses a postgres db. Served over Caddy. Using caddy-docker-proxy I was able to get my django container/web app working with Caddy. But then when I added my postgres db to my compose file, Caddy no longer redirected my domain to django. ]1 Instead I get a Not Found. Here's my full docker compose file version: "3.7" services: web: build: . command: sh -c "gunicorn notobackend.wsgi:application --bind 0.0.0.0:8000" restart: always ports: - "8000:8000" expose: - 8000 environment: - POSTGRES_DB=supadb - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres networks: - caddy - internal container_name: web depends_on: - db links: - db:db labels: caddy: supa.blog caddy.reverse_proxy: "{{upstreams 8000}}" env_file: - .env db: container_name: db image: postgres:latest restart: always expose: - 5432 ports: - 5432 environment: - POSTGRES_DB=supadb - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - './data/db:/var/lib/postgresql/data' networks: - internal caddy: image: lucaslorentz/caddy-docker-proxy:ci-alpine ports: - 80:80 - 443:443 environment: - CADDY_INGRESS_NETWORKS=caddy networks: - caddy volumes: - /var/run/docker.sock:/var/run/docker.sock - caddy_data:/data restart: unless-stopped networks: caddy: external: true internal: external: false driver: bridge volumes: caddy_data: {} If I remove the "internal" network from the db service, Caddy correctly serves my django web app but now I get a 500 server error since I don't have my …