Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make the session lifetime counted from the start of the page load, checked every minute and not disrupted by post request?
session life settings SESSION_COOKIE_AGE=120 (2 minutes) now a question, at the first rendering of the page of the template confirm_email.html the form of code input from 6 fields is loaded, if you do not enter the code (inactivity) and wait, then every minute will be checked to send a get request from the script check_session.js every minute in the view CheckSession and it will give json response back and 30 seconds before the end of session life will trigger the script timer.js and after the end of 2 minutes the user will be redirected to the main page - everything is fine here!!!!. And if at the first rendering of the confirm_email.html template page (for example, the page loaded at 18:00:00) the form of code input from 6 fields is loaded, and suppose you enter an incorrect code after 30 seconds (at 18:00:30), then a post request is sent to the ConfirmEmail view and the check_session script. js will send a request to the CheckSession view from this post request time, i.e. the script will send a request at 18:01:30, i.e. a minute from the post request, but not from the time the page loaded at 18:00:00. Where it is … -
How to connect a react native app without docker to a django docker container?
I have a react native app for web configured. And I have a django app for the backend. I can connect this two apps with each other. But now I have dockerized the django app. But not the react app. And if I run the react app with the running django docker app. I get this error if I try to login from the react app: authentication.service.js:32 POST http://192.168.1.135:8000/api/user/token/ 400 (Bad Request) So this is my docker compose.yml file: version: "3.9" name: dwl_backend services: app: image: crdierenwelzijn2.azurecr.io/web1 build: context: C:\repos\dierenwelzijn\dwl_backend dockerfile: Dockerfile args: DEV: "true" command: - sh - -c - "python manage.py wait_for_db && python ./manage.py migrate && python ./manage.py runserver 0:8000" depends_on: db: condition: service_started required: true environment: DB-PORT: "5432" DB_HOST: db DB_NAME: name DB_PASS: pass DB_USER: user DEBUG: "1" DJANGO_ALLOWED_HOSTS: localhost 127.0.0.1 [::1] SECRET_KEY: django-insecure-kwuz7%@967xvpdnf7go%r#d%lgl^c9ah%!_08l@%x=s4e4&+(u networks: default: null ports: - mode: ingress target: 8000 published: "8000" protocol: tcp volumes: - type: bind source: C:\repos\dierenwelzijn\dwl_backend\DierenWelzijn target: /app bind: create_host_path: true db: environment: POSTGRES_DB: db POSTGRES_PASSWORD: password POSTGRES_USER: user image: postgres:13-alpine networks: default: null volumes: - type: volume source: dev-db-data target: /var/lib/postgresql/data volume: {} networks: default: name: dwl_backend_default volumes: dev-db-data: name: dwl_backend_dev-db-data and my login method for react looks … -
data inserted in email filed is not broadcasted properly to backend, request.is_ajax() returns false
I am following a tutorial about an ecommerce app. The app is made with Django 4, and ajax is used in the frontend. I am currently working on a contact page. compiling the form and submiting should trigger a jquery-confirm popup displaying message "thank you a lot!". This is obtained not by simple javascript submit form button , but via a custom ajax logic. The problem is that, when I compile and submit the form, the form is validated, the javascript is loaded, but the email data is not transmitted properly (I get None), and in views.py, request.is_ajax() returns None. This is what happens when I fill up all the form fields and click on submit: backend: contact_form.cleaned_data {'fullname': 'John Doe', 'email': None, 'content': 'uvyibuon'} no ajax in this request: <WSGIRequest: POST '/contact/'> [20/Nov/2023 16:21:15] "POST /contact/ HTTP/1.1" 200 16035 frontend: Navigated to http://127.0.0.1:8000/contact/ contact/:255 readyyyy contact/:261 before submit Here are my files mainapp_ecommerce/urls.py urlpatterns = [ ... path('contact/', contact_page, name="contact"), ] mainapp_ecommerce/views.py from .forms import ContactForm def contact_page(request): contact_form = ContactForm(request.POST or None) context = { "title":"Contact", "content":"Welcome to the contact page!", "form": contact_form, "brand":"new brand name", } if contact_form.is_valid(): print("contact_form.cleaned_data", contact_form.cleaned_data) if request.is_ajax(): # asinchronous javascript and xml … -
Implementing Multi-Tenant Architecture in Django with Shared and Unique Models
I am working on a large, multi-tenant Django project primarily utilizing Django's ORM capabilities. The project involves a PostgreSQL database where each schema represents a different tenant. Django commands are used to insert data into the db, import data from the db and perform some calculation and then send it back to the db, and delete certain data from the database. In each schema, several tables and views are designated for Business Intelligence (BI) tools. Many of my Django models are shared across tenants (in structure, not data), but each tenant should also have unique models, which is where my problem stems from. I want to be able to implement unique models per tenant that can have foreign keys to the common models of that tenant. Implementing these unique tenant models in Django has proven to be difficult and I am aware that this is an unconventional use case for Django. I would like to keep data separate, so using a single schema with a tenant identifier column isn't a preferred option. And as some tables will be exposed I'd prefer to keep power over the table names and not go to general tables and general fields where the data … -
watchlist in Django
This code adds the product to the watchlist before making some changes, and the product could be removed from the list by clicking on the Remove button on the list page. But Product information wasn't displayed on the watchlist page. The link for more information on the watchlist page didn't work and gave an error. After adding the product, the Add to Watchlist button on the product introduction page wasn't changed to Remove. I came across this error while solving these bugs. When you click on add button, it gives this error. Page not found (404) No Watchlist matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/add/1/?productid=1 Raised by: auctions.views.add Using the URLconf defined in commerce.urls, Django tried these URL patterns, in this order: admin/ [name='index'] login [name='login'] logout [name='logout'] register [name='register'] product_detail/<int:product_id>/ [name='product_detail'] watchlist/<str:username>/ [name='watchlist'] add/<int:productid>/ [name='add'] The current path, add/1/, matched the last one. models.py class User(AbstractUser): pass class List(models.Model): choice = ( ('d', 'Dark'), ('s', 'Sweet'), ) user = models.CharField(max_length=64) title = models.CharField(max_length=64) description = models.TextField() category = models.CharField(max_length=64) first_bid = models.IntegerField() image = models.ImageField(upload_to="img/", null=True) image_url = models.CharField(max_length=228, default = None, blank = True, null = True) status = models.CharField(max_length=1, choices= choice) active_bool = models.BooleanField(default … -
I can't install pillow in my venv with pip install Pillow
I can't install pillow in my venv with pip install Pillow. This is the error message that I got. Building wheel for Pillow (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for Pillow (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [199 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.win32-cpython-39 creating build\lib.win32-cpython-39\PIL copying src\PIL\BdfFontFile.py -> build\lib.win32-cpython-39\PIL copying src\PIL\BlpImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\BmpImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\BufrStubImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ContainerIO.py -> build\lib.win32-cpython-39\PIL copying src\PIL\CurImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\DcxImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\DdsImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\EpsImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ExifTags.py -> build\lib.win32-cpython-39\PIL copying src\PIL\features.py -> build\lib.win32-cpython-39\PIL copying src\PIL\FitsImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\FliImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\FontFile.py -> build\lib.win32-cpython-39\PIL copying src\PIL\FpxImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\FtexImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\GbrImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\GdImageFile.py -> build\lib.win32-cpython-39\PIL copying src\PIL\GifImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\GimpGradientFile.py -> build\lib.win32-cpython-39\PIL copying src\PIL\GimpPaletteFile.py -> build\lib.win32-cpython-39\PIL copying src\PIL\GribStubImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\Hdf5StubImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\IcnsImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\IcoImagePlugin.py -> build\lib.win32-cpython-39\PIL copying src\PIL\Image.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageChops.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageCms.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageColor.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageDraw.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageDraw2.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageEnhance.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageFile.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageFilter.py -> build\lib.win32-cpython-39\PIL copying src\PIL\ImageFont.py -> build\lib.win32-cpython-39\PIL copying … -
How do I implement the place bid functionality with django
I have really tried different methods in order to implement a place bid functionality, but it seems not to be working out, pls I need help. Here's my code: views.py def place_bid(request): if request.method == "POST": #create and save the bid value item_id = request.POST("item_id") listing_item_id = get_object_or_404(Listing, pk=item_id) bid_value = request.POST("bid_value") Bids.objects.create(bidder=request.user, bid_price=bid_value, listing_id=listing_item_id) listing_item_id.initial_price = bid_value listing_item_id.save() return render(request, "auctions/listing_view.html", { "price": listing_item_id, "message": "Your bid has been placed successfully" }) models.py class Listing(models.Model): product_name = models.CharField(max_length=64, verbose_name="product_name") product_description = models.TextField(max_length=200, verbose_name="product description") product_image = models.ImageField(upload_to="images/", verbose_name="image", blank=True) is_active = models.BooleanField(blank=False, default=True) initial_price = models.DecimalField(decimal_places=2, max_digits=6, null=True, blank=True) owner = models.ForeignKey(User, related_name="auction_owner", on_delete=models.CASCADE, default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category") def __str__(self): return self.product_name class Bids(models.Model): bidder = models.ForeignKey(User, null=True, on_delete=models.CASCADE) bid_price = models.DecimalField(decimal_places=2, max_digits=6, null=True, blank=True) listing_id = models.ForeignKey(Listing, null=True, on_delete=models.CASCADE) def __str__(self): return self.bid_price templates <div class="right"> <h3>{{ listing.product_name }}</h3> <h4>${{ price.initial_price }}</h4> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> <div class="btn-groups"> {% if listing in watchlist_items %} <a href="{% url 'remove_from_watchlist' item_id=listing.id %}" class="fas fa-shopping-cart"><button type … -
Is there a common way to deploy a Django application with Windows Server ISS?
I deployed a Django application on a Windows Server 2016 of a customer, but he wants it deployed through ISS, which as a Linux person i had no idea what it was. So I searched for it, and how to deploy a Django application using ISS. The best content I could find about this was on Matt Woodward post from years ago. Still it didn't work as expected, and I can't find where the problem is. specs: django 4.2 wfastcgi 3.0 python 3.11 windows server 2016 folder structure: Steps This was my steps trying to get it working. Setting up dependencies 1 - Installed Python and ISS on the OS; 2 - Created virtual environment and installed project requirements + wfastcgi; 3 - Tested Django application - working fine with runserver; Configure FastCGI 1 - As Full path value: C:\Users\one\Documents\app\myApplication\virtualenv\Scripts\python.exe 2 - As arguments value: C:\Users\one\Documents\app\myApplication\virtualenv\Lib\site-packages\wfastcgi.py 3 - For environment variables: DJANGO_SETTINGS_MODULE: core.settings PYTHONPATH: C:\Users\one\Documents\app\myApplication\core WSGI_HANDLER: django.core.wsgi.get_wsgi_application() Configure IIS Site 1 - As Content Directory/Physical path: C:\Users\one\Documents\app\myApplication\core 2 - For Handler Mappings: Request path: * Module: FastCgiModule Executable: C:\Users\one\Documents\app\myApplication\virtualenv\Scripts\python.exe|C:\Users\one\Documents\app\myApplication\virtualenv\Lib\site-packages\wfastcgi.py Now when I go to http://localhost:81 I receive this page Now I don't know if there's some problem with configs or … -
How to Convert and Save Uploaded Video File to M3U8 Format Using Django?
I'm working on a Django project where users can upload video files, and I need to convert these uploaded videos into the M3U8 format for streaming purposes. Could anyone provide guidance or a code example on how to achieve this conversion and save the resulting M3U8 file using Django? I'm open to using any libraries or tools that could simplify this process. Thanks in advance for any help or suggestions! # models.py class Video(AdvertisementModelMixin): text = models.CharField(max_length=255) description = models.TextField() image = WEBPField( verbose_name='Image', upload_to=video_folder, ) video = models.FileField( upload_to='video/', validators=[FileExtensionValidator( allowed_extensions=[ 'MOV', 'avi', 'mp4', 'webm', 'mkv', 'm' ]) ] ) skip_duration = models.PositiveSmallIntegerField( null=True, blank=True, validators=[ MinValueValidator(3), MaxValueValidator(20) ] ) def __str__(self): return f"{self.id}. {self.text}" class Meta: verbose_name = "video" # views.py class VideoViewSet(ModelViewSet): queryset = (Video.objects.all() .prefetch_related("devices") .prefetch_related("provinces")) serializer_class = VideoSerializer pagination_class = AdsPagination ads_type = "video" -
Websocket not receiving messages from Django Channels
I'm currently working on a project using Django Channels for WebSocket communication. However, I'm facing an issue where the WebSocket connection is established successfully, but messages are not being received on the client side. WebSocket connection is established without errors. I've verified that the Django Channels server is sending messages. However, the client-side WebSocket does not seem to receive any messages my asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator import transposys_main.routing import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'transposys_main.settings') django.setup() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( URLRouter( transposys_main.routing.websocket_urlpatterns ) ), }) consumer.py import json from channels.generic.websocket import AsyncWebsocketConsumer import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) class DepartmentCreatedConsumer(AsyncWebsocketConsumer): async def connect(self): logger.info(f"WebSocket connected: {self.channel_name}") await self.accept() async def disconnect(self, close_code): logger.info(f"WebSocket disconnected: {self.channel_name}") async def receive(self, text_data): logger.info(f"WebSocket message received: {text_data}") try: text_data_json = json.loads(text_data) message_type = text_data_json.get('type') message = text_data_json.get('message') if message_type == 'department.created': logger.info(f"New Department: {message}") except json.JSONDecodeError as e: logger.error(f"Error decoding JSON: {e}") async def department_created(self, event): try: logger.info(f"Department created event received: {event['message']}") await self.send(text_data=json.dumps({ 'type': 'department.created', 'message': event['message'], })) except Exception as e: logger.error(f"Error sending WebSocket message: {e}") routing.py: from django.urls import re_path from .consumers import DepartmentCreatedConsumer websocket_urlpatterns … -
Django Admin Recent Actions in a react Js website
I want to know if I can use the logs that are displayed on Django Admin in a custom React Js Admin Panel. I have a requirement which is to show all recent changes done by any user. Django admin already has that Recent Actions widget. How can I use that data and serialize it in some API/View I tried using django-simple-history but it shows specific history for a specific object. I want a complete generic log list -
Django: Implementing fund reversal in post_save signal
I'm using django post_save signal to update the status of a transaction based on whether funds are received. The problem is that funds_received is not working as expected. The issue is in using .exists(), because, it checks if there is any account with the exact balance equal to the transaction amount. If anyone has suggestions or knows of a better way for checking if funds are received, I would greatly appreciate the guidance. from django.db.models.signals import post_save from django.dispatch import receiver from .models import Transaction, Account @receiver(post_save, sender=Transaction) def transaction_status(sender, instance, created, **kwargs): if created: amount = instance.amount sender_account = instance.sender.account receiver_account_number = instance.account_number receiver_account = account.objects.get(account_number=receiver_account_number) check_if_funds_received = Account.objects.filter(account_balance=amount).exists() funds_received = check_if_funds_received if funds_received: instance.status = 'Reversed' instance.save() else: instance.status = 'Reversed' instance.save() # return funds to sender sender_account.account_balance += amount sender_account.save() My Models: class Account(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) account_number = models.BigIntegerField(unique=True) account_balance = models.DecimalField(max_digits=12, decimal_places=6) account_id = models.CharField(max_length=15, unique=True) user_qrcode = models.ImageField() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) account_status = models.CharField(max_length=50, choices=ACCOUNT_STATUS) pin = models.CharField(max_length=4) def __str__(self): return str(self.user.first_name) class Transaction(models.Model): STATUS = ( ('Success', 'Success'), ('Reversed', 'Reversed') ) sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='receiver') amount = models.DecimalField(max_digits=12, decimal_places=6) account_number = models.BigIntegerField() first_name … -
stocks quantity only decreasing not increasing
after updating the data, the stocks. Quantity is only decreasing does not matter if we only increase the quantity or decrease the quantity. I want when we update the data the stocks quantity will also be updated for ex-, we increase 2 points then only 2 quantities will be decreased. suppose we have 5 unit of shoes in cart and stocks have 10 quantities left so if we increase 2 so the total quantity will in cart 7 and left quantity in stocks will be 8 quantity shoes and if we decrease 3 quantities so the total quantity in cart will be 4 and total quantity in stocks are 11. for ex-, we increase 2 points then only 2 quantities will be decreased. suppose we have 5 unit of shoes in cart and stocks have 10 quantities left so if we increase 2 so the total quantity will in cart 7 and left quantity in stocks will be 8 quantity shoes and if we decrease 3 quantities so the total quantity in cart will be 4 and total quantity in stocks are 11. I just need the logic. hope you guys get that! ================================================================================== views.py > def supplier_edit(request, id): try: … -
problem loading static files with django nginx gunicorn on AWS lightsail
I installed my django app on lightsail, on a ubuntu server from scratch. The webpage is working ok but the static files are not loading. I read about adding some info on the web_app.conf (cht_web.conf) and it looks like this: `server { listen 80; server_name xxx.xxx.xxx.xxx; location / { include proxy_params; ` proxy_pass http://localhost:8000/; } location /static/ { autoindex on; root /home/ubuntu/cht_web/cht_web/static/; } I´m not sure if i have to install Supervisor, so I´ve not installed it yet, im running gunicorn with: gunicorn cht_web.wsgi --bind 0.0.0.0:8000 --workers 4 and the log is: \[2023-11-20 12:47:13 +0000\] \[38774\] \[INFO\] Starting gunicorn 21.2.0 \[2023-11-20 12:47:13 +0000\] \[38774\] \[INFO\] Listening at: http://0.0.0.0:8000 (38774) \[2023-11-20 12:47:13 +0000\] \[38774\] \[INFO\] Using worker: sync \[2023-11-20 12:47:13 +0000\] \[38775\] \[INFO\] Booting worker with pid: 38775 \[2023-11-20 12:47:13 +0000\] \[38776\] \[INFO\] Booting worker with pid: 38776 \[2023-11-20 12:47:13 +0000\] \[38777\] \[INFO\] Booting worker with pid: 38777 \[2023-11-20 12:47:13 +0000\] \[38778\] \[INFO\] Booting worker with pid: 38778 my settings.py static config is: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' #representa la raiz del directorio STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), my base dir is: BASE_DIR = Path(__file__).resolve().parent.parent (maybe the extra.parent is an issue, but it loads media!) Its in debug … -
Django app, how to download all files asociated a project?
I'm trying to create a definition in my view.py file to download all files associated with a project. This time I'm using the python ZipFile package to zip all the files, but I'm having a lot of trouble finding the right code My Models class File(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) project_slug = AutoSlugField(populate_from='project', always_update=True) pub_date = models.DateTimeField(auto_now_add=True) def directory_path(instance, filename): return 'files_project/project_{0}/{1}'.format(instance.project_slug, filename) upload = models.FileField(upload_to=directory_path) My view def DownloadAllFilebyProject(request, id): project = Project.objects.get(id=id) files = project.file_set.all() zf = zipfile.ZipFile(os.path.join(settings.MEDIA_ROOT, 'files_project/project_{0}/'.format(project.slug), 'allfile.zip'), 'w') for file in files: zf.writestr(os.path.join(settings.MEDIA_ROOT, 'files_project/project_{0}/'.format(project.slug)), file) zf.close() return HttpResponse(print(zf)) My Template <a href="{% url 'apppro:DownloadAllFilebyProject' project.id %}" class="btn btn-warning float-right" method="get"> descargar todos los archivos</a> The error TypeError at /downloadallzipfiles/13 object of type 'File' has no len( -
POST data not registering in Django custom admin action with intermediate form
I am trying to add a custom admin action do my Django model. The goal is to show a form to the user where they can select a group which will get linked to all my selected candidates. My issue is that the code works in the render part, and the form is shown. However when I click apply my code never enters the if 'apply' in request.POST condition. It also seems the code is never called a second time. Here are the relevant parts of my code: CandidateAdmin.py from django.contrib import admin from django.utils.safestring import mark_safe from exem_poi.models import Candidate from django.urls import reverse from django.utils.html import format_html from django.http import HttpResponseRedirect from django.shortcuts import render from exem_poi.views.utils import convert_to_wgs84 from exem_poi.models.Candidate import Group @admin.register(Candidate) class CandidateAdmin(admin.ModelAdmin): list_display = ('batiment_construction_id', 'emitters_100m', 'height', 'display_owners', 'is_public') list_filter = ('emitters_100m', 'height', 'is_public') search_fields = ('batiment_construction_id', 'emitters_100m', 'height', 'is_public') readonly_fields = ('centroid',) actions = ['assign_to_group'] def assign_to_group(self, request, queryset): # Handle the form submission for assigning candidates to a group print(request.POST) if 'apply' in request.POST: group_id = request.POST.get('group_id') group = Group.objects.get(id=group_id) for candidate in queryset: group.candidates.add(candidate) self.message_user(request, f'Successfully assigned candidates to group {group.name}') return HttpResponseRedirect(request.path) groups = Group.objects.all() context = {'groups': groups, 'candidates': … -
How to join multiple models with OnetOne relationship in Django?
I have a main model with several fields and a few other models that serve as extra information which varies depending on user input. The main model will always be related to one of these. I want to retrieve all the information between the main models and the models with extra information. Here's an example of the relationship: class MainModel(models.Model): MAIN_MODEL_CHOICES = [(1, "Extra info 1"), (2, "Extra info 2"), (3, "Extra info 3")] name = models.CharField(max_length=100) description = models.CharField(max_length=100) choice = models.IntegerField(choices=MAIN_MODEL_CHOICES) class ExtraModel1(models.Model): main_model = models.OneToOneField(MainModel, on_delete=models.CASCADE) extra_text_info = models.TextField() class ExtraModel2(models.Model): main_model = models.OneToOneField(MainModel, on_delete=models.CASCADE) important_number = models.IntegerField() class ExtraModel3(models.Model): main_model = models.OneToOneField(MainModel, on_delete=models.CASCADE) important_bool = models.BooleanField(default=False) I have tried MainModel.objects.prefetch_related("extramodel1", "extramodel2", "extramodel3") and MainModel.objects.select_related("extramodel1__main_model", "extramodel2__main_model", "extramodel__main_model") but the retrieved queryset doesn't include the extra models, only the main one. -
Celery Tasks not Running on Mac M2 (Process 'ForkPoolWorker' exited with 'signal 11 (SIGSEGV)')
I am encountering an issue while trying to run Celery tasks on my Mac M1 machine. The error message I'm getting is as follows: The process has forked and you cannot use this CoreFoundation functionality safely. You MUST exec(). Break on __THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC__() to debug. [2023-11-20 15:51:19,174: ERROR/MainProcess] Process 'ForkPoolWorker-8' pid:5547 exited with 'signal 11 (SIGSEGV)' I am using Celery for my Django app task processing, and this issue seems to be related to forking on the M2 architecture. I initially attempted to resolve the issue by exporting OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES, which seemed to work for a brief period. However, the problem has resurfaced, and this solution no longer has any effect. It's worth noting that I am currently running MacOS Sonama 14.2 Beta on my machine. Interestingly, I encountered and successfully resolved this problem once before while on the same beta program. Any insights or suggestions on how to resolve this issue would be greatly appreciated. -
How to connect react native with android studio with django docker container?
I have a react native app for web configured. And I have a django app for the backend. I can connect this two apps with each other. But now I have dockerized the django app. But not the react app. And now the react app cannot any more communicate with the django docker app. So this is my docker compose.yml file: version: "3.9" name: dwl_backend services: app: image: crdierenwelzijn2.azurecr.io/web1 build: context: C:\repos\dierenwelzijn\dwl_backend dockerfile: Dockerfile args: DEV: "true" command: - sh - -c - "python manage.py wait_for_db && python ./manage.py migrate && python ./manage.py runserver 0:8000" depends_on: db: condition: service_started required: true environment: DB-PORT: "5432" DB_HOST: db DB_NAME: name DB_PASS: pass DB_USER: user DEBUG: "1" DJANGO_ALLOWED_HOSTS: localhost 127.0.0.1 [::1] SECRET_KEY: django-insecure-kwuz7%@967xvpdnf7go%r#d%lgl^c9ah%!_08l@%x=s4e4&+(u networks: default: null ports: - mode: ingress target: 8000 published: "8000" protocol: tcp volumes: - type: bind source: C:\repos\dierenwelzijn\dwl_backend\DierenWelzijn target: /app bind: create_host_path: true db: environment: POSTGRES_DB: db POSTGRES_PASSWORD: password POSTGRES_USER: user image: postgres:13-alpine networks: default: null volumes: - type: volume source: dev-db-data target: /var/lib/postgresql/data volume: {} networks: default: name: dwl_backend_default volumes: dev-db-data: name: dwl_backend_dev-db-data and my login method for react looks like: export const loginRequest = async (email, password) => { try { const response = await fetch("http://192.168.1.135:8000/api/user/token/", { … -
Notifications not showing on list
I have a django app with django-notifications-hq installed. The notifications are working pretty well except for the list of notifications aren't showing on the field. The notifications count is showing in the navbar. Here's my code : <div class="dropdown"> <button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false"> <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-bell" viewBox="0 0 16 16"> <path d="M8 16a2 2 0 0 0 2-2H6a2 2 0 0 0 2 2zM8 1.918l-.797.161A4.002 4.002 0 0 0 4 6c0 .628-.134 2.197-.459 3.742-.16.767-.376 1.566-.663 2.258h10.244c-.287-.692-.502-1.49-.663-2.258C12.134 8.197 12 6.628 12 6a4.002 4.002 0 0 0-3.203-3.92L8 1.917zM14.22 12c.223.447.481.801.78 1H1c.299-.199.557-.553.78-1C2.68 10.2 3 6.88 3 6c0-2.42 1.72-4.44 4.005-4.901a1 1 0 1 1 1.99 0A5.002 5.002 0 0 1 13 6c0 .88.32 4.2 1.22 6z"/> </svg> {{ request.user.notifications.unread.count }} </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton1"> {% for notification in notifications %} <a class="dropdown-item" href="{{ notification.data.action_object.get_absolute_url }}"> Notification: {{ notification.actor }} {{ notification.verb }} </a> {% empty %} <span class="dropdown-item">No notifications</span> {% endfor %} </div> </div> I've tried to consult ChatGPT but don't get any answers. So any help from this community would be a great one. Also, if you need me to post anything else, I would definitely post it here. -
Django does not load the maps in the admin panel
I need to upgrade the Django version of a project that uses GeoModelAdmin for displaying maps in the admin panel. The recommended class to be used is ModelAdmin as stated in the documentation: Deprecated since version 4.0: This class is deprecated. Use ModelAdmin instead. However, when I use ModelAdmin the maps do not load at all. And I get this error in the console: GET https://gitc.earthdata.nasa.gov/wmts/epsg3857/best/BlueMarble_ShadedRelief_Bathymetry/default/%7BTime%7D/GoogleMapsCompatible_Level8/8/92/146.jpg 500 (Internal Server Error) Is there a configuration that I missed or there are problems with the server? In the past I used OSMGeoAdmin which was exactly what I needed, but got it deprecated in Django 4.0. Now is suggested to use GISModelAdmin instead. When I use GISModelAdmin the maps are loaded, but I want to configure the zoom level and if I set the gis_widget_kwargs according to the documentation, nothing changes. gis_widget_kwargs = { "attrs": { "default_lon": 5, "default_lat": 47, "default_zoom": 3, } } -
Django .initial attribute in the form seems doesn't work
I have a problem with my Django project. I have a Model "Fattura" and a Form "EntrataForm", here is the code of the model: class Fattura(models.Model): TIPO_CHOICES = [ ('T', 'Tasse'), ('B', 'Burocrazia'), ('C', 'Clienti'), ('S', 'Spese'), ] numero = models.CharField(max_length=20) data = models.DateField(default=django.utils.timezone.now) tipo = models.CharField(max_length=1, choices=TIPO_CHOICES) importo = models.DecimalField(max_digits=10, decimal_places=2) cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE, null=True, blank=True) viaggi = models.ManyToManyField(Viaggio) def clean(self): if self.importo is None: raise ValidationError('L\'importo non può essere None.') def __str__(self): return f"{self.numero} - {self.data} - {self.importo} - {self.tipo}" and the form: class EntrataForm(forms.ModelForm): class Meta: model = Fattura fields = ['numero', 'data', 'cliente','viaggi','importo','tipo'] def __init__(self, *args, **kwargs): id = kwargs.pop('id',None) super(EntrataForm, self).__init__(*args, **kwargs) importo_finale = 0 viaggi = Viaggio.objects.filter(cliente_id=id) for viaggio in viaggi: importo_finale += viaggio.prezzo_viaggio print(id) self.fields['tipo'].widget.attrs['readonly'] = True self.fields['tipo'].required = False self.fields['tipo'].widget = forms.HiddenInput() self.fields['tipo'].initial = 'C' self.fields['viaggi'].widget.attrs['readonly'] = True self.fields['viaggi'].required = False self.fields['viaggi'].widget = forms.HiddenInput() self.fields['viaggi'].initial = viaggi self.fields['cliente'].widget.attrs['readonly'] = True self.fields['cliente'].required = False self.fields['cliente'].widget = forms.HiddenInput() self.fields['cliente'].initial = Cliente.objects.get(id=id) self.fields['importo'].widget.attrs['readonly'] = True self.fields['importo'].required = False self.fields['importo'].widget = forms.HiddenInput() self.fields['importo'].initial = importo_finale print(self.fields['importo'].initial) As you can see i use the ".initial" attribute for 4 fields, but only "importo" doesn't initialize correctly. In init the final value is correct and the last line … -
Allow Admin user to see only the user the admin creates in Django
I am trying to create a school management system, where by a school can register and becomes an admin, the school which is an admin, can create their staffs and students. The staff and students should be able to login to their accounts. The key thing here is that, there will be more than one school registered, thus each school should only see their own staffs and students. How can i ensure that the admin only sees the students and staff account created by that admin alone? Functionality so far I have created different user type accounts, admin(school) can login and create a student and staff accounts, students and staffs account created by admin which is the school can also login. The thing here is that, all admin can see all staffs, i don't want this to happen, i want admin to only see the student and staffs created by that admin alone. Below is my code for review accounts/models.py my custom user model class CustomUser(AbstractUser): USER_TYPE = ((1, "school"), (2, "Staff"), (3, "Student")) GENDER = [("M", "Male"), ("F", "Female")] username = None # Removed username, using email instead email = models.EmailField(unique=True) user_type = models.CharField(default=1, choices=USER_TYPE, max_length=1) gender = models.CharField(max_length=1, … -
DJango and Docker: db shutting down and web service not accepting connections
I have a problem with Docker. I am trying to build a docker postgres DB and web service for a DJango app. Here is my config: Dockerfile: # syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ docker-compose.yml: services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=whatsarounddb - POSTGRES_USER=dbadmin - POSTGRES_PASSWORD=dbadmin123 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=whatsarounddb - POSTGRES_USER=dbadmin - POSTGRES_PASSWORD=dbadmin123 depends_on: - db settings.py from Django: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] **code** # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'whatsarounddb', 'USER': 'dbadmin', 'PASSWORD': 'dbadmin321', 'HOST': 'localhost', 'PORT': 5432, } } When I use docker-compose up --build I get the following output: [+] Running 14/1 ✔ db 13 layers [⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿] 0B/0B Pulled 9.6s [+] Building 7.0s (14/14) FINISHED docker:default => [web internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => [web internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 234B 0.0s => [web] resolve image config for docker.io/docker/dockerfile:1 1.5s => [web auth] docker/dockerfile:pull token for … -
Django Add Multiple Files To Single Instance
enter image description here MY Problem is when i click on extension ID it should display all the audio files relegated to that ID is there any way to upload multiples files Audio Files For Single Instance enter image description here Here Is The Second Image It Showing Only One Audio File But I want to upload multiple audio files trying to create different form applying different method in model