Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
que aplicaciones desplegar en heroku
el problema es que tengo una aplicacion en python y django que usa conexiones web socket con cnannels y daphne, el asunto es si heroku permite el uso de estas conexiones ya adquiri una suscripcion en pythonAnywhere y me toca cancelarla porque no admiten estas conexiones y me vine a dar cuenta ya con los errores que arrojaba despues de estar en el servidor. si, si se permite este tipo d conexion en heroku quiciera que me dieran un enlace donde expliquen bien como se configuran en esete servidor heroku y si no entoces que proveedor de servicios puedo contratar para el uso de esta aplicacion, recuerden aplicacion desarrollada en django y python con conexiones websocket usando chanels y daphne con BD mysql probe en pyrhonAnywhere y quede viendo un chispero -
Automate e2e test with selenium of Django app in gitlab cicd -Error: selenium.common.exceptions.WebDriverException: neterror?e=dnsNotFound
This is the output of my cicd pipline which is failing base/tests/e2e_tests/test_register.py F [100%] =================================== FAILURES =================================== _____________ TestRegistrationPage.test_register_valid_credentials _____________ self = <test_register.TestRegistrationPage testMethod=test_register_valid_credentials> def test_register_valid_credentials(self): """ Test whether the registration process works flawlessly. This method asserts that after sucessful redirect url equals home. """ > self.driver.get("http://secprog:8080/") FAILED base/tests/e2e_tests/test_register.py::TestRegistrationPage::test_register_valid_credentials - selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=dnsNotFound&u=http%3A//secprog%3A8080/&c=UTF-8&d=We%20can%E2%80%99t%20connect%20to%20the%20server%20at%20secprog. Stacktrace: RemoteError@chrome://remote/content/shared/RemoteError.sys.mjs:8:8 WebDriverError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:193:5 UnknownError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:832:5 checkReadyState@chrome://remote/content/marionette/navigate.sys.mjs:58:24 onNavigation@chrome://remote/content/marionette/navigate.sys.mjs:330:39 emit@resource://gre/modules/EventEmitter.sys.mjs:148:20 receiveMessage@chrome://remote/content/marionette/actors/MarionetteEventsParent.sys.mjs:33:25 This is my Dockerfile: # Stage 1: Build stage FROM python:3.12.0b2-alpine3.17 RUN apk update WORKDIR /app COPY . . EXPOSE 8080 CMD ["python", "manage.py", "runserver", "0.0.0:8080"] This is my .gitlab-ci.yml. in my build stage everything works fine and it gets passed. The problem is in my run_e2e_test. I don't know where my error is. I assume that there is a problem with how i define the alias for the services, but i don't know how the to services can communicate with each other: stages: - unit_tests - build - integration_tests - static_code_analysis - start_server - sec_vuln_assessment - e2e_tests run_build: stage: build image: docker:20.10.16 services: - docker:20.10.16-dind variables: DOCKER_TLS_CERTDIR: "/certs" before_script: # login working, but -p is unsecure. try --password-stdin - docker login registry.mygit.th-deg.de -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD script: - docker build -t registry.mygit.th-deg.de/pk27532/secprog . - docker … -
user.username shows incorrect information about the logged in user name
views.py def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Account has been updated') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) users/profile.html <h1>{{ user.username }}</h1> <h2>{{ user.email }}</h2> <img src="{{ user.profile.image.url }}" width="200" style="border: 3px solid black;"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ u_form }} {{ p_form }} <button type="submit">Update profile</button> </form> When I submit form with username that already exists, it shows error "A user with that username already exists", but user.username field is equal to that invalid existing username, but in database nothing changes. Also if this field doesn't pass any validators then it also shows this invalid data. I expected {{user.username }} to remain the same as in the database and as the logged in user's data -
How to import and use Django models inside new process outside views.py
I have some models inside 'models.py' inside 'app1' : ... class ChitaMoney(models.Model): chita_market = models.CharField( verbose_name=_('chita market name'), max_length=20 ) ... my 'views.py' calls a function from 'multy.py' from 'core' directory inside 'app1' 'multy.py' startes a new infinite process . when the process whants to import the models: from ..models import ChitaMoney this happens: Process chita_main: Traceback (most recent call last): File "C:\Users\David\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\process.py", line 314, in _bootstrap self.run() File "C:\Users\David\AppData\Local\Programs\Python\Python312\Lib\multiprocessing\process.py", line 108, in run self._target(*self._args, **self._kwargs) File "D:\Django\JaNext_Boos_1\app1\core\multy.py", line 160, in chita_main_thread ins_l_t, ins_l_a = chita_init(chita_dtt) ^^^^^^^^^^^^^^^^^^^^^ File "D:\Django\JaNext_Boos_1\app1\core\multy.py", line 112, in chita_init from ..models import ChitaMoney File "D:\Django\JaNext_Boos_1\app1\models.py", line 5, in class ChitaStock(models.Model): File "d:\Django\JaNext_Boos_1.venv\Lib\site-packages\django\db\models\base.py", line 129, in new app_config = apps.get_containing_app_config(module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "d:\Django\JaNext_Boos_1.venv\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "d:\Django\JaNext_Boos_1.venv\Lib\site-packages\django\apps\registry.py", line 138, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Django==5.0.4 any help would be appreciated I had same problem without process importing models in top of .py files and after I import the models inside functions, I could use the models. But inside new process ... -
I'm getting a 503 error when I upload an image to a pre-trained model and try to get output using python + Django on a shared web host
Background: *Beginner here. * I made a simple app with some basic models and trained it to distinguish happy and sad faces. I made this and ran it in a local development server with Django which worked perfectly and I was even able to display the image after getting a non-logged-in user to upload. Then, I tried uploading the app to a non-local server. This server is part of a shared web hosting package and has cPanel. The app works fine till I upload the image and then it shows a 503 error. The server resource logs show that usage spikes when I upload the image and it is fed into the pre-trained neural network but nothing that would overpower the limits, only 75% of server physical memory being used. Server Specs: Server Specs TLDR: Uploaded a Django app with an Image Classification model which shows a 503 error after uploading the image from the front-end. Error Logs: 2024-05-05 16:03:28.355186: I external/local_tsl/tsl/cuda/cudart_stub.cc:32] Could not find cuda drivers on your machine, GPU will not be used. 2024-05-05 16:03:28.359620: I external/local_tsl/tsl/cuda/cudart_stub.cc:32] Could not find cuda drivers on your machine, GPU will not be used. 2024-05-05 16:03:28.396387: I tensorflow/core/platform/cpu_feature_guard.cc:210] This TensorFlow binary is … -
django uploaded images from admin panel not displayed in the homepage
i created a django project to upload images both from the user interface and from the admin panel. but when uploading images from user interface, the images are not uploaded to the media folder.and also not shown in the homepage. but when uploading from the admin panel, the images are uploaded to the media folder correctly but in the home page the images are not shown. this problem is with the images only. other fields are correctly displayed like the title, price aand so on. tell me how to fix my issue. these are my code snippets. user interface uploading code <div class="layout__body"> <form class="form" action="" method="POST" enctype="multipart/form-data" > {% csrf_token %} <div class="form__group"> <label for="post_category">Enter a Category</label> <input required type="text" value="{{post.category.name}}" name="category" list="category-list" /> <datalist id="category-list"> <select id="post_category"> {% for category in categories %} <option value="{{category.name}}">{{category.name}}</option> {% endfor %} </select> </datalist> </div> <div class="form__group"> <label for="post_name">Post Title</label> {{form.title}} </div> <div class="form__group"> <label for="post_image">Post Image</label> {{form.image}} </div> <div class="form__group"> <label for="post_price">Post Price</label> {{form.price}} </div> <div class="form__action"> <a class="btn btn--dark" href="{{request.META.HTTP_REFERER}}" >Cancel</a > <button class="btn btn--main" type="submit">Submit</button> </div> </form> views.py for post creation @staff_member_required @login_required(login_url='login') def create_post(request): form = PostForm(request.POST,request.FILES) categories = Category.objects.all() if request.method == 'POST': category_name = request.POST.get('category') category,created_at … -
How to read file from DigitalOcean Spaces using Django?
I have a Django app that uses DigitalOcean Spaces to store user-uploaded files. The app then transcribes those files and returns the text. However when I try to read the file using the url to the stored file it fails. Here is my views.py: This code saves the file to Spaces if form.is_valid(): uploaded_file = request.FILES['file'] request.session['uploaded_file_name'] = uploaded_file.name request.session['uploaded_file_size'] = uploaded_file.size#add to models session_id = str(uuid.uuid4()) request.session['session_id'] = session_id transcribed_doc, created = TranscribedDocument.objects.get_or_create(id=session_id) transcribed_doc.audio_file = uploaded_file transcribed_doc.save() request.session['uploaded_file_path'] = transcribed_doc.audio_file.url#store url to file #rest of code This code reads the file: file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path')#store url in 'file_path' variable if request.method == 'POST': try: if not file_name or not file_path: return redirect (reverse('transcribeSubmit')) audio_language = request.POST.get('audio_language') output_file_type = request.POST.get('output_file_type') if file_name and file_path: file_extension = ('.' + (str(file_name).split('.')[-1])) #open file located at DO Spaces and initiate transcription with open(file_path, 'rb') as f: path_string = f.name destination_dir = 'ai_transcribe_output' transcript = transcribe_file(path_string, audio_language, output_file_type, destination_dir) My intention is to transcribe the file directly from the url at DO Spaces or if that is not feasible then instead to temporarily store a copy of the file locally so that it can be transcribed then deleted. I'm using django-storages[s3] to … -
django deploywment with daphne
I want to up my django server with run this command for in daphne: daphne -b 0.0.0.0 -p 9001 core.asgi:application And this error occurred: Traceback (most recent call last): File "/usr/local/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) File "/usr/local/lib/python3.8/site-packages/daphne/cli.py", line 171, in entrypoint cls().run(sys.argv[1:]) File "/usr/local/lib/python3.8/site-packages/daphne/cli.py", line 233, in run application = import_by_path(args.application) File "/usr/local/lib/python3.8/site-packages/daphne/utils.py", line 17, in import_by_path target = importlib.import_module(module_path) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 843, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/app/./core/asgi.py", line 4, in <module> from stream.routing import ws_urlpatterns File "/app/./stream/routing.py", line 2, in <module> from .consumers import OccurrenceConsumer File "/app/./stream/consumers.py", line 5, in <module> from .models import Occurrence File "/app/./stream/models.py", line 5, in <module> class Asset(models.Model): File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 129, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/usr/local/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must … -
Django ordering with many to many relationship in model
I am using Django-rest-framework modelviewset, I have a many-to-many relationship with my models below: class Data(TimestampMixin): user = models.ForeignKey( "User", null=True, blank=True, on_delete=models.SET_NULL, related_name="files", ) file = models.FileField(upload_to=user_directory_path, null=True, blank=True) doc_id = models.TextField(null=True, blank=True) url = models.CharField(max_length=255, null=True, blank=True) deleted = models.BooleanField(default=False) tags = models.ManyToManyField("Tag", blank=True, null=True) class Tag(models.Model): team = models.ForeignKey("Team", on_delete=models.CASCADE, blank=True, null=True) name = models.TextField(max_length=255) now here is my problem, I want to create a sorting for tag name, and here is what i've got in my Model-view-set: class UserDataViewSet(ModelViewSet): queryset = Data.objects.all() serializer_class = UserDataSerializer ordering_fields = ["file"] def get_queryset(self): user = self.request.user queryset = super().get_queryset() owner_id = getattr(self.request.user.team, "owner_id", None) if user is not None: if owner_id is not None: queryset = queryset.filter(user=owner_id, deleted=False) else: queryset = queryset.filter(user=user, deleted=False) ordering = self.request.query_params.get("ordering", "") if ordering == "tags": pass return queryset as you can see i have a condition regarding ordering == tags , I want to perform the sorting inside the condition. Now i created also a raw query that will suite my needs but i don't know how to execute it on drf side: select * from users_data ud left join users_data_tags udt on ud.id = udt.data_id left join users_tag ut on udt.tag_id = … -
How do I display an image slideshow using Bootstrap Carousel in Django?
I am trying to display a slideshow using Bootstrap Carousel in Django. The idea is to show multiple images in the slideshow for each event detail (attached with a foreign key). I believe it might have something to do with image handling in the settings.py file. What code should I add for this to work? This is an image of where I would like the slideshow to show, but it is not working. admin.py from django.contrib import admin from .models import Person, PersonDetail, Event, EventDetail, EventImage admin.site.register(Person) admin.site.register(PersonDetail) admin.site.register(Event) admin.site.register(EventDetail) admin.site.register(EventImage) models.py from django.db import models class Person(models.Model): person_text = models.CharField(max_length=200) def __str__(self): return self.person_text class PersonDetail(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) person_subtext = models.TextField() def __str__(self): return f"{self.person_subtext[:50]}..." class Event(models.Model): event_text = models.CharField(max_length=200) def __str__(self): return self.event_text class EventDetail(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) event_subtext = models.TextField() def __str__(self): return self.event_subtext class EventImage(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) image = models.ImageField(upload_to='pics/%y/%m/%d/') title = models.CharField(max_length=150) sub_title = models.CharField(max_length=100) def __str__(self): return self.title views.py from django.shortcuts import render from .models import Person, Event, EventImage def index(request): """The home page for History Gallery.""" return render(request, 'galleries/index.html') def persons(request): """Show all persons.""" persons = Person.objects.all() context = {'persons': persons} return render(request, 'galleries/persons.html', context) def person_detail(request, person_id): … -
How can I run tasks in background of djagno project? [duplicate]
I need to run a few tasks in background of my Django project and also I didn't know what is __init__.py file in the Main and App directory in my Django project. I thought myself this file could help me to run my tasks when I run the server with runserver command, But when I'm trying to put some simple codes in this file, I'm facing with this error django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.. My idea is to change my Django database in a scheduled way in background with async functions in django event loop. How can I do that? -
I use decompyle3 or uncompyle6 It decompiles my functions that do not start with "get" but if my function starts with "get" it generates an error?
I use decompyle3 or uncompyle6 It decompiles my functions that do not start with "get" but if my function or method starts with "get" it generates an error: def get_list_patientParse error at or near `POP_BLOCK' instruction at offset 120 so my function is get_list_patient(request): since it starts with "get" it gives this error. def get_list_patientParse error at or near `POP_BLOCK' instruction at offset 120 -
Why uwsgi doesn't disable threads inside django application
Uwsgi docs says, that threads inside an application are turned off until you haven't explicitly turned them on. For me, it works not like that. I have checked it through a simple view in django. uwsgi run params: - uwsgi - --socket=0.0.0.0:8081 - --module=conf.shop.wsgi - --buffer-size=65535 - --py-autoreload=1 - --lazy - --lazy-apps - --vacuum When uwsgi starts, it writes: *** Python threads support is disabled. You can enable it with --enable-threads *** View code: from threading import Thread def view(): def foo(time_sleep, number: int): time.sleep(time_sleep) return number results = {} threads = [] for i in range(8): thread = Thread( target=foo, kwargs={'time_sleep': 1, 'number': i}, name=f'task {i}', ) threads.append(thread) [thread.start() for thread in threads] [thread.join() for thread in threads] performed_threads = [thread for thread in threads if thread.result is not None] for thread in performed_threads: results[thread.name] = thread.result return results But this code works for 1s, not 8s. I tried --strict and many other options, but didn't find why it works in that way. How to turn them off, if it is possible? -
How to transfer from django to drf + nextjs
I divided the django project into back and front. I saw the reference of drf + next.js, but not transfer django to drf + next.js. Please help me I made the previously implemented function react. I'm at a loss trying to convert every page -
Changes to Django-Parler aren't applied
I'm working on my django project and currently I'm incorporating translations and localization and I have an issue. I used to had defoult language English but now I want it to be Spanish, but for some reason it's still English. Also, with Django-parler, I can see on English side of website with Spanish content even I already selected 'hide_untranslated': True, . Why changes aren't applied? # languages LANGUAGE_CODE = 'es' LANGUAGES = [ ('es', _('Spanish')), ('en', _('English')), ('ar', _('Arabic')), ('tr', _('Turkish')), ] LOCALE_PATHS = [ BASE_DIR / 'locale', ] PARLER_LANGUAGES = { 1: ( {'code': 'es',}, # Spanish {'code': 'en',}, # English {'code': 'ar',}, # Arabic {'code': 'tr',}, # Turkish ), 'default': { 'fallbacks': ['es'], 'hide_untranslated': True, } } Thanks in advance! -
Django-tenants based multi tenant server is not getting accessed from browser
Recently i have configured multi tenancy architecture in Django using django-tenants package. When accessing the newly created tenants on the Django server deployed on development environment( localhost) it is working fine. But on the production environment when i am accessing the tenants by giving following address:- http://demo.maumodern.co.in/ i am getting following error:- This site can’t be reachedCheck if there is a typo in demo.maumodern.co.in. If spelling is correct, try running Windows Network Diagnostics. DNS_PROBE_FINISHED_NXDOMAIN Please help me to diagnose this issue. Thanks & Regards Neha Singh I have tried looking all the configuration on Apache Tomcat and django server but of no avail -
Is it necessary to use Nuxt Server as an intermediary between my external Django API and the Nuxt 3 frontend in SSR mode?
I am developing a SaaS application using a backend architecture with a Django REST API and a PostgreSQL database, while the frontend uses Nuxt 3 with TypeScript, Tailwind, and TanStack Query for API request management. I have enabled Server-Side Rendering (SSR) by setting ssr: true in the nuxt.config.ts file : export default defineNuxtConfig({ ssr: true, }) In my current architecture, I have a server/api/ directory within my Nuxt 3 application containing multiple files that represent endpoints to interact with the Django API. For instance, I have a file server/api/projects/index.ts that points to the Django endpoint /api/projects/ to fetch all projects. Nuxt Server Integration: Nuxt Server Directory Structure: server/api/projects/index.ts : Points to the Django endpoint /api/projects/ to fetch all projects. server/api/projects/[id].get.ts : Fetches a project by its ID from /api/projects/detail/${projectId}/. API Interaction Logic: These endpoints are used within a service handler (api/projects.api.ts) that provides functions like getAllProjects, getProjectById, and deleteProjectById. Composable (useProjects.ts): The composable useProjects.ts uses the functions in api/projects.api.ts to manage project data and interact with the Nuxt Server endpoints in server/api/projects/. It leverages useQuery from TanStack Query for efficient state management. Question : Is it necessary to have an intermediary Nuxt server between the Nuxt 3 frontend and an … -
Poetry installed packages not recognized in VS code
I need some advice on Poetry package manager. I am working on a Django rest API. I use Poetry for the project. I ran into a situation that I do not understand. First, I made a virtual environment with pyenv, then I ran poetry install to install required packages, such as Django restframework, psycopg2 and everything. After that, in the VScode, it doesn't seem these packages not working properly because when I import these packages, it shows yellow underline. When I installed these packages globally with pip, then it all started working. So, my question is that when I work with Poetry, should I install the all packages that I need in a project globally also? It seems a little bit messy. Please give me an advice or any comment will be greatly appreciated. -
HttpOnly cookie in NextJS + Redux + Django API for storing JWT
I'm using NextJS in the frontend, Django API in the backend along with DRF and JWT for authentication and redux for state management. Almost all of my routes requires authentication. I'm able to store and access tokens in http-only cookies via NextJS routes API but since I'm using Redux too, all of my requests are going like this; user request -> redux action -> nextjs route -> backend Is this normal? I'd to implement nextjs route for each route just to access the http-only cookie and send it to backend endpoint as the route requires an authentication. This is tedious to implement and maintain, I've hundreds of routes. Is there any other way I can achieve this efficiently? -
Method "PATCH" not allowed error in django
I have django rest framework and with generics views. Whenever I try to make a PATCH request, I get an error that method not allowed. Below is my views.py code class VisitorsLogBooktbViewSet(generics.ListCreateAPIView): queryset = VisitorsLogBooktb.objects.all() serializer_class = VisitorsLogBooktbSerializer class Visitor_data(generics.RetrieveUpdateDestroyAPIView): queryset = models.VisitorsLogBooktb.objects.all() serializer_class = VisitorsLogBooktbSerializer and below is my urls.py code in the app root urlpatterns = [ path('', VisitorsLogBooktbViewSet.as_view(),), path('api/All-visitors/', Visitor_data.as_view(),), ] I have tried changing the generics views by creating views only for updates using just generics.UpdateAPIView......But it still doesn't work. -
django project on macbook pro M1 pro crashed with illegal hardware instruction
environment: 16-inch,2021 cpu: Apple M1 Pro mermory: 16 GB os version: 14.4.1 (23E224) python version: 2.7.15 i try to run "python manage.py runserver 0.0.0.0:8080", but i got illegal hardware instruction.(history project on my company is using python2.7&Django==1.11.29) below is the traceback on osx system report; ------------------------------------- Translated Report (Full Report Below) ------------------------------------- Process: python2.7 [20108] Path: /Users/USER/*/python2.7 Identifier: python2.7 Version: ??? Code Type: X86-64 (Translated) Parent Process: zsh [19681] Responsible: pycharm [750] User ID: 505 Date/Time: 2024-05-04 23:55:26.3734 +0800 OS Version: macOS 14.4.1 (23E224) Report Version: 12 Anonymous UUID: 5CBB7AC0-C198-33B7-4503-8B049D36B4D6 Sleep/Wake UUID: AC988E56-79A2-4466-AAD1-47F1578D8084 Time Awake Since Boot: 22000 seconds Time Since Wake: 3855 seconds System Integrity Protection: enabled Notes: PC register does not match crashing frame (0x0 vs 0x10CD53688) Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_BAD_INSTRUCTION (SIGILL) Exception Codes: 0x0000000000000001, 0x0000000000000000 Termination Reason: Namespace SIGNAL, Code 4 Illegal instruction: 4 Terminating Process: exc handler [20108] Error Formulating Crash Report: PC register does not match crashing frame (0x0 vs 0x10CD53688) Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 corecext.so 0x10cd53688 initcorecext + 9048 1 libpython2.7.dylib 0x10cfe9df6 _PyImport_LoadDynamicModule + 150 2 libpython2.7.dylib 0x10cfe848f import_submodule + 319 3 libpython2.7.dylib 0x10cfe7ebe load_next + 270 4 libpython2.7.dylib 0x10cfe6c9b PyImport_ImportModuleLevel + 939 5 libpython2.7.dylib 0x10cfbd0d7 … -
how to load the sale price based on the selecter with django
hi I am a beginner on django and I would like to display the sale price depending on the product selected, see my source codes below. I'm stuck and I can't unblock, please I need your help. Thanks for your help the sales model: class Sale(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) product = models.ForeignKey('Product', on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) sale_price = models.PositiveIntegerField(default=0) montant_total = models.CharField(max_length=15, default=0) def __str__(self): return self.montant_total the views : def addSale(request=None): current_sale = Sale() list_user = User.objects.all().order_by('-username') list_product = Product.objects.all().order_by('-name') if request.POST: if request.POST.get('user') != "": current_sale.user = User.objects.get(id=request.POST.get('user')) if request.POST.get('product') != "": current_sale.product = Product.objects.get(id=request.POST.get('product')) if request.POST.get('quantity') != "": current_sale.quantity = request.POST.get('quantity') if request.POST.get('sale_price') != "": current_sale.sale_price = request.GET.get('price') if request.POST.get('montant_total') != "": current_sale.montant_total = request.POST.get('montant_total') current_sale.save() return redirect('products-list') context = {'sale': current_sale, 'list_user': list_user, 'list_product': list_product} return render(request, 'daara/add_sale.html', context) the add_sale.html template: <div class="card-body"> <form method="POST"> {% csrf_token %} <div class="form-group col-md-6"> <label for="utilisateur">Utilisateur</label> <select class="form-control" name="user"> <option value="1" selected="selected">Selectionez un utilisateur</option> {% for user in list_user %} {% if user.id == sale.user.id %} <option value="{{sale.user.id}}" selected="selected">{{sale.user.username}}</option> {% else %} <option value="{{user.id}}">{{user.username}}</option> {% endif %} {% endfor %} </select> </div> <div class="form-group col-md-6"> <label for="produit">Produit</label> <select class="form-control" name="product" id="product"> <option value="0" selected="selected">Selectionez un produit</option> … -
Whenever I try running the server for django in my virtual enviroment it doesn't work
Whenever I try running the server for django in my virtual enviroment it doesn't work. Example: python manage.py runserver Replies: NameError: name 'include' is not defined I know it's referencing my urls.py where I say path('hello/', include("hello.urls")) but I need that for me to do what I'm doing I tried looking on stack overflow, youtube, fixing it, trying something my ide said would work. All I wanted it to do was run a server that I could copy and paste the url for and would be able to access it but no. -
Choosing Between Django and Headless CMS for Website Development: Seeking Advice
I've been delving into the decision-making process for a website project I'm working on for a hotel owner. They're keen on having a robust admin interface to manage various aspects of the site, including a gallery, blog, events, emails, and payments. While I've done my fair share of research, I'm still grappling with the decision between using Django for its powerful admin capabilities or exploring the possibility of using an open-source headless CMS like Strapi or Payload to streamline content management and integration with a Next.js frontend. Despite my efforts, I find myself in a bit of a quandary. Here's where I could use your expertise: Development Complexity: In your experience, how does the development complexity compare between building everything within Django versus integrating a headless CMS with a Next.js frontend? Admin Interface: How user-friendly and customizable are the admin interfaces provided by open-source headless CMS platforms like Strapi or Payload compared to Django Admin? Performance and Scalability: Are there any performance or scalability considerations I should keep in mind when choosing between Django and a headless CMS for this project? Cost and Deployment: Which open-source headless CMS options allow self-hosting without additional costs for deployment? How do the deployment … -
Custom admin inline for manytomany field
I have a manytomany field called following where all the other users a user is following is stored. I want to be able to view, add, delete the users in this per user in the field. This is my attempt with creating a custom inline in admin can someone help with getting this to work as desired. models.py (following field in class user(abstractuser): following = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Following', blank=True, symmetrical=False) Admin.py: from django.contrib import admin from .models import User class FollowingInline(admin.TabularInline): model = User.following.through fk_name = 'from_user' extra = 1 # Allow adding one extra form for adding followers class UserAdmin(admin.ModelAdmin): list_display = ('username', 'full_name', 'email') inlines = [FollowingInline] def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: if instance.to_user_id: # Check if a user is selected instance.save() elif instance.id: # Check if an existing instance is being deleted instance.delete() formset.save_m2m() admin.site.register(User, UserAdmin)