Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django logger only logging to console from celery worker process
I have a following logging config: "root": { "level": "ERROR", "handlers": ["console", "server_file"], }, "handlers": { "celery_file": { "class": "logging.handlers.RotatingFileHandler", "level": "DEBUG", "filename": os.path.join(ROOT_LOGS_DIR, "celery", "celery.log"), "formatter": "standard", "maxBytes": 1024 * 1024 * 50, # 50 MB "backupCount": 30, }, "server_file": { "class": "logging.handlers.RotatingFileHandler", "level": "DEBUG", "filename": os.path.join(ROOT_LOGS_DIR, "server.log"), "formatter": "standard", "maxBytes": 1024 * 1024 * 50, # 50 MB "backupCount": 30, }, "loggers": { # '': {'handlers': ["root"], "level": "DEBUG", "propagate": True, }, 'django': {'handlers': ['django'], 'level': 'DEBUG', 'propagate': False, }, "celery": { "handlers": ["celery_file"], "level": "INFO", "propagate": True, }, From celery task, log = logging.getLogger("celery.inbound_outbound_jobs") log.error("Hello, World!") # this won't be written to files. Only Console. I run this task using celery-beat and worker. celery -A log_project beat --loglevel=info celery -A log_project worker --loglevel=info But this is not writing logs to server.log and celery.log. Only console logging is happening. When running this task directly from django server and not as celery worker process, this is working in all celery.log, server.log and console. Can anyone help understand this? -
Django logging - how does propagate work?
I have a following logging config: "root": { "level": "ERROR", "handlers": ["console", "server_file"], }, "handlers": { "celery_file": { "class": "logging.handlers.RotatingFileHandler", "level": "DEBUG", "filename": os.path.join(ROOT_LOGS_DIR, "celery", "celery.log"), "formatter": "standard", "maxBytes": 1024 * 1024 * 50, # 50 MB "backupCount": 30, }, "loggers": { # '': {'handlers': ["root"], "level": "DEBUG", "propagate": True, }, 'django': {'handlers': ['django'], 'level': 'DEBUG', 'propagate': False, }, "celery": { "handlers": ["celery_file"], "level": "INFO", "propagate": True|False, }, In application, log = logging.getLogger("celery.inbound_outbound_jobs") print(log.handlers) # output: [] No handlers log.error("test") My question is : when celery logger propagate =True, will this log be handled by celery logger? Also does it propagate to root logger? when propagate=False, will log be still handled by celery logger? -
django and react access control over REST
I am new to react and webservices, I have a Django+DRF+react project. I am using one of react open source FW( not naming it because this is a theoretical question ). this FW gives you an access control API so you can implement your own. as for my little understanding, django manages access pretty well, So I managed hook up the FW access control with my DRF, which request for a permission based resource and user action and I am getting the response and its all working well(I think). just to make sure we are all on the same page, I am talking about restricting the react UI side, my DRF already managing the permissions of the data on the backend. but just so user wont even be able to see a button referencing an area out of there permission. the issue is the hit on the server, there are many calls per page and I, with my very little knowledge in this field, I'm not sure is this OK ? is this conventional ? does implementing such access control which requires API call is normal procedure ? -
Uvicorn dependency issue
I want to create a Django webserver capable of handling HTTP requests and WebSocket requests. I am using uvicorn so that both types of requests can be handled in the same server instance. Whenever I try to launch my server with the command: uvicorn core.asgi:application --host 0.0.0.0 --port 8000 I get the error message: python3.11/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 11, in import websockets.legacy.handshake ModuleNotFoundError: No module named 'websockets.legacy' Here is my conda file: name: [env-name] channels: conda-forge defaults dependencies: channels python=3.11 daphne django djangorestframework uvicorn boto3 pip pip: django-cors-headers websockets "uvicorn[standard]" I'm not sure why this is happening. I've tried pip installing all of the dependencies, reinstalling the virtual environment, but it always says "Requirement Already Satisfied". -
ModuleNotFoundError: No module named 'backend' when running my make seed data script in django-admin
I am at my wit's end as I am trying to debug and figure out what the issue is. When trying to search, I just get annoyingly AI responses which I don't want so decided to write a question here on SO. Here is my traceback: Traceback (most recent call last): File "/api/manage.py", line 22, in <module> main() File "/api/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/api/api/companies/models.py", line 5, in <module> from backend.api.models import BaseModel ModuleNotFoundError: No module named 'backend.api' make: *** [seed] Error 1 Here is my settings.py INSTALLED_APPS: INSTALLED_APPS = [ # Local apps 'api', 'api.companies', 'api.assessments', 'api.users', "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] Here is my file … -
Django does not change the default storage system
I have a django application that works perfectly fine with storing media locally. I have decided to change the default storage to be able to store files on a remote cloud system (s3), I set the default storage in my settings.py as below: DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" and I verified that this variable is available in django shell: >>> from django.conf import settings >>> print(settings.DEFAULT_FILE_STORAGE) storages.backends.s3boto3.S3Boto3Storage however, django keeps using the default file storage system (FileSystemStorage): >>> from django.core.files.storage import default_storage >>> print(default_storage.__class__.__name__) # Should print "S3Boto3Storage" FileSystemStorage >>> print(default_storage) <django.core.files.storage.filesystem.FileSystemStorage object at 0x000002A6E6C8FA10> it is a very simple code and there is no possibility of override of these values in my code, not sure why django does not pick up the default file system provided in settings.py, any idea? -
Queryset sorting worked in development/sqlite3 db but it does not work when I deploy it to a shared web hosting with MySQL Database
I am sorting a queryset to show tasks with due date closest to/past current date to show first but sort tasks with no due dates to the bottom of the list. My code works in development using sqlite3 but when I deploy it to my shared hosting site with a MySQL backend, sorting does not work. There is no error message, it just won't sort. My model: task_name = models.CharField(max_length=100) task_description = models.TextField(max_length=2000, blank=True, null=True) due_date = models.DateField(null=True, blank=True) date_completed = models.DateTimeField(null=True, blank=True) assigned_to = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.SET_NULL, related_name='workorders_assigned', blank=True, null=True) completed_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='workorders_completed', blank=True, null=True) isDeleted = models.BooleanField(default=False) The code I used to sort the due date are: workorders = workorders.extra(select ={'custom_dt': 'date(due_date)'}).order_by(F('due_date').asc(nulls_last=True)) and workorders = workorders.extra(select={'date_is_null': 'due_date IS NULL',}, order_by=['date_is_null', 'due_date']) both worked in development but neither worked when deployed. Thanks in advance for your help. -
How to efficiently exclude already assigned objects in a Django QuerySet?
I am working on a Django project where I need to filter objects based on their status while excluding those that are already assigned in another model. I have two models: CartObject – Stores all objects. OnGoingProcess – Tracks objects that are currently assigned. Each OnGoingProcess entry has a OneToOneField relationship with CartObject, meaning each object can only be assigned once. My goal is to fetch all objects with a specific status but exclude those that are already assigned in OnGoingProcess. Models: class CartObject(models.Model): object_id = models.CharField(max_length=100, unique=True) status = models.CharField(max_length=50, choices=[("pending", "Pending")]) # Other fields... class OnGoingProcess(models.Model): user = models.OneToOneField(DeliveryProfile, on_delete=models.CASCADE, related_name="ongoing_process") associated_object = models.OneToOneField(CartObject, on_delete=models.CASCADE, related_name="associated_process", blank=True, null=True) # Other fields... Current View Code: @user_passes_test(lambda user: user.is_staff) def process_manager_view(request): # Get objects that are already assigned in OnGoingProcess assigned_objects = OnGoingProcess.objects.values_list('associated_object', flat=True) # Exclude objects that are already assigned available_objects = CartObject.objects.filter(status="pending").exclude(id__in=assigned_objects).order_by("-id") context = { "available_objects": available_objects, } return render(request, "useradmin/available-objects.html", context) Issue: I am using values_list('associated_object', flat=True) to extract the assigned object IDs. Then, I am using exclude(id__in=assigned_objects) to filter out those objects. Is this the most efficient way? Or is there a better Django ORM method to achieve the same result? Should I use Subquery(), isnull=False, … -
How to force python sintax in pre-commit?
How to force variable and function names and follow python pep 8 style in git pre-commit? I'm working in a Django project and I want to force developers to write code following the PEP 8 style for variables and function, preventing CamelCase in variable name like this example: class MyModel(models.Model): roomName = models.CharField() roomNumber = models.CharField() That is, I would like this declaration to be forced by git to have the following syntax: class MyModel(models.Model): room_name = models.CharField() room_number = models.CharField() In the case of functions, instead of: def checkRules()... it would be something like: def check_rules()... I have this .pre-commit-config.yaml but some bad code are passing and if we can force good practice in pre-commit that would be great. repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.6.0 hooks: - id: check-added-large-files - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/psf/black rev: 24.4.2 hooks: - id: black args: ["--line-length", "120"] - repo: https://github.com/PyCQA/flake8 rev: 7.1.0 hooks: - id: flake8 additional_dependencies: [] - repo: https://github.com/pycqa/isort rev: 5.13.2 hooks: - id: isort args: ['--order-by-type', "--profile", "black", "--filter-files"] name: isort (python) - id: isort name: isort (cython) types: [cython] - id: isort name: isort (pyi) types: [pyi] -
drf permissions' depending serialization
I'm using Django REST framework and want to have a standard users, admins and moderators. All of them have different permissions obviously. So, the question is, can we return the data about some user, depending on who's accessing to it: if any of admins sending the request to the api, then they should get all of the available information on the user, if a moderator is accessing the endpoint, then they should get all data on the user excluding two fields, if user is trying to get information about THEMSELVES, then they should get some fields (e.g. username, id) and also email should be included, but if user's trying to get information about the OTHER person, then email should NOT be provided for them -
Add custom field to page settings in Django CMS
I have a PageExtension with a custom field in my Django CMS app. How do I make this custom field editable in the Page's Settings or Advanced Settings? -
Check if a user has permission to view another page in Django CMS
I would like to check if a user has the permissions (is part of the groups necessary) to view a different page than the current one. from cms.models.permissionmodels import PagePermission if PagePermission.objects.filter(page=page_to_check, user=request.user, can_view=True).exists(): always returns false. How can I check if the user should be able to view the page_to_check? Thank you! -
Django access to related model fields in form view
I'm trying to create a form that retrieves all objects for one table (students) in the database and let the user select which one of them they want to pick to send an email. Right now I'm not able to properly render the students data, but it is actually showing the right number of students. If I pick the second input the one render by student.tag it actually retrieves the right information but if I pick the first one there is no information submitted. Here is my form: class SendEmailStudentsForm(forms.Form): students = forms.ModelMultipleChoiceField( queryset=Students.objects.all(), widget=forms.CheckboxSelectMultiple, required=False) And the template I'm using: <form action="#" method="post"> {% csrf_token %} {% for student in form.students %} <ul> <li>{{ forloop.counter }} - {{ student.id }}</li> <li>Email: - {{ student.email }}</li> <li>Add student<input type="checkbox" id="{{ student.id }}"></li> <li>Add <span>{{ student.tag }}</span></li> </ul> {% endfor %} <button type="submit" class="btn btn-primary">Send emails</button> <a href="{% url 'students:index' %}" class="btn btn-primary">Back</a> </form> And my view: def select_students_emails(request): if request.method == "POST": form = SendEmailStudentsForm(request.POST) if form.is_valid(): print(form.cleaned_data) # send_mail(...) return HttpResponseRedirect(reverse('students:index')) else: form = SendEmailStudentsForm() return render(request, 'students/select_students.html', context={'form': form}) -
which type of python framework is good for data analytics [closed]
I am learning a data analytics course provided by Google in Coursera, Python Programming is not included in, so i want to learn more about python for data analytics practice questions in parallel. I did not install the software yet, i want to get a recommendation from the experienced individuals have used before. -
Platform.sh CLI Login Fails with HTTP 500 Error and Symfony Console Error
I’m encountering issues while trying to log in to Platform.sh using the command-line interface (CLI). When I run platform login, the CLI opens a URL in my browser (http://127.0.0.1:5000), but the browser displays an error: “This page isn’t working. 127.0.0.1 is currently unable to handle this request.” The CLI output is: Opened URL: http://127.0.0.1:5000 Please use the browser to log in. Help: Leave this command running during login. If you need to quit, use Ctrl+C. If I try to run platform create without logging in, the CLI prompts me to log in. When I confirm, I receive a fatal error: If I try to run platform create without logging in, the CLI prompts me to log in. When I confirm, I receive a fatal error: Fatal error: Uncaught Error: Class "Symfony\Component\Console\Event\ConsoleErrorEvent" not found in phar://C:/Users/Макар/AppData/Local/Temp/platformsh-cli-8.2.26-4.22.0/phar-4.22.0/vendor/symfony/console/Application.php:1027 Stack trace: #0 phar://C:/Users/Макар/AppData/Local/Temp/platformsh-cli-8.2.26-4.22.0/phar-4.22.0/src/Application.php(429): Symfony\Component\Console\Application->doRunCommand() #1 phar://C:/Users/Макар/AppData/Local/Temp/platformsh-cli-8.2.26-4.22.0/phar-4.22.0/vendor/symfony/console/Application.php(255): Platformsh\Cli\Application->doRunCommand() #2 phar://C:/Users/Макар/AppData/Local/Temp/platformsh-cli-8.2.26-4.22.0/phar-4.22.0/vendor/symfony/console/Application.php(148): Symfony\Component\Console\Application->doRun() #3 phar://C:/Users/Макар/AppData/Local/Temp/platformsh-cli-8.2.26-4.22.0/phar-4.22.0/bin/platform(37): Symfony\Component\Console\Application->run() #4 C:\Users\Макар\AppData\Local\Temp\platformsh-cli-8.2.26-4.22.0\phar-4.22.0(10): require('...') #5 {main} thrown in phar://C:/Users/Макар/AppData/Local/Temp/platformsh-cli-8.2.26-4.22.0/phar-4.22.0/vendor/symfony/console/Application.php on line 1027 I’ve tried: Checking if port 5000 is in use (it doesn’t seem to be). Using a different browser. Disabling browser extensions. Temporarily disabling my firewall. I am using Windows. I am trying to deploy a Django project. Any suggestions on … -
RTSP Live Camera in Django Server or React App
I wanna stream camera live videos in my website using django and react. in VLC -> Media -> Open Network Stream I set this RTSP url in Network tab and I can see live camera video perfectly: rtsp://user:password%40123@ip:port But I can't do it in django. or maybe I don't need to do this on django and can do it on react only. best I could achieve was this code which only worked in local with a VPN: class VideoCamera: def __init__(self): url = "rtsp://user:password%40123@ip:port" self.video = cv2.VideoCapture(url, cv2.CAP_FFMPEG) if not self.video.isOpened(): print("Failed to open RTSP stream") self.running = False return self.running = True self.grabbed, self.frame = self.video.read() self.lock = threading.Lock() # Prevents race conditions self.thread = threading.Thread(target=self.update, daemon=True) self.thread.start() def update(self): while self.running: grabbed, frame = self.video.read() if not grabbed: print("Failed to grab frame, retrying...") continue # Prevents self.frame from being None with self.lock: self.frame = frame def get_frame(self): with self.lock: if self.frame is None: return None success, jpeg = cv2.imencode('.jpg', self.frame) if not success: print("Encoding failed") return None # Prevent sending invalid data return jpeg.tobytes() def stop(self): self.running = False self.thread.join() # Ensures clean exit self.video.release() def get_camera(camera): while camera.running: frame = camera.get_frame() if frame: yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' … -
How to make django form dropdown shows items created by the author only not by all the users?
I have created two models Topics and entries. User can create topic and also create the entries for each topic they created. In Create Topic Entry class, the fields 'topic' showing all topics created by all users in the form dropdown menu. However, I just want the form dropdown shows topics created by the author only so that user can only create the entry for their topic but not others topic. How to do that? models.py: class Topic(models.Model): '''A topic that user will add the content about.''' title = models.CharField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) class Entries(models.Model): '''Entries and Topic will have many to one relationship''' topic = models.ForeignKey(Topic, on_delete=models.CASCADE) name = models.CharField(max_length=100) text = models.TextField() entries_image = models.ImageField(default= 'default.jpg', upload_to ='images') date_added = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) views.py class CreateTopic(LoginRequiredMixin, CreateView): model = Topic fields = ['title'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class CreateTopicEntry(LoginRequiredMixin, CreateView): model = Entries fields = ['topic', 'name','text','entries_image'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) Topic_form.html: <div> <form method="POST"> {% csrf_token %} {% if object %} <h4 class="mb-4">Update your Topic &#128071</h4> {{ form|crispy }} {% else %} <h4 class="mb-4">Create your new Topic &#128071</h4> {{ form|crispy }} {% endif %} <div … -
Assistance Needed: MySQL Access Denied and User Privileges Error
Despite following the standard setup instructions, I am encountering an "Access denied for user" error when trying to perform database migrations.the error encountered is 'django.db.utils.OperationalError: (1045, "Access denied for user 'Nooshin'@'10.0.5.126' (using password: YES)")' my database configuration in setting.py file is : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'Nooshin$ads', 'USER': 'Nooshin', 'PASSWORD': 'ads123', 'PORT': '3306', 'HOST': 'Nooshin.mysql.pythonanywhere-services.com', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, } } and here is my database interface in pythonanywhere please help me solve the issue I am facing. -
Access to XMLHttpRequest at ' ' from origin ' ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No
Access to XMLHttpRequest at ' ' from origin ' ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. i am facing this issue while i am trying to host my project from vercel I got everything right in my settings.py file but got this error over and over while i tried to host my project from vercel . I am using django 5.1.6 django-cors-headers: 4.6.0 djangorestframework: 3.15.2 i am also using react as my frontend framework. i also put this file as vercel.json in my backend directory but still got this error { “builds”: [ { “src”: “backend/wsgi.py”, “use”: “@vercel/python”, “config”: { “maxLambdaSize”: “15mb” } } ], “routes”: [ { “src”: “/(.*)”, “dest”: “backend/wsgi.py” } ] } this is my setting file please someone help me through this error CORS_ALLOW_ALL_ORIGINS =True ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'corsheaders', 'rest_framework', 'rest_framework_simplejwt', ] 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.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
Django Rest API : ValueError: badly formed hexadecimal UUID string
I'm getting the following error while attempting to create a superuser on Django 5.0.4 Rest API ValueError: badly formed hexadecimal UUID string Here is the stack trace : File "/home/ubuntu/myapi_aws/my_auth/models.py", line 55, in get_by_natural_key uuid = UUID(uuid) File "/usr/lib/python3.10/uuid.py", line 177, in __init__ raise ValueError('badly formed hexadecimal UUID string') ValueError: badly formed hexadecimal UUID string Model definitions: from uuid import UUID class UserManager(DjangoUserManager): def get_by_natural_key(self, uuid): if not isinstance(uuid, UUID): uuid = UUID(uuid) return self.get(uuid=uuid) class User(AbstractUser): """" Custom user model to change behaviour of the default user model such as validation and required fields. """ uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True,verbose_name=_("UUID")) What I've tried delete migrations flush database using flush command reset database using reset_db command -
How can I send data to intermediate page when using custom django action?
I want to add custom django action that allows to change choice field for my model. I want intermediate page, where user can set the new value for this field. This field should be on another URL. The problem is that I need somehow send selected ids to this intermediate page, and GET params is not an option, because the amount of ids can be too big, and I have project restriction of url length to be strictly less then 8000 symbols. Right now I have this setup and it works great, but I have no clue how can I send selected object ids without GET params. forms.py class MyModelChangeStepForm(Form): _selected_action = forms.CharField(widget=forms.MultipleHiddenInput) step_code = forms.ChoiceField(choices=...) admin.py @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): actions = ('change_mymodel_step',) @admin.action(description='') def change_mymodel_step(self, request, queryset): selected_mymodel_ids = list(queryset.values_list('id', flat=True)) mymodels_count = len(selected_mymodel_ids) if 'apply' in request.POST: form = MyModelChangeStepForm(request.POST) if form.is_valid(): new_step_code = form.cleaned_data['step_code'] # use `filter` instead of `queryset` to prevent FieldError because queryset has annotations MyModel.objects.filter(pk__in=selected_mymodel_ids).update(step_code=new_step_code) for mymodel in queryset: self.log_change(request, mymodel, '...') self.message_user(request, '...') return None self.message_user( request, '...', level=messages.ERROR, ) return None form = MyModelChangeStepForm(initial={ '_selected_action': selected_mymodel_ids, 'action': request.POST['action'], }) return render( request, 'mymodel_change_step_code.html', {'form': form, 'objects': queryset, 'mymodels_count': mymodels_count}, ) mymodel_change_step_code.html {% … -
Django model formset to update objects with user input
Having some troubles with understanding objects update using model formset. Creation of objects is not a problem as flow is clear. Updating predefined objects is not a problem as well as we use instance to pass instances. However the question is : How to update objects which user inputs in model formset fields? Let's say I have some dummy code: models: class Product(models.Model): serial_number = Charfield() config = ForeignKey(Configuration) class Configuration(models.Model): items = ManyToMany(Item) forms: class ProductFormset(forms.BaseModelFormSet): def __init__(self, *args, **kwargs): super(ProductFormset, self).__init__(*args, **kwargs) self.queryset = models.Product.objects.none() class ProductForm(forms.ModelForm): class Meta: model = Product fields = ["serial_number"] ProductFormSet = modelformset_factory(Product, ProductForm, ProductFormset, min=1, extra=0) So whenever user inputs some serial_number(s) on creation page I'm able to use clean_data to process new objects and save(). Whenever I use object's DetailView to redirect to update link I'm able to pass object id and use it to assign as instance and all works fine for save(). But on update page I want to let user decide which products to edit. So until form submitted the serial_number(s) are unknown and can't be used as initial. Formset is_valid() returns False as well as field error risen Object already exists. I'm also using JS to dynamically … -
Prometheus can't scrape Django metrics (400 Bad Request) when running in Docker container
I'm trying to collect prometheus-django metrics from a Django application running inside a Docker container. The metrics are exposed at http://127.0.0.1:8888/prometheus/metrics, and I can access them from my local machine. However, when Prometheus (running in another container) tries to scrape them, I get a 400 Bad Request response. 400 Bad Request docker-compose: backend: build: ./store/ container_name: store_backend env_file: .env volumes: - static:/backend_static/ - media:/app/media/ nginx: build: ./nginx/ container_name: store_nginx env_file: .env volumes: - static:/staticfiles/ - media:/app/media/ ports: - ${PORT}:80 depends_on: - backend prometheus: build: ./monitoring container_name: store_prometheus volumes: - prometheus_data:/prometheus command: - "--config.file=/etc/prometheus/prometheus.yml" ports: - "9090:9090" prometheus.yml: global: scrape_interval: 5s scrape_configs: - job_name: 'django' static_configs: - targets: ['store_backend:8888'] metrics_path: '/prometheus/metrics' nginx.conf: location /prometheus/metrics/ { proxy_set_header Host $http_host; proxy_pass http://backend:8888/prometheus/metrics/; } While troubleshooting this issue, I set ALLOWED_HOSTS = ['*'], but it doesn't work. So Prometheus can connect to the Django container, but the Django app rejects the request. Can you help me to understand what might be causing this issue? -
Django - pagination for inline models
I realize this is probably a beginner level error, but I'm out of ideas. I need to add pagination to Inline model for admin page. I'm using Django 1.8.4 ( yup, I know it's really old ) and python 3.6.15. Inside admin.py: class ArticleInline(GrappelliSortableHiddenMixin, admin.TabularInline): model = ArticleSection.articles.through raw_id_fields = ("article",) related_lookup_fields = { 'fk':['article'], } extra = 1 class ArticleSectionsAdmin(reversion.VersionAdmin): list_display = ('name','slug','template_file_name') inlines = [ArticleInline] admin.site.register(ArticleSection,ArticleSectionsAdmin) Inside models.py: class ArticleSection(Section): articles = models.ManyToManyField(Article, verbose_name=_("article"), through="M2MSectionArticle", related_name="sections") limit = models.PositiveSmallIntegerField(default=10) class Meta: db_table = 'sections_article_section' verbose_name = _("article section") verbose_name_plural = _("articles sections") def content(self, request): query = Q(m2msectionarticle__visible_to__isnull=True) & Q(m2msectionarticle__visible_from__isnull=True) query.add(Q(m2msectionarticle__visible_to__gte=timezone.now(), m2msectionarticle__visible_from__lte=timezone.now()), Q.OR) limit = self.limit_override if hasattr(self, 'limit_override') and self.limit_override is not None else self.limit return self.articles.filter(query).published().prefetch_related('images').order_by('m2msectionarticle__position')[:limit] class M2MSectionArticle(models.Model): section = models.ForeignKey(ArticleSection, related_name='section_articles') article = models.ForeignKey(Article, verbose_name=_('article')) position = models.PositiveSmallIntegerField(_("position"), default=0) visible_from = models.DateTimeField("Widoczne od", null=True, blank=True) visible_to = models.DateTimeField("Widoczne do", null=True, blank=True) class Meta: db_table = 'sections_section_articles' ordering = ["position"] I found django-admin-inline-paginator and it seems to work for everyone else, but I get "Function has keyword-only parameters or annotations, use getfullargspec() API which can support them" when I use TabularInlinePaginated instead of admin.TabularInline. from django_admin_inline_paginator.admin import TabularInlinePaginated class ArticleInline(GrappelliSortableHiddenMixin, TabularInlinePaginated): model = ArticleSection.articles.through raw_id_fields = … -
Using special characters in a Django template tags
I am trying to make a field with Django Tweaks and I am trying to add some HTMX attributes. I want to use the following syntax: {% render_field field <other attributes> hx-vals='{"country": this.value}' %} However, if I use this syntax, I get an rendering error. This is because it tries to interpret the brackets. I have searched a lot on the internet, and each answer for escaping characters in Django Templates, suggests using the verbatim tag or something similar. The problem is that that only allows you to render special characters, not use them in a variable. Is there a solution that allows me to escape special characters in Django template variables? Right now I am sending the string in the context, but that is not ideal. Thanks in advance!