Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 4.2.2 not respecting STORAGES['default']['BACKEND']
Using settings.py: STORAGES = { "staticfiles": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage", }, "mediafiles": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage", }, "default": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage", }, } and running: from django.conf import settings print('settings.DEFAULT_FILE_STORAGE', settings.DEFAULT_FILE_STORAGE) prints: settings.DEFAULT_FILE_STORAGE django.core.files.storage.FileSystemStorage Media is writing to local and not S3 and this must be why. Static, for some reason, writes to S3 no problem. Any help or ideas would be appreciated. The full codebase can be seen here: https://github.com/rkuykendall/Simplici7y -
Is Using Psycopg2 with Django Ok?
I prefer using Psycopg2 over Django's built-in database handling system. Are there any major disadvantages to this? Would this not work well with larger-scale projects? Are there any important features that I would be missing out on this way? -
Validate a model instance for unique drf
I am working on a "Recipes" model and I want to prevent the creation of duplicate models with the same fields. Specifically, I want to throw a validation error if a model instance already exists with the same field values. This is my current code: def validate_recipe(self, value): recipes = Recipe.objects.all().filter(author=self.context['request'].user) for rec in recipes: if rec._meta.fields == value._meta.fields: raise serializers.ValidationError( {'errors': 'Do you have this recipe!'} ) return value Here are the images of the output I am currently getting: enter image description here enter image description here -
Dynamically scheduled tasks
I successfully configured Celery on my Django app and tested it. The test run was successful, as shown by the following output: celery -A concentrApp call mytask 0016f381-ed04-4a44-8c7a-c091a66dce0a [2023-06-17 13:46:28,465: INFO/MainProcess] Task mytask[0016f381-ed04-4a44-8c7a-c091a66dce0a] received [2023-06-17 13:46:28,477: INFO/ForkPoolWorker-8] Task mytask[0016f381-ed04-4a44-8c7a-c091a66dce0a] succeeded in 0.009182458000005056s: None ` Now, I would like to take this a step further and make the task dynamic. My goal is to create an endpoint that accepts parameters such as time, and param, and then run the task every sunday-thursday in the given hour using the provided parameter. This will allow me to customize the task execution based on user input, and make it several times that the user want. Thank you -
مشکل ارور :Page not found (404) در جنگو
I wrote a program in Zang, but whatever I do, it gives this error: 404 Using the URLconf defined in storefront.urls, Django tried these URL patterns, in this order: admin/ The current path, contact/, did not match any of these. URLs.py code: from django.urls import path from .views import save_user urlpatterns = [ path('save-user/', save_user, name='save_user'), ] There is no error during execution, but when I enter the code: http://localhost:8000/myapp/save-user/ in the browser, it gives an error on that page. -
can't open the page "127.0.0.1:8000" because the server dropped the connection unexpectedly
I want to run a Django project via Docker. I wrote a Dockerfile and docker-compose, but when I run the Django project it says : "Safari can't open the page Safari can't open the page "127.0.0.1:8000" because the server dropped the connection unexpectedly. This problem sometimes occurs if the server is busy. Wait a few minutes and try again." Dockerfile FROM python:3.9-slim WORKDIR /app RUN pip3 install --upgrade pip wheel COPY . . ADD requirements.txt . RUN pip3 --no-cache-dir install -r requirements.txt CMD ["python3", "manage.py", "runserver", "127.0.0.1:8000"] docker-compose.yml version: '3.6' services: invite_service: container_name: invite_service build: dockerfile: Dockerfile context: . ports: - "8000:8000" ALLOWED_HOSTS in Django settings ALLOWED_HOSTS = ['localhost', '127.0.0.1', '0.0.0.0'] -
psycopg2.OperationalError triyng to connect postgres to django
i am getting this error when i try to runserver: `Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\backends\base\base.py", line 289, in ensure_connection self.connect() File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\backends\base\base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\backends\postgresql\base.py", line 275, in get_new_connection connection = self.Database.connect(**conn_params) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\psycopg2_init_.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Zhadi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Zhadi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\core\management\commands\runserver.py", line 136, in inner_run self.check_migrations() File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\core\management\base.py", line 574, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\migrations\loader.py", line 58, in init self.build_graph() File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\migrations\recorder.py", line 81, in applied_migrations if self.has_table(): File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\migrations\recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Zhadi\Desktop\Coding\Python\bronKz\back\env\lib\site-packages\django\db\backends\base\base.py", line … -
DJANGO: I have genres in my database, and django doesnt display them in my page('shop.html') even though i used loop
I am trying to modify a Django website. One of the webpages lists video games. Each game has a genre property, and I want to allow the user to filter the games based on their genres. However, each game can have multiple genres. Therefore, I created a Genre model that has a "title" property, and each Game has a many-to-many relationship with genres. I have already created the Genre model and created a page that lists all the existing genres. Now I want to create a page that lists all the games that have a certain genre. Here is my code below: in models.py class Genre(models.Model): title = models.CharField(max_length=255, verbose_name='Название жанра') def __str__(self): return self.title in views.py def shop_page(request): return render(request, 'store/shop.html') def genre_page(request, pk): genre = Genre.objects.get(pk=pk) genres = Genre.objects.all() games = Game.objects.filter(genres=genre) context = { # 'genre': genre, 'genres': genres, 'games': games } return render(request, 'store/shop.html', context) in urls.py path('shop/', shop_page, name='shop_page'), path('genre/', genre_page, name='genre'), in shop.html <ul class="trending-filter"> <li> {% for genre in genres %} <a class="is_active" href="{% url 'genre' genre.pk %}" data-filter="*">{{ genre.title }}</a> {% endfor %} </li> </ul> -
How can I use skfuzzy in Django?
I have created a Django project and I want to implement a simple fuzzy logic with three inputs and one output. However, when I import "skfuzzy" in Django views and reload the page, I get a Gateway Timeout error after 2 minutes (even without any implementation, just importing "skfuzzy"). I have run "pip3 install scikit-fuzzy" in the project virtual environment, and everything seems to be working fine. The code runs without a problem in the terminal, but it doesn't work in the Django project. Why is this happening? -
Django filter a model in the template
I want to be able to filter a model in the template (or find a different solution to fix my problem). The relevant models look like this: class CommissionElection(models.Model): title = models.CharField(max_length=64) commission = models.ManyToManyField(Commissie, related_name="elections") class ElectablePerson(models.Model): commission = models.CharField(max_length=128) election = models.ManyToManyField(CommissionElection, related_name="electables") class Commissie(models.Model): commissie = models.CharField(max_length=64) Here Commissie is a model from a different app. I have created a page for a specific election, now I want on that page a list per commission which states all the ElectablePersons that stated themselves electable for that commission (and for that election). I tried the following in my template: {% for commission in election.commission.all %} {{ commission }} {% for electable in election.electables.filter(commission=commission) %} {{ electable}} {% endfor %} {% endfor %} This gives the error Could not parse the remainder: '(commission=commission)' from 'election.electables.filter(commission=commission)' Is there anyway I could filter the model in the template or is there a different way I could do this? -
How to add to card without login, without user authentication. Help in session method of Django
How to add to card without login, without user authentication. Help in session method of Django. I am stuck in this. How to modify this code, so I can easily implement add to card, add to wishlist without login and also connected with users. Models.py class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) product_qty = models.IntegerField(null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) class Wishlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) wishlist.py from django.http import JsonResponse from django.shortcuts import render, redirect from django.contrib import messages from buyjoi.models import Product, Cart, Wishlist from django.contrib.auth.decorators import login_required @login_required(login_url='loginpage') def wishlistpage(request): wishlistitem = Wishlist.objects.filter(user=request.user) context = {'wishlistitem':wishlistitem} return render(request, 'wishlist.html', context) def addtowishlist(request): if request.method == 'POST': if request.user.is_authenticated: prod_id = int(request.POST.get('product_id')) product_check = Product.objects.get(id=prod_id) if(product_check): if(Wishlist.objects.filter(user=request.user, product_id=prod_id)): return JsonResponse({'status':"Product already in wishlist"}) else: Wishlist.objects.create(user=request.user, product_id=prod_id) return JsonResponse({'status':"Product added to wishlist"}) else: return JsonResponse({'status':"No such product found"}) else: return JsonResponse({'status':"Login to continue"}) return redirect('/') def deletewishlistitem(request): if request.method == 'POST': if request.user.is_authenticated: prod_id = int(request.POST.get('product_id')) if(Wishlist.objects.filter(user=request.user, product_id=prod_id)): wishlistitem = Wishlist.objects.get(product_id=prod_id) wishlistitem.delete() return JsonResponse({'status':"Product removed from wishlist"}) else: Wishlist.objects.create(user=request.user, product_id=prod_id) return JsonResponse({'status':"Product not found in wishlist"}) else: return JsonResponse({'status':"Login to continue"}) return redirect('/') checkout.py from http.client import HTTPResponse from django.shortcuts … -
Is it possible to use update_state and progress_observer within a function executed by a Celery task instead of directly inside the task itself?
I am developing a Django app that browses a website, selects a comic, and downloads it in the background with Celery. In the task.py file, I have a download_comic() function decorated with @shared_task(). The function checks the URL's hostname and uses different child classes of the base class FileHost to download the file. The actual download is done inside the class method, not on the task function. I came across this article (https://buildwithdjango.com/blog/post/celery-progress-bars/) that suggested using task.update_state and progress_observer.set_progress for progress monitoring. However, I am not sure if I can use these functions inside a class method or not. Here's a snippet of the FileHost class and download() method for reference: class FileHost: def __init__(self, url): self.url = url r = requests.get(self.url) self.soup = BeautifulSoup(r.content, "html.parser") def download_file(self): # Implement the file download logic here raise NotImplementedError() def download(self, filename, direct_link): response = requests.get(direct_link, stream=True) temp_path = Path('/tmp') / filename if 'Content-Disposition' in response.headers: content_disposition = response.headers['Content-Disposition'] temp_path = Path('/tmp') / content_disposition.split("=", -1)[-1] if response.status_code == 200: total_size = int(response.headers.get('content-length', 0)) downloaded_size = 0 with open(temp_path, "wb") as file: for chunk in response.iter_content(chunk_size=4096): if chunk: file.write(chunk) downloaded_size += len(chunk) # Calculate the progress percentage progress = int((downloaded_size / total_size) * … -
django migrations error. I migrated model but changes not aplied
i added new field to model and deleted another field but not deleting old field and not adding new feld.I deleted all migration files and re migrate it problem is same not working migration. It was a message " No migrations to apply. here is result after migrate app here is my changed model -
how to update default status of any record using django rest framework
I have three buttons named start, stop and cancel in my project. There is a status field which is default registered. When the 'start' button is clicked, the status should update 'running'. When the 'close' button is clicked, the status should update 'closed'. When the 'cancel' button is clicked, the status should update 'cancelled'. @csrf_exempt def projectApi(request,id=0): if request.method=='GET': project = Project.objects.all() project_serializer = ProjectSerializer(project, many=True) return JsonResponse(project_serializer.data, safe=False) elif request.method=='POST': project_data = JSONParser().parse(request) project_serializer = ProjectSerializer(data=project_data) if project_serializer.is_valid(): project_serializer.save() return JsonResponse("Added Successfully!!", safe=False) return JsonResponse("Failed to Add",safe=False) This is my views.py file. -
Customizing Django viewflow url
I am using the django-viewflow application with a custom view representing a stock item record where there are a number of workflows that can be attached to the record (registering/ issuing/ disposing etc.). In the detail view of the record I want to have a list of all workflows attached to the item and to be able to list all the tasks related to that workflow. I am aiming for a url that looks like .../asset/3/ - for the detail view .../asset/3/register/93/ - for the register process (and subsequent tasks) .../asset/3/movement/1/ - for movement process (and subsequent tasks) etc My application url.py looks like: asset_urls = FlowViewSet(AssetFlow).urls movement_urls = FlowViewSet(MovementFlow).urls app_name = 'asset' workflowurlpatterns = [ # path('ajax/load-budget_lines/', views.load_budget_lines, name='ajax_load_budget_lines'), path('viewflow/', include((asset_urls, 'asset'))), path('movement/', include((movement_urls, 'movement'))), # path('', views.Detail.as_view(), name='detail'), ] urlpatterns = [ path('', views.List.as_view(), name='assets'), path('<int:asset_pk>/', views.Detail.as_view(), name='detail'), path('<int:asset_pk>/', include((workflowurlpatterns))) ] The issue is that all the urls generated by the template tag {% flowurl task user=request.user as task_url %} fail with a NoReverseMatch error. Is there a clever way to pass the asset_id so that the urls work (or another solution)? -
unsupported format character '_' (0x5f)
models.py class ChangingDocument(PrivateCommentMixin, models.Model): # Список изменяющих документов. treaty = models.ForeignKey("treaties.Treaty", on_delete=models.CASCADE, blank=False, null=False, related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", ) changing_document = models.ForeignKey("treaties.Treaty", on_delete=models.CASCADE, blank=False, null=False, related_name="%(app_label)s_%(class)_changing_documents_related", related_query_name="%(app_label)s_%(class)ss_changing_documents", ) def __str__(self): return str(self.changing_document) Stack trace (venv) michael@michael:/media/michael/750/Programming/treaty_outer/treaty_project$ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/usr/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 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/media/michael/750/Programming/treaty_outer/treaty_project/changing_documents/models.py", line 6, in <module> class ChangingDocument(PrivateCommentMixin, File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/db/models/base.py", line 194, in __new__ new_class.add_to_class(obj_name, obj) File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/db/models/base.py", line 371, in add_to_class value.contribute_to_class(cls, name) File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/db/models/fields/related.py", line 866, in contribute_to_class super().contribute_to_class(cls, name, private_only=private_only, **kwargs) File "/media/michael/750/Programming/treaty_outer/venv/lib/python3.8/site-packages/django/db/models/fields/related.py", line 357, in contribute_to_class related_name %= { ValueError: unsupported format character '_' (0x5f) at index 22 Problem I have … -
How upload Django web application using React JS?
Anybody knows how should I upload my Django web application using font-end React JS on Cpanel? -
Not able to override unittest `startTest` and `stopTest` isn’t working correctly in custom test runner when using with –parallel
I have override startTest and stopTest from unittest TextTestResult class and used it in my custom test runner. It’s working correctly in normal scenario but not working correctly when using with --parallel flag. I tried to debug and found the time elapsed b/w startTest and stopTest is coming very very small. Like 4.8000000000492093e-05 which is incorrect. Would someone please tell me is it the right hooks for --parallel flag or I have to use some another hook? -
Reorder models in admin
Could you tell me how to organise an arbitrary order in the admin site> Maybe something ready to use from here https://djangopackages.org/grids/g/admin-interface/ There exists django-modeladmin-reorder But it's a long time since it has been updated. Could you recommend something to me instead of that? -
Pk becoming lost from django url
I have a view defined as follows: u = reverse("ipsych_results", kwargs = {"ipsychcase_id": ipsychvisit_instance.ipsychvisit_id}) print(f'the url being passed to redirect is {u}') return redirect(u) It prints out: the url being passed to redirect is /ipsych/processed/8b429f6d-8538-4af6-90b9-102168887e34/ When I enter http://localhost:8000/ipsych/processed/8b429f6d-8538-4af6-90b9-102168887e34/ into the browser, the subsequent view is generated correctly. However, when I click the Submit button that triggers POST (which prints out the above), I get the following error: Page not found (404) "/Users/a/Documents/websites/website/ipsych/processed" does not exist Request Method: GET Request URL: http://localhost:8000/ipsych/processed// Raised by: django.views.static.serve Why is the ipsychcase_id getting lost? -
How to call an API function using a view
I am trying to fetch data from an API and render that data using a view. I am not sure what is wrong. Could someone please show me what I need to change in order to make it work ? My fixtures.py: def get_fixtures(): credentials = service_account.Credentials.from_service_account_file( settings.GOOGLE_CALENDAR_CREDENTIALS_FILE, scopes=['https://www.googleapis.com/auth/calendar.readonly'] ) service = build('calendar', 'v3', credentials=credentials) events = service.events().list(calendarId='u6kmbrsrt5qr3r6gjrtsussomc@group.calendar.google.com').execute() fixtures = [] for event in events['items']: fixture = { 'summary': event['summary'], 'start': event['start'].get('dateTime', event['start'].get('date')), 'end': event['end'].get('dateTime', event['end'].get('date')), } fixtures.append(fixture) My views.py : def fixtures_view(request): fixtures = get_fixtures() return render(request, 'fixtures.html', {'fixtures': fixtures}) print(fixtures) There's nothing on my HTML page and nothing is being printed on the command prompt either. -
Static files not loading on Django deploy on digitalocean app
I am trying to deploy a Django application on DigitalOcean. However, static files are not getting served on the server. I am not sure what the issue is since they work fine locally. The following is my settings file: from django.core.management.utils import get_random_secret_key from pathlib import Path import os import sys import dj_database_url BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key()) DEBUG = os.getenv("DEBUG", "False") == "True" DEVELOPMENT_MODE = os.getenv("DEVELOPMENT_MODE", "False") == "True" ALLOWED_HOSTS = os.getenv("DJANGO_ALLOWED_HOSTS", "127.0.0.1,localhost").split(",") INSTALLED_APPS = [ 'app.apps.AppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', "whitenoise.runserver_nostatic", # new "django.contrib.staticfiles", ] 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', ] ROOT_URLCONF = 'myapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myapp.wsgi.application' if DEVELOPMENT_MODE is True: DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), } } elif len(sys.argv) > 0 and sys.argv[1] != 'collectstatic': if os.getenv("DATABASE_URL", None) is None: raise Exception("DATABASE_URL environment variable not defined") DATABASES = { "default": dj_database_url.parse(os.environ.get("DATABASE_URL")), } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ … -
django subdomains error namespace does not exist
Trying to configure subdomains. ie. two.example.com default domain www.example.com but getting error "app_two is not a registered namespace" via {% url 'app_two:app-two-list' %} in base.html I've also tried {% host_url 'app-two-list' host 'two' %} but it redirects to just two and not two.example.com project urls.py urlpatterns = [ path("admin/", admin.site.urls), path("", include("app_one.urls", namespace="app_one")), ] app_one urls.py app_name = "app_one" urlpatterns = [ path("", views.home, name="home") ] app_two urls.py app_name = "app_two" urlpatterns = [ path("", AppTwoListView.as_view(), name="app-two-list"), path("new/", AppTwoCreateView.as_view(), name="app-two-create") ] project hosts.py host_patterns = [ host("www", settings.ROOT_URLCONF, name="www"), host( "two", include("app_two.urls", namespace="app_two"), name="two" ), ] project setting.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.sites", "django.contrib.redirects", "django_hosts", "app_one", "app_two", ] MIDDLEWARE = [ "django_hosts.middleware.HostsRequestMiddleware", ... "django_hosts.middleware.HostsResponseMiddleware", ] ROOT_URLCONF = "project.urls" ROOT_HOSTCONF = "project.hosts" DEFAULT_HOST = "www" SITE_ID = 1 projects base.html {% load static %} {% load hosts %} <nav> <a class="navbar-brand" href="{% url 'app_one:home' %}"> <img src="{% static 'app_one/svg/logo.svg' %}" alt="App One Logo" height="30"> </a> <a class="nav-link" style="color:#ffff" href="{% url 'app_two:app-two-list' %}">two</a> </nav> -
How do I run "python manage.py migrate" in a Visual Studio Django Web Project?
I am trying to run the default Django Web Project using Visual Studio 2022. I have reached this point: I open a Developer PowerShell window and run "python manage.py migrate". However, this fails because manage.py is in a sub-directory. So I run "python DjangoWebProject\manage.py migrate". This fails with "ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?" What should I do to get this working? -
Why do multiple test files cause Django issues when running in parallel?
I am using django 4.1 on windows. running my tests sequentially (python manage.py test) works fine. but when I run my tests in parallel (python manage.py test --parallel) I get the following error File "C:\Users\SomeGuy\miniconda3\envs\SomeProject\lib\multiprocessing\process.py", line 315, in _bootstrap self.run() File "C:\Users\SomeGuy\miniconda3\envs\SomeProject\lib\multiprocessing\process.py", line 108, in run self._target(*self._args, **self._kwargs) File "C:\Users\SomeGuy\miniconda3\envs\SomeProject\lib\multiprocessing\pool.py", line 109, in worker initializer(*initargs) File "C:\Users\SomeGuy\miniconda3\envs\SomeProject\lib\site-packages\django\test\runner.py", line 420, in _init_worker process_setup(*process_setup_args) TypeError: process_setup() missing 1 required positional argument: 'self' I created a project and made a folder underneath the main app folder for my tests called "tests" next to manage.py I have two test files test_losing_hair.py: from django.test import TestCase class WhyTest(TestCase): def test_counting_scheme(self): self.assertTrue(True) and test_rapidly.py: from django.test import TestCase class WontThisWorkTest(TestCase): def test_counting_scheme(self): self.assertTrue(True) What Am I doing wrong here? I've noticed running it in parallel works if I choose one file or the other, but both at the same time creates the error above.