Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin Custom Add
Say I have a model called Book: class Book(EOModel): title = models.CharField(max_length=100, null=False, blank=False) subtitle = models.CharField(max_length=100, null=True, blank=True) open_library_key = models.CharField(max_length=32, null=True, blank=True) ... location = models.ForeignKey(Order, null=False, blank=False, on_delete=models.PROTECT) The Book model has a classmethod to craete an entry using openlibrary ID. @classmethod def from_open_library(cls, open_library_key: str, location: Order) -> Self: data = open_library_get_book(open_library_key) ... book.save() return book So given a correct openlibrary ID and an Order object from_open_library would create a new entry. My question is, how can I implement an django admin page for it? Can I add a "add via openlibrary" next to the actual add button? The page has a char field to get the ID and dropdown would list the Orders to select. -
Changes detected after squashmigrations
python manage.py showmigrations shows mainapp [X] 0001_initial ... [X] 0240_employer_data [X] 0241_person_metadata [X] 0242_personemployer_employerworkplace [X] 0243_personemployer_employed_personemployer_stage [X] 0244_remove_employerworkplace_and_more I ran python manage.py squashmigrations mainapp 0244 and now showmigrations shows mainapp [-] 0001_squashed_0244_remove_employerworkplace_and_more (244 squashed migrations) Run 'manage.py migrate' to finish recording. But python manage.py migrate reports the errors No migrations to apply. Your models in app(s): 'mainapp' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. How can there be changes detected immediately after running squashmigrations without doing anything in between? python manage.py makemigrations --dry-run shows many "Alter field" lines like Migrations for 'mainapp': mainapp/migrations/0001_squashed_0244_remove_employerworkplace_and_more.py ~ Alter field field on employergroup ~ Alter field image_alt on employee ~ Alter field context on employer ... My expectation: After running squashmigrations, makemigrations should show "No changes detected" So what happened? What might have caused this bizarre situation? How might I fix it? -
Pytest fails with "ValueError: Missing staticfiles manifest entry for 'assets/img/favicon.ico' " while STATICFILES_STORAGE is set to default in tests
FAILED tests/test_views.py::test_index_view - ValueError: Missing staticfiles manifest entry for 'assets/img/favicon.ico' In my Django Template based project I have the error above when running pytests on views. Generally I understand what this is and how to deal with this when deploying BUT do not wish to worry about the static files manifest with these tests. The most obvios solution I found is to disable it by setting STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' in settings/test.py; this being the default, I shouldn't be worrying about the manifest entries any more, but it persists. I wrote a testcase to confirm that pytest infact uses this setting and that test case passes. In summary, why do I have a manifest entry error from tests running with the default STATICFILES_STORAGE setting and how do I specifically fix this? have tried a few other options but the general principle seems to be around changing the settings for STATICFILES_STORAGE. What am I missing/getting wrong? The simple view function: def index(request): return render (request, "main/index.html") The test cases i.e. tests/test_views.py: import pytest from django.urls import reverse from django.test import Client from django.conf import settings from main.models import SubscriptionPlan def test_static_storage(): print(settings.STATICFILES_STORAGE) assert settings.STATICFILES_STORAGE == 'django.contrib.staticfiles.storage.StaticFilesStorage' def test_index_view(): """ Test that the … -
Django: "KeyError: 'Django'"
The immediate traceback is this: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/template/utils.py", line 69, in __getitem__ return self._engines[alias] ~~~~~~~~~~~~~^^^^^^^ KeyError: 'django' During handling of the above exception, another exception occurred: Okay, here is the complete traceback: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/template/utils.py", line 69, in __getitem__ return self._engines[alias] ~~~~~~~~~~~~~^^^^^^^ KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/threading.py", line 1041, in _bootstrap_inner self.run() ~~~~~~~~^^ File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/threading.py", line 992, in run self._target(*self._args, **self._kwargs) ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) ~~^^^^^^^^^^^^^^^^^ File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/core/management/commands/runserver.py", line 134, in inner_run self.check(display_num_errors=True) ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/core/management/base.py", line 486, in check all_issues = checks.run_checks( app_configs=app_configs, ...<2 lines>... databases=databases, ) File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/contrib/admin/checks.py", line 79, in check_dependencies for engine in engines.all(): ~~~~~~~~~~~^^ File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/template/utils.py", line 94, in all return [self[alias] for alias in self] ~~~~^^^^^^^ File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/template/utils.py", line 85, in __getitem__ engine = engine_cls(params) File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/template/backends/django.py", line 26, in __init__ options["libraries"] = self.get_templatetag_libraries(libraries) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^ File "/Users/mike/.virtualenvs/djangoprod/lib/python3.13/site-packages/django/template/backends/django.py", line 88, in get_templatetag_libraries libraries … -
Django not Working in ASGI app in second/defferent process
I have Django and FastAPI on process#1, and they work in Sync and Async functions with no problem. I am running the SocketIO app in process#2 with multiprocessing. ProcessusingAsyncServerandASGIApp. The problem is that Django works with Sync functions like get()orcreate(), but if we use aget()oracreate()` the process disappears and vanishes. The rest of the line never runs with no error. self.sio = socketio.AsyncServer( async_mode="aiohttp", cors_allowed_origins=self.socket_config.cors_allowed_origins, always_connect=self.socket_config.always_connect, logger=self.logger if self.socket_config.logger else False, engineio_logger=self.logger if self.socket_config.engineio_logger else False, ) self.socket_application = socketio.ASGIApp(self.sio, socketio_path=self.socket_config.socketio_path) and run it with uvicorn with pro multiprocessing.Process( target=uvicorn.run, kwargs={ "app": "0.0.0.0", "host": 8002, "port": int(service_config.SERVICE_PORT), }, daemon=True ).start() I have tried to add get_asgi_application() into other_asgi_app of socketio.ASGIApp but nothing changed. I think the problem isn't from the Django setting with async permissions, it is between the ASGIApp and Django. When it logged the self.socket_application from ASGIApp something interesting showed up, ...DjangoDBProcessRemove object .... I would be looking forward to any help. Update: If I run the SocketIO application in the main process works just fine. So I did. SocketIO in the main process and FastAPI in the Second with multiprocess, This time FastAPI faced this issue. -
I dont have intellisense in django while im using vscode
my vscode doest have intellisense for these things: settings.py: Ihave no intellisense in that file importing settings: when i do this: from django.conf import settings a = settings. # i have no intellisense after the dot too saving objects: when im using filter , get and etc in .objects i dont i have any intellisense. For example: from .models import Account user: Account = Account.objects.get() # i dont have any intellisense in get method even with filtering with Q method I try installing extenstions like django django-intellisense, django template but they dont work, also i try using mypy and django-stubs but they dont work too, and i try changing my vscode settings but none of them worked. my settings: { "djangointellisense.projectRoot": "C:/path/myprojectname", "djangointellisense.settingsModule": "myprojecctname.settings", "djangointellisense.debugMessages": false, "python.languageServer": "Jedi", "python.analysis.extraPaths": ["C:/path/myprojectname"], "python.autoComplete.extraPaths": ["C:/path/myprojectname"], "python.analysis.autoImportCompletions": true, } -
Relier plusieurs projets django à une même base des données? [closed]
J’essaye de creer une base des données postgreSQL qui sera commune à deux projets django qui utilisent les mêmes models Premièrement j’ai crée une application commune CommonModels dans le repertoire parents des deux projets django en utilisant django-admin startapp CommonModels ! Je l’ai installé en tant que module avec pip install -e CommonModels .Ensuite je l’ai inclus dans les deux projets django . Mais quand j’essay de mettre CommonModels dans installed_apps de chaque projet et que j’applique les migrations , une erreur d’importation de CommonModels dans installed_apps empêche l’execution des migrations! J’ai besoin d’aide pour la resolution de ce problème svp ! -
In Django are updates of dict within a form class from a view persistent for all users? [duplicate]
I use Django 5.1.2 In order to clarify what my users need to do when my app serves them a form, I've added a dict to my forms called 'contents'. It contains a bunch of instructions for the template form.html: class MyForm(forms.Form): contents = { 'icon' : 'img/some-icon.png', 'title' : 'Description of form', 'message' : 'Some instruction for user', 'value' : 'text-label-of-the button', } class Meta: fields = ('',) Then in the view myview the form.contents are updated according to what the view does: def myview(request): if request.method == 'GET': form = MyForm() form.contents.update({ 'icon' : 'img/wrong_red.png', 'title' : 'You did it wrong', 'color' : 'red', 'message' : 'Something user did wrong', 'value' : 'Cancel', }) context = {'form' : form} return render(request, 'form.html', context) I run into the problem that the updated content for color persist throughout multiple requests from users. I would expect that update to a value in a class instance wouldn't persist. In my memory this used to be the case. As a work-around I could make a unique form class for each view, but this would result in a lot of repetitive code. What is the best fix for this issue? -
HTMX Django not activating on form fields
I have a form with 3 select options, when the user selects the first one i updated the second with htmx, when the used selects the second i would like to update the third the same way. However, the third doesn't initialize the htmx request. Here is my django form: purchased_by = forms.ModelChoiceField( label="Empresa compradora", queryset=OurCompany.objects.filter(definecat=2).order_by('name'), widget=forms.Select(attrs={'class': 'form-control', 'hx-get': reverse_lazy('compras:oc_update_local'), 'hx-trigger': 'change', 'hx-target': '#div_local', 'hx-swap': 'outerHTML'}), ) delivery_location = forms.ModelChoiceField( label="Local de Entrega/Obra", queryset=Empreendimento.objects.all().order_by('name'), widget=forms.Select(attrs={'class': 'form-control', 'hx-get': reverse_lazy('compras:oc_update_cc'), 'hx-trigger': 'change', 'hx-target': '#div_cc', 'hx-swap': 'outerHTML'}), ) This is my views: def oc_update_local(request): company = request.GET.get('purchased_by') empresa = OurCompany.objects.get(pk=company) if empresa.definecat == 1: if empresa.name[:5] == "Cabiu": company = OurCompany.objects.get(name='Cabiunas Inc') empreendimentos = Empreendimento.objects.filter( company=company).order_by('name') elif empresa.name[:5] == "Coque": company = OurCompany.objects.get( name='Coqueiral Agropecuaria Matriz') empreendimentos = Empreendimento.objects.filter( company=company).order_by('name') else: empreendimentos = Empreendimento.objects.filter( company=company).order_by('name') return render(request, "compras/partials/oc_update_local.html", {"empreendimentos": empreendimentos}) def oc_update_cc(request): local = request.GET.get('delivery_location') ccs = CentroCusto.objects.filter(imovel=local).order_by('name') return render(request, "compras/partials/oc_update_cc.html", {"ccs": ccs}) And this is my html template: <div class="form-row"> <div class="form-group col-3"> {{ form.purchased_by | as_crispy_field }} </div> <div class="form-group col-4" id="div_local"> {{ form.delivery_location | as_crispy_field }} </div> <div class="form-group col-4" id="div_cc"> {{ form.cc |as_crispy_field }} </div> </div> And i have a partial for each update, but the second never triggers. … -
Why is the JSONField data not displayed correctly in the vector tile response?
I’m encountering an issue with displaying data from a JSONField in a vector tile (MVT) in Django. The value of the data in the test_json_field column is as follows: { "look": "1", "at": 2, "some": "asdfjkl;", "JSON": [ { "data": 1234, "arranged": "(and how!)" }, "as an example" ] } In my code, I’ve defined the tile_fields as: tile_fields = ("start_time", "end_time", "test_json_field") However, when I render the view, I only see the following fields in the JSON response: { "start_time": "2024-12-12 08:00:00+00", "end_time": "2024-12-12 08:15:00+00", "at": 2, "look": "1", "some": "asdfjkl;", "layer": "trajectory" } But the other values in the test_json_field column (such as the JSON array) are not displayed. Here’s my code: The TrajectoryTileView class: `class TrajectoryTileView(VectorLayer): """ A view to represent trajectory data as a vector tile layer. """ model = Trajectory id = "trajectory" tile_fields = ("start_time", "end_time", "test_json_field") geom_field = "geom" def get_queryset(self): device_id = getattr(self, "device_id", None) queryset = Trajectory.objects.all() if device_id: queryset = queryset.filter(device__uid=device_id) return queryset` The TrajectoryMVTView class: `class TrajectoryMVTView(MVTView): """ MVTView handles one or more vector layers defined in the layer_classes attribute. """ layer_classes = [TrajectoryTileView] def get(self, request, *args, **kwargs): device_id = kwargs.get("device_id") for layer_class in self.layer_classes: layer_class.device_id = device_id … -
Dead lock found in django transaction with select_for_update function
I have two functions: one for updating data and one for reading data. When they run concurrently in two threads, a deadlock occurs. Does anyone know why? The database's isolation level is set to REPEATABLE-READ. sleep function is used to increase the likelihood of a deadlock occurring. @transaction.atomic() def func_change_data(): print("start") time.sleep(10) boos = Boo.objects.select_for_update(skip_locked=True).filter(pk=xxx) if not changes.exists(): return print("sleep") time.sleep(10) boo = boos.first() boo.stage = 'stage_2' boo.save() print("end") @transaction.atomic() def func__read(): boo = Boo.objects.select_for_update().get( pk=xxx, target_branch='master', stage='stage_1' ) time.sleep(10) print("end sleep") -
How to join attributes of a reverse ManyToManyField in Django ORM
Suppose that these are my models: class Product(models.Model): sku = models.CharField(unique=True) # Something like RXT00887 class Bill(models.Model): customer = models.ForeignKey(Customer) products = models.ManyToManyField(Product) date = models.DateTimeField() Each Product is related to only one Bill or none at all. I am working on a feature which requires me to search through the Products that were bought by a given customer. I am achieving this through: bills = Bill.objects.filter(customer=customer) results = Product.objects.filter(bill__in=bills, sku__icontains=search_str) However, I also need to have some attributes of Bill of each product in the results. For example, I need the bill id and the bill date. So each row in the result should contain all attributes of the product along with two additional attributes: bill_id and bill_date. Is it possible to achieve this is Django by using joins? If so, how? -
Django Form Submission Not Triggering `create_cancel` View
Problem Description: I am implementing an order cancellation feature in my Django application. The process involves displaying a cancellation form (cancel-order.html) using the cancel_order view and processing the form submission with the create_cancel view to update the product_status of CartOrder and CartOrderItems. However, the issue is that the create_cancel view is not being triggered when the form is submitted. No success or error messages are displayed, and no updates are made to the database. Views: Here are the relevant views: def cancel_order(request, oid): sub_category = SubCategory.objects.all() categories = Category.objects.prefetch_related('subcategories').order_by('?')[:4] wishlist = wishlist_model.objects.filter(user=request.user) if request.user.is_authenticated else None nav_category = Category.objects.filter(special_category=True).prefetch_related('subcategories').order_by('?')[:4] order = CartOrder.objects.get(user=request.user, id=oid) products = CartOrderItems.objects.filter(order=order) # Calculate discounts for each product total_old_price = 0 total_price = 0 for item in products: product = item.product # Assuming a ForeignKey from CartOrderItems to Product qty = item.qty # Assuming a quantity field in CartOrderItems total_old_price += (product.old_price or 0) * qty total_price += (product.price or 0) * qty # Calculate total discount percentage if total_old_price > 0: # Prevent division by zero discount_percentage = ((total_old_price - total_price) / total_old_price) * 100 else: discount_percentage = 0 context = { "order": order, "products": products, "sub_category": sub_category, "categories": categories, "wishlist": wishlist, "nav_category": nav_category, "discount_percentage": … -
When I create custom permissions, After saving it automatically deleting the saved permissions in Django
In the Django admin class for the group creation page, I added additional fields. Based on these fields, I need to filter and set the permissions for the group. However, the issue arises in the save method. Although it saves the permissions, I noticed during debugging that the save_m2m() method in the superclass deletes all the assigned permissions class CustomGroupForm(forms.ModelForm): env_name = forms.CharField(max_length=100, required=False) schema_name = forms.CharField(max_length=100, required=False) class Meta: model = Group fields = ['name', 'permissions', 'env_name', 'schema_name'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['permissions'].queryset = Permission.objects.none() def save(self, commit=True): group = super().save(commit=False) # Use the name field as the prefix to filter permissions name = self.cleaned_data.get('name', '') prefix = name logger.info(f'Prefix 1: {prefix}') # Filter permissions using the prefix filtered_permissions = Permission.objects.filter( content_type__app_label__startswith=prefix ) # Save the group first to ensure it has an ID group.save() # Set the filtered permissions group.permissions.set(filtered_permissions) if commit: group.save() return group I expected the custom logic in the save method to correctly save the filtered permissions to the group without being overwritten. Specifically, I wanted the dynamically filtered permissions to persist after saving, without the save_m2m() method clearing them. -
Forbidden (CSRF cookie not set.) Django, Next.js
I am trying to post data to a Django server in order to update a user profile from a Next.js app; I have this similar setting with other routes and they work fine, but here I get the following error: Forbidden (CSRF cookie not set.): /users/api/update-profile/ [15/Dec/2024 20:53:02] "POST /users/api/update-profile/ HTTP/1.1" 403 2855 #settings.py CSRF_COOKIE_HTTPONLY = False # Allow JavaScript to read the CSRF cookie #CSRF_USE_SESSIONS = False CSRF_COOKIE_SAMESITE = 'Lax' CSRF_COOKIE_SECURE = False # Ensure these are set correctly SESSION_COOKIE_SAMESITE = 'Lax' # or 'None' for cross-site CSRF_COOKIE_SAMESITE = 'Lax' # or 'None' for cross-site MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOW_CREDENTIALS = True #CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOWED_ORIGINS = [ #"http://localhost", #"http://127.0.0.1", "http://localhost:3000" ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] #views.py @login_required def update_profile(request): if request.method == 'POST': user = request.user print('user', user) # Gender validation if 'gender' in request.POST: gender = request.POST.get('gender') if gender in dict(user.gender_choices): user.gender = gender # Username validation if 'username' in request.POST: username = request.POST.get('username') if len(username) <= 50 and not User.objects.exclude(pk=user.pk).filter(username=username).exists(): user.username = username else: return JsonResponse({'status': 'error', 'message': 'Invalid or … -
Django: Cancel Order functionality not updating CartOrder and CartOrderItems instances
I'm building an e-commerce application using Django, and I'm having trouble with the cancel order functionality. When a user cancels an order, I want to update the product_status field of both the CartOrder and CartOrderItems instances to "cancelled". However, the update is not happening, and I'm not seeing any error messages. Here's my code: models.py: class CartOrder(models.Model): # ... product_status = models.CharField(choices=STATUS_CHOICE, max_length=30, default="processing") class CartOrderItems(models.Model): # ... product_status = models.CharField(max_length=200, blank=True, null=True) order = models.ForeignKey(CartOrder, on_delete=models.CASCADE, related_name="cartorderitems") views.py: def create_cancel(request, oid): if request.method == "POST": user = request.user try: # Fetch the CartOrder instance order = get_object_or_404(CartOrder, id=oid) order.product_status = "cancelled" order.save() # Fetch the related CartOrderItems instance order_item = order.cartorderitems.first() order_item.product_status = "cancelled" order_item.save() # Fetch the associated product product = get_object_or_404(Product, pid=order.pid) # Additional product-related operations can be done here, if needed messages.success(request, "Order successfully cancelled.") except Exception as e: messages.error(request, f"An error occurred: {e}") return redirect("core:dashboard") else: messages.error(request, "Invalid request method.") return redirect("core:dashboard") I've tried using order.cartorderitems.first() and CartOrderItems.objects.filter(order=order).first() to get the related CartOrderItems instance, but neither approach is working. Can anyone help me figure out what's going wrong? I've checked the database, and the product_status field is not being updated for either the CartOrder or … -
PDFs with ReportLab in Django. Punjabi Unicode (e.g., ਵਿਰੋਧ ਦੇ ਸਮੇਂ ਫਾਸ਼ੀਵਾਦ) is not displaying correctly. Need font solution
def generate_punjabi_pdf(request): font_path = os.path.join(settings.BASE_DIR, 'static/myapp/css/fonts/Noto_Sans_Gurmukhi/static', 'NotoSansGurmukhi-Regular.ttf') pdfmetrics.registerFont(TTFont('NotoSansGurmukhi', font_path)) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="punjabi_text.pdf"' c = canvas.Canvas(response, pagesize=A4) c.setFont("NotoSansGurmukhi", 16) c.drawString(100, 750, "ਵਿਰੋਧ ਦੇ ਸਮੇਂ ਫਾਸ਼ੀਵਾਦ") c.showPage() c.save() return response -
Django does not detect change to the code when running it with Cursor
My app is based on Django 4.2.16. When I run the app in PyCharm, I see the following message when I run the app: "Watching for file changes with StatReloader". In this setup, changes to HTML files are immediately reflected on the web page after refreshing the browser. The application automatically reloads when I make changes to backend code. However, after switching to Cursor, this behavior is no longer working: I need to manually stop and restart the server for changes (both to HTML and backend code) to take effect. Here is my launch.json configuration in Cursor: { "version": "0.2.0", "configurations": [ { "name": "Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": ["runserver", "localhost:8000"], "django": true, "justMyCode": true, "console": "integratedTerminal", "cwd": "${workspaceFolder}", "pythonPath": "C:/Users/xxx/miniconda3/envs/xxxconda3/python.exe" } ] } I tried to install watchdog with pip but it did not change anything. In my settings.py file, DEBUG = True What can I do ? -
Unable to use psycopg2 with Postgres in Django
As stated in my question, I am now configuring my djagno project to connect with postgres. The issue i am facing is that, when making migrations, it shows me the following error: python manage.py makemigrations Traceback (most recent call last): File "E:\Code\Ecom\Ecom\ecom\Lib\site-packages\django\db\backends\postgresql\base.py", line 25, in <module> import psycopg as Database ModuleNotFoundError: No module named 'psycopg' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "E:\Code\Ecom\Ecom\ecom\Lib\site-packages\django\db\backends\postgresql\base.py", line 27, in <module> import psycopg2 as Database File "E:\Code\Ecom\Ecom\ecom\Lib\site-packages\psycopg2\__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ...<10 lines>... ) ImportError: DLL load failed while importing _psycopg: The specified module could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "E:\Code\Ecom\Ecom\backend\manage.py", line 22, in <module> main() ~~~~^^ File "E:\Code\Ecom\Ecom\backend\manage.py", line 18, in main execute_from_command_line(sys.argv) ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^ File "E:\Code\Ecom\Ecom\ecom\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() ~~~~~~~~~~~~~~~^^ File "E:\Code\Ecom\Ecom\ecom\Lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() ~~~~~~~~~~~~^^ File "E:\Code\Ecom\Ecom\ecom\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\Code\Ecom\Ecom\ecom\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() ~~~~~~~~~~~~~~~~~~~~~~~~^^ File "E:\Code\Ecom\Ecom\ecom\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^ File "E:\Coding Apps\Lib\importlib\__init__.py", line 88, in import_module return _bootstrap._gcd_import(name[level:], package, level) ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File … -
How can I turn a PC into a Django web hosting server for use by 50 to 100 users at the same time?
I want to develop an application to manage an organization, which will be used by 50 to 100 users simultaneously. It will work only on a local network and will not connect to the internet. I want the application to be developed using web technologies, not desktop applications, and in Python and Django. How can I turn a PC into a Django web hosting server for use by 50 to 100 users at the same time? What are the requirements for this device? -
Django has a slow import time when using Poetry instead of PIP
I used PIP and poetry in the same project. I also use importtime-waterfall to check import time when running the application (run manage.py file). With case-use Poetry, Django takes more importing time (x2, x3) than case-use PIP. Can you help me explain it? Or give me related documents. Thank you so much !!! -
Python Django Channels provides error on startup on colleagues computer but not on my computer what is going wrong?
I have encountered the following error. The weird thing about this error is that it does not occur on my windows 11 computer, but it only occurs on the windows 11 computer of a colleague and on a remote debian linux server which I have setup specifically to test whether an error like this would also occur on Linux. All computers have the same code (git synced), same libraries (pip freeze and venv), same python version (except the linux server) I cannot figure out the origin and I cannot find any information about a similar error on StackOverflow or any other site. The weird thing is that it does work on my own computer! Traceback (most recent call last): File "/usr/lib/python3.11/threading.py", line 1038, in _bootstrap_inner self.run() File "/usr/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/srv/<redacted>/venv/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/srv/<redacted>/venv/lib/python3.11/site-packages/daphne/management/commands/runserver.py", line 128, in inner_run application=self.get_application(options), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/srv/<redacted>/venv/lib/python3.11/site-packages/daphne/management/commands/runserver.py", line 153, in get_application return ASGIStaticFilesHandler(get_default_application()) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/srv/<redacted>/venv/lib/python3.11/site-packages/daphne/management/commands/runserver.py", line 31, in get_default_application raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'config.asgi' This error is very unhelpful, so after some more debugging we figured out that the origin of the crash comes from: … -
I tried to enable the remove option on cart to remove cart item by adding the some code, result come in following error
I have added the code to enable the remove option on the cart. the following error occurs. Reverse for 'remove_cart_item' with arguments '(2,)' not found. 1 pattern(s) tried: ['cart/remove_cart_item/(?P<product_id>[0-9]+)/(?P<cart_item_id>[0-9]+)/$'] cart.html {% extends 'base.html' %} {% load static %} {% block content %} <!-- ============================ COMPONENT 1 ================================= --> {% if not cart_items%} <h2 class="text-center">Your shopping cart is empty</h2> <br> <div class="text-center"> <a href="{% url 'store' %}" class="btn btn-primary">Continue Shopping</a> </div> {% else %} <div class="row"> <aside class="col-lg-9"> <div class="card"> <table class="table table-borderless table-shopping-cart"> <thead class="text-muted"> <tr class="small text-uppercase"> <th scope="col">Product</th> <th scope="col" width="120">Quantity</th> <th scope="col" width="120">Price</th> <th scope="col" class="text-right" width="200"> </th> </tr> </thead> <tbody> <tr> {% for cart_item in cart_items %} <td> <figure class="itemside align-items-center"> <div class="aside"><img src="{{ cart_item.product.images.url }}" class="img-sm"></div> <figcaption class="info"> <a href="{{ cart_item.product.get_url }}" class="title text-dark">{{cart_item.product.product_name}}</a> <p class="text-muted small"> {% if cart_item.variations.all %} {% for item in cart_item.variations.all %} {{item.variation_category |capfirst }} : {{item.variation_value | capfirst}} <br> {% endfor %} {% endif %} </p> </figcaption> </figure> </td> <td> <!-- col.// --> <div class="col"> <div class="input-group input-spinner"> <div class="input-group-prepend"> <a href="{% url 'remove_cart' cart_item.product.id cart_item.id %}" class="btn btn-light" type="button" id="button-plus"> <i class="fa fa-minus"></i> </a> </div> <input type="text" class="form-control" value="{{cart_item.quantity}}"> <div class="input-group-append"> <form action="{% url 'add_cart' cart_item.product.id %}" method="POST"> … -
Override Django Admin Template In 3rd Party Package?
I am developing a Python package which includes a Django addon app. The package is related to authentication so I wanted to extend the django.contrib.admin login page. Is it possible for my 3rd party package to override another 3rd party package? The template for the login page is under django/contrib/admin/templates/admin/login.html. Which means the template is registered as admin/login.html. I put my overridden template in my package's templates/admin/login.html directory but the template does not get overridden. The order of my package and Django contrib admin in INSTALLED_APPS, template app dirs = true don't seem to change this. -
As I try to add product by selecting its variaitons this error appears NoReverseMatch at /cart/
cart.html <td class="text-right"> <a href="{% url 'remove_cart_item' cart_item.product.id cart_item.id %}" class="btn btn-danger"> Remove</a> </td> urls.py file of the carts app urlpatterns = [ path('', views.cart, name='cart'), path('add_cart/<int:product_id>/', views.add_cart, name='add_cart'), path('remove_cart/<int:product_id>/<int:cart_item_id>/', views.remove_cart, name='remove_cart'), path('remove_cart_item/<int:product_id>/<int:cart_item_id>/', views.remove_cart_item, name='remove_cart_item'), ] views.py file of the carts app def remove_cart_item(request, product_id, cart_item_id): cart = Cart.objects.get(cart_id = _cart_id(request)) product = get_object_or_404(Product, id=product_id) cart_item = CartItem.objects.get(product = product, cart = cart, id=cart_item_id) cart_item.delete() return redirect('cart')