Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best approach for integrating Django with an external API using RabbitMQ (Pub/Sub)?
I am developing a decoupled system consisting of two APIs that communicate through RabbitMQ. One API is entirely developed by me using Django, while the other is an external API managed by another developer (I can request changes but don’t have access to its code). The integration works as follows: My Django API publishes a message to Queue A in RabbitMQ. The external API consumes messages from Queue A, processes them, and publishes a response to Queue B. My Django API then consumes messages from Queue B. In this setup: My Django API acts as a publisher for Queue A and a consumer for Queue B. The external API acts as a consumer for Queue A and a publisher for Queue B. I want to validate whether this is a good approach and if there are alternative ways to achieve this communication efficiently. Additionally, if this approach is valid, how should I implement the consumer for Queue B in Django? Where should I place the RabbitMQ consumer so that it integrates well with Django’s ecosystem? How can I ensure it follows Django’s standard execution flow? Would it be best to run it as a separate process, a Django management command, … -
Django OpenTelemetry Logging Error: 'ProxyLogger' object has no attribute 'resource' Azure application insights
I am integrating OpenTelemetry logging into my Django application to send logs to Azure Application Insights, but I am encountering the following error: AttributeError: 'ProxyLogger' object has no attribute 'resource' The settings has following logger setup copilot/settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s' }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'standard', }, }, 'root': { 'handlers': ['console'], 'level': 'INFO', }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'INFO', 'propagate': True, }, 'copilot': { # Parent logger for your app 'handlers': ['console'], 'level': 'INFO', 'propagate': True, # Allows child loggers to inherit handlers }, }, } This is the copilot/otel_config.py # otel_config.py import os from django.conf import settings import logging from dotenv import load_dotenv from opentelemetry import trace from opentelemetry._logs import set_logger_provider from opentelemetry.sdk._logs import ( LoggerProvider, LoggingHandler, ) from opentelemetry.sdk._logs.export import BatchLogRecordProcessor from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.resources import Resource from opentelemetry.sdk.trace.export import BatchSpanProcessor from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter, AzureMonitorLogExporter from opentelemetry.instrumentation.django import DjangoInstrumentor from opentelemetry.instrumentation.logging import LoggingInstrumentor def setup_opentelemetry(): # Set up the tracer provider with resource attributes resource = Resource(attributes={ "service.name": "copilot", }) tracer_provider = TracerProvider() trace.set_tracer_provider(tracer_provider) connection_string = settings.APPLICATIONINSIGHTS_CONNECTION_STRING trace_exporter = AzureMonitorTraceExporter( connection_string = connection_string ) … -
In Django how to convert HTML input field values or csv values to Python list
<input type="hidden" name="allowed-extension[]" value="jpg" /> <input type="hidden" name="allowed-extension[]" value="jpeg" /> <input type="hidden" name="allowed-extension[]" value="png" /> or <input type="hidden" name="allowed-extensions" value="jpg,jpeg,png" /> I need to convert HTML input field values or CSV values to a Python list, like in the above scenarios. Kindly let me know. Thank you -
Creating a child table record, when a new parent table record is created
I have this model: from django.db import models from django.contrib.auth.models import User from django.templatetags.static import static from simple_history.models import HistoricalRecords from treebeard.mp_tree import MP_Node from . import constants from datetime import datetime class Profile(models. Model): # Managed fields user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) memberId = models.CharField(unique=True, max_length=15, null=False, blank=False, default=GenerateFA) avatar = models.ImageField(upload_to="static/MCARS/img/members", null=True, blank=True) birthday = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10, choices=constants.GENDER_CHOICES, null=True, blank=True) invited = models.BooleanField(default=False) registered = models.BooleanField(default=False) height = models.PositiveSmallIntegerField(null=True, blank=True) phone = models.CharField(max_length=32, null=True, blank=True) address = models.CharField(max_length=255, null=True, blank=True) number = models.CharField(max_length=32, null=True, blank=True) city = models.CharField(max_length=50, null=True, blank=True) zip = models.CharField(max_length=30, null=True, blank=True) @property def get_avatar(self): return self.avatar.url if self.avatar else static('static/MCARS/img/avatars/default.jpg') def save(self, **kwargs): if not self.pk: super(Profile, self).save(**kwargs) rank = Rank.objects.create(user=self, longrank='o1', shortrank='o1', branch='r') rank.save() else: super(Profile, self).save(**kwargs) def __str__(self): rank = Rank.objects.get(user=self.user.profile).get_longrank_display() return rank + " " + self.user.first_name + " " + self.user.last_name + "(" + self.memberId + ")" class Rank (models.Model): user = models.ForeignKey(Profile, related_name="Rank", on_delete=models.CASCADE) longrank = models.CharField(max_length=5, null=True, blank=True, choices=constants.long_rank) shortrank = models.CharField(max_length=5, null=True, blank=True, choices=constants.short_rank) branch = models.CharField(max_length=5, null=True, blank=True, choices=constants.branch) image = models.ImageField(upload_to="static/MCARS/img/ranks", null=True, blank=True) history = HistoricalRecords() def save(self, **kwargs): self.shortrank = self.longrank self.image = 'static/MCARS/img/ranks/' + self.branch[0] + '-' + self.longrank + … -
django create record under specific circumstances
I have this model: class CommandPositions(models.Model): command = models.ForeignKey(Command, related_name="Positions", on_delete=models.CASCADE) name = models.CharField(max_length=255, null=True, blank=True) responsibility = models.TextField(null=True, blank=True) def save(self, **kwargs): if not self.pk: super(CommandPositions, self).save(**kwargs) else: super(CommandPositions, self).save(**kwargs) I'm stuck on the self.pk. My assumption is self.pk is about the relationship between command and name. There can be multiple command lines with the same command, but different names. how can I check if this is the first time the inbound command is the first time this value is used, regardless of name value? Thanks! -
Django admin always redirected to static react app
I serve a static React app in Django like this: # In /my_django_project/urls.py urlpatterns = [ path('admin/', admin.site.urls), re_path(r"^(?P<path>.*)$", my_django_app.views.serve_react, {"document_root": settings.REACT_APP_BUILD_PATH})] # In /my_django_app/views.py from django.views.static import serve as static_serve def serve_react(request, path, document_root=None): path = posixpath.normpath(path).lstrip("/") fullpath = pathlib.Path(safe_join(document_root, path)) if fullpath.is_file(): return static_serve(request, path, document_root) else: return static_serve(request, "index.html", document_root) According to Django's documentation, the URLs are matched in the order they are declared in urlpatterns and stop at the first match. But if when I access http://127.0.0.1:8000/admin or http://127.0.0.1:8000/admin/, I always get redirected to my static React app homepage, despite the admin/ URL being first in the URL patterns (as if the ordering was not relevant). If I comment out the static_serve line, the admin page get served as expected. Why ? How to make the admin page served ? -
Django View Only Returns JSON Instead of Rendering Template
In my Django views.py, I have a function that is supposed to both render a website and return a JsonResponse. Normally, when I visit the URL, I expect to see the rendered website. However, instead of rendering the template, the only thing I see is the JSON response. def chatbot(request): if request.method == 'POST': message = request.POST.get('message') response = 'hi hi hi' print(message) return JsonResponse({'message': message, 'response':response}) return render(request, 'chatbot.html',{'response':response}) Web site output: web site output -
Image upload corruption with SeaweedFS S3 API
Problem Description I'm experiencing an issue where images uploaded through Django (using boto3) to SeaweedFS's S3 API are corrupted, while uploads through S3 Browser desktop app work correctly. The uploaded files are 55 bytes larger than the original and contain a Content-Encoding: aws-chunked header, making the images unopenable. Environment Setup Storage: SeaweedFS with S3 API Proxy: nginx (handling SSL) Framework: Django Storage Client: boto3 Upload Method: Using Django's storage backend with PrivateStorage Issue Details When uploading through S3 Browser desktop app: File size matches original Image opens correctly No corruption issues When uploading through Django/boto3: File size increases by 55 bytes Response includes Content-Encoding: aws-chunked Image becomes corrupted and unopenable First bytes contain unexpected data (100000) Last bytes end with .x-amz-checksum- Example of Corrupted File Original file size: 12345 bytes Uploaded file size: 12400 bytes (+55 bytes) First bytes: 100000... Last bytes: ...x-amz-checksum-crc32:SJJ2UA== Attempted Solutions Tried different upload methods: # Method 1: Using ContentFile storage.save(path, ContentFile(file_content)) # Method 2: Using Django File object storage.save(path, File(file)) # Method 3: Direct boto3 upload client.upload_fileobj(f, bucket_name, path) Questions Is this a known issue with SeaweedFS's S3 API implementation? Is there a way to disable the aws-chunked encoding in boto3? Are there specific headers … -
How to avoid redundant manual assignment of environment variables in Django settings?
In my Django project, I store configuration variables in a .env file for security and flexibility. However, every time I introduce a new environment variable, I have to define it in two places: .env and settings.py. As the project grows and the number of environment variables increases, settings.py gets cluttered with redundant redefinitions of what’s already in .env. Is there a way to automatically load all .env variables into Django’s settings without manually reassigning each one? Ideally, I want any new variable added to .env to be instantly available from settings module without extra code. What I can think of is something like: from dotenv import dotenv_values env_variables = dotenv_values(".envs") globals().update(env_variables) Or even something a little bit better to handle values of type list. for key, value in env_variables.items(): globals()[key] = value.split(",") if "," in value else value # Ensure ALLOWED_HOSTS is always a list ALLOWED_HOSTS = ALLOWED_HOSTS if isinstance(ALLOWED_HOSTS, list) else [ALLOWED_HOSTS] But I do not like to mess around with globals(). -
Django app performance issues with cloud PostgreSQL & Redis
I recently deployed my Django app on Railway, where I set up PostgreSQL and Redis and connected them to my project. However, I’ve noticed a drastic slowdown in query and cache performance compared to running locally—by several orders of magnitude. For example, one of my views executes queries in 2.58ms on my local database but takes 7411.42ms on Railway. Similarly, the same view’s cache time is 24.14ms on local Redis but 2122.14ms on Railway. I expected some performance drop when moving to a cloud-hosted setup, but this level of slowdown seems excessive. Initially, I suspected an incorrect connection setup on Railway, but after testing with Redis Cloud, the performance remained similar to Railway’s Redis. I haven’t tested another cloud database yet. Does anyone have insights into what might be causing such a drastic difference? Here’s my database setup in settings.py: DATABASES = { 'default': dj_database_url.config(default=os.getenv('DATABASE_URL')) } and cache setup: SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default" SELECT2_CACHE_BACKEND = "select2" CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": REDIS_URL, "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } }, 'select2': { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": REDIS_URL, "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } Any help would be greatly appreciated! Thanks! -
How to fix "SignUpView is missing a QuerySet"
In my django web app i am trying to build a Newspaper app, in my homepage when i click on SIGN UP Button i get an error "ImproperlyConfigured at /accounts/signup/", I didnt figure out where is the problem. forms.py: from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): #Creation of CustomUser class Meta: model = CustomUser fields = UserCreationForm.Meta.fields + ("age",) class CustomUserChangeForm(UserChangeForm): #Modifying existing users class Meta: model = CustomUser fields = UserChangeForm.Meta.fields and models.py: from django.contrib.auth.models import AbstractUser #username, pw1, pw2 from django.db import models class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) urls.py: from django.urls import path from .views import SignUpView #Accounts/urls.py : Handles only registrations URLs!! urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), ] and views.py: from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import CustomUserCreationForm class SignUpView(CreateView): from_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' signup.html: {% extends 'base.html' %} {% block title %}Sign Up{% endblock title %} {% block content %} <h2>Sign Up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign Up</button> </form> {% endblock content %} I tried to change fields in forms.py with: fields = ( "username", "email", "age",) but nothing to be mention -
Why does my code execute despite error message?
I have Created a react app the allows me to enter form data and send it to my django backend. I also have created a delete view that will trigger when the request containe the "DELETE" phrase. I noticed that after sending a request which included the line of code below, I received a PUT 400 error on my browser as well as in the django console. However, the delete request was still executed. Kindly assist as i am confused about why the request still executed tho i got an error. formData.append("drivers_license", "DELETE"); -
How to properly connect PostgreSQL with Django?
I'm working on a Django project and using PostgreSQL as my database. I updated my settings.py as follows: ** DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'myuser', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '5432', } } ** However, when I run python manage.py migrate, I get the following error: django.db.utils.OperationalError: could not connect to server: Connection refused I have PostgreSQL installed and running. I also verified that my credentials are correct. What could be the issue? -
Django ManyToMany Relationship Not Returning First Available Size in View
I am working on a Django e-commerce project where a product can have multiple sizes. However, I am facing an issue where, if no size is explicitly selected by the user, the system should automatically take the first available size of the product. Currently, it always returns "No Size", even though sizes exist for the product. Models: Here is my Product model: class Product(models.Model): pid = ShortUUIDField(length=10, max_length=100, prefix="prd", alphabet="abcdef") title = models.CharField(max_length=100, default="Apple") image = models.ImageField(upload_to=user_directory_path, default="product.jpg") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) size = models.ManyToManyField("Size", blank=True) def get_product_price_by_size(self): """Returns price based on the first available size if none is selected""" first_size = self.size.first() # Get the first available size if first_size: return self.price + first_size.price # Assuming 'price' exists in Size model return self.price # Default to base price if no size exists def __str__(self): return self.title class Size(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) def __str__(self): return self.name View Handling "Add to Cart" (add_to_cart_search): When a user clicks "Add to Cart," I want to fetch the product's size. If no size is explicitly selected, the first available size should be assigned automatically. def add_to_cart_search(request): if request.GET.get('buy_now'): return redirect('core:payment_getway') product_id = request.GET.get('pid') … -
Trouble setting PORT in Django/Heroku Procfile using Waitress
I'm trying to deploy my Django application with Heroku (on Windows), and using Waitress (because Gunicorn no longer runs on Windows??). When I hard coded the PORT number, I was able to run it fine. When I try to define PORT in the Procfile as an environment variable Procfile: web: waitress-serve --port=$PORT [projectname].wsgi:application .env WEB_CONCURRENCY=2 PORT=$PORT settings.py import environ from environ import Env ... PORT = env('PORT') running "heroku local" produces ValueError: invalid literal for int() with base 10: '$PORT' I keep seeing mention that "$PORT" is not appropriate for Windows. However I can't figure out what I'm missing. I've seen suggestions that "%PORT%" would work for Windows, but I haven't had success. If there is a Windows friendly syntax, would I need to use it in both .env and Procfile? -
uploading multiple images in Django admin
I have a category and for each category I want to add multiple images but whatever I do, I have just one upload file but I want to have multiple. In my Django project I have this class: in my model file: class SalonSampleImages(models.Model): service = models.ForeignKey(Salon, on_delete=models.CASCADE) Category = models.ForeignKey( ServiceCategory, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="the main service", default=1 ) image = models.ImageField(upload_to='salon_images/', verbose_name="images") def __str__(self): return f"images" class Meta: verbose_name = "picture" verbose_name_plural = "pictures" in my admin file: class SalonSampleImagesInLineFormSet(forms.BaseInlineFormSet): def clean(self): super().clean() total_images = len([form for form in self.forms if form.cleaned_data and not form.cleaned_data.get('DELETE', False)]) if total_images < 3: raise ValidationError("you must all at least 3 images") if total_images > 10: raise ValidationError("you cannot add more than 10 images") class SalonSampleImagesInLine(admin.TabularInline): model = SalonSampleImages formset = SalonSampleImagesInLineFormSet extra = 1 and I registered all then I created a model file: class MultiFileInput(forms.ClearableFileInput): allow_multiple_selected = True def __init__(self, attrs=None): if attrs is None: attrs = {} attrs.setdefault('multiple', 'multiple') super().__init__(attrs=attrs) def value_from_datadict(self, data, files, name): return files.getlist(name) class MultiImageUploadForm(forms.Form): category = forms.ModelChoiceField( queryset=ServiceCategory.objects.all(), label="choose category" ) images = forms.FileField( widget=MultiFileInput(), label="upload pictures" ) then I created a html file: {% extends "admin/base_site.html" %} {% block content %} <h1>{{ title … -
Django app works locally but shows "Unhandled Exception" on PythonAnywhere (Logs available)
Link to the youtube video: https://youtu.be/iJrUiem10iI I have developed a Django application that includes features like downloading YouTube videos (using yt-dlp) and potentially converting file formats. The Problem: The application runs perfectly fine on my local machine using python manage.py runserver. I can access the views, for example at http://127.0.0.1:8000/converter/, and the functionality works as expected. However, after deploying the application to PythonAnywhere (using the free tier), I encounter an error. When I try to access my site at https://kristjan.pythonanywhere.com/ or the specific app URL https://kristjan.pythonanywhere.com/converter/, I get a generic PythonAnywhere error page stating: Something went wrong :-( Something went wrong while trying to load this website; please try again later. Error code: Unhandled Exception Self-note: The error page provides links to logs, which should contain the specific traceback. What I've Done and Checked: Local Server: Confirmed the app works correctly locally via runserver. The URL http://127.0.0.1:8000/converter/ loads the correct index.html template. Virtual Environment: Created a virtualenv on PythonAnywhere at /home/Kristjan/.virtualenvs/djangoappvirtualenv. I activated this virtualenv and installed all necessary packages (Django, yt-dlp, etc., matching my local environment as closely as possible) using pip install -r requirements.txt (or individually) within a PythonAnywhere console. Database Setup: Configured the default DATABASES setting in … -
password reset email in django
ive been following along with corey schafers django blog app tutorial on youtube, and up until episode 12 everything was fine and perfect. But i cant make the password reset email work no matter what i try i have all the code exactly how he does and i think what it might be is google app password but i have no idea how to link it to the application. if anyone can help it would be much appreciated! path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') -
Why do filters affect the result of StringAgg?
I'm using StringAgg and order as follows: # Get order column & annotate with list of credits if request.POST.get('order[0][name]'): order = request.POST['order[0][name]'] if order == 'credits_primary': releases = releases.annotate(credits_primary=StringAgg( 'credits__entity__name', delimiter=', ', filter=Q(credits__type='primary'), ordering='credits__id' )) elif order == 'credits_secondary': releases = releases.annotate(credits_secondary=StringAgg( 'credits__entity__name', delimiter=', ', filter=Q(credits__type='secondary'), ordering='credits__id' )) else: order = 'title' # Order releases if request.POST.get('order[0][dir]') == 'desc': releases = releases.order_by(F(order).desc(nulls_last=True), 'title') else: releases = releases.order_by(F(order).asc(nulls_last=True), 'title') for release in releases: try: print(release.credits_primary) except: pass try: print(release.credits_secondary) except: pass This in itself works exactly as expected: the ordering is what I expect, and print returns the values I expect. However, when I apply filters before this, it starts behaving strangely. Namely, sometimes it's fine and still works as expected, sometimes each credits__entity__name is repeated a random number of times, sometimes the annotation just returns None even though there are values. I can't figure out a pattern here. Below are the filters I'm applying, note that exclude as far as I can tell does not cause this problem: if request.POST.get('entity'): releases = Release.objects.filter(credits__entity=request.POST['entity']) else: releases = Release.objects.all() records_total = releases.count() # Filter by type if request.POST.get('type'): query = Q() for type in loads(request.POST['type']): if type in Release.TYPES_P_TO_S: query.add(Q(type=Release.TYPES_P_TO_S[type]), Q.OR) releases … -
Why is the data-tags attribute not preserved in my Django form widget? autoComplete DAL Select2
I'm using a CharField with a custom widget (ListSelect2) from the django-autocomplete-light library. I have a set of data-* attributes, including data-tags, that I want to be passed to the HTML output, but it doesn't seem like the data-tags attribute is being preserved or rendered correctly in the final after form is saved. industry_type = forms.CharField( widget=autocomplete.ListSelect2( url='/career-listings/industry-autocomplete/', attrs={ 'class': 'w-full px-4 py-2 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition duration-200', 'data-placeholder': 'Industry', 'data-minimum-input-length': 1, 'data-theme': 'tailwindcss-3', 'data-tags': 'true', # The attribute I'm trying to preserve 'id': 'id_industry_type', }, forward=['name'], ), required=True, ) What happens instead: The data-tags attribute does not appear in the HTML after form is saved. The field Things I've tried: I added data-tags to the attrs dictionary of the widget. I ensured that the widget is being properly rendered in the template. The data only data-tags is not preserved on form is submitted. -
Getting list of distinct ManyToManyField objects
Given these models: class Format(models.Model): name = models.CharField(unique=True) # More fields... class Release(models.Model): formats = models.ManyToManyField(Format, blank=True) # More fields... When I have a queryset of Releases (e.g. through releases = Release.objects.filter(foo='bar')), how do I get a list of the formats in that queryset, as objects and distinct? Neither of the following achieve this: # produces a list of dicts with IDs, not distinct e.g. [ { 'formats': 1 }, { 'formats': 2 }, { 'formats': 1 } ]: formats = releases.values('formats') # produces a list of IDs, not distinct, e.g. [ 1, 2, 1 ]: formats = releases.aggregate(arr=ArrayAgg('platforms'))['arr'] The only way I can think of is manually creating a list by looping through the IDs, checking if it already exists in the list, and if not adding it with formats.append(Format.objects.get(id=the_id)), but I would really like to avoid doing that, if possible. -
(fields.E331) Field specifies a many-to-many relation through model, which has not been installed
When I run makemigrations I get the error teams.Team.members: (fields.E331) Field specifies a many-to-many relation through model 'TeamMember', which has not been installed. from django.db import models from django.conf import settings from common import TimestampMixin from users.models import User class Team(models.Model, TimestampMixin): name = models.CharField(max_length=100) owner = models.ForeignKey( User, related_name='owned_teams', on_delete=models.CASCADE ) members = models.ManyToManyField( User, through='TeamMember', related_name='teams' ) def __str__(self): return self.name class TeamMember(models.Model, TimestampMixin): user = models.ForeignKey( User, on_delete=models.CASCADE ) team = models.ForeignKey( Team, on_delete=models.CASCADE ) def __str__(self): return f"{self.user} in {self.team}" I don't get why it's happening because the 'teams' app is installed and both Team and TeamMember is in the same file. Any ideas? -
Getting error message running Django server
I’m not able to run python manage.py runserver. I was able to run python manage.py migrate successfully. I even changed ASGI_APPLICATION = "MyProject.asgi.application" to ASGI_APPLICATION = "routing.application" which didn’t work. Here is the error I get show_sunset_warning() System check identified no issues (0 silenced). March 28, 2025 - 17:51:56 Django version 5.1.7, using settings 'MyProject.settings' Starting ASGI/Daphne version 4.1.2 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Exception in thread django-main-thread: Traceback (most recent call last): File "/home/corey-james/Arborhub/MyProject/venv/lib/python3.12/site-packages/daphne/management/commands/runserver.py", line 29, in get_default_application module = importlib.import_module(path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 995, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "/home/corey-james/Arborhub/MyProject/MyProject/asgi.py", line 12, in <module> import arborchat.routing File "/home/corey-james/Arborhub/MyProject/arborchat/routing.py", line 3, in <module> from . import consumers File "/home/corey-james/Arborhub/MyProject/arborchat/consumers.py", line 2, in <module> from channels.exceptions import StopConsumer ImportError: cannot import name 'StopConsumer' from 'channels.exceptions' (/home/corey-james/Arborhub/MyProject/venv/lib/python3.12/site-packages/channels/exceptions.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.12/threading.py", line 1075, in _bootstrap_inner self.run() File "/usr/lib/python3.12/threading.py", line … -
why does the terminal say PATCH but no change in database
in my webpage, i update the request details to approve or reject. but it does not change in the status and still shows pending. the problem is, in my terminal it says PATCH so I though that means change and the database has been changed. but when I run my SQL shell, it still shows pending . what would the problem be? this is my handlestatusupdate code in the frontend: **const handleStatusUpdate = async (newStatus: 'approved' | 'rejected') => { if (!selectedRequest?.id) return; try { const response = await fetch(`${API_URL}/requests/${selectedRequest.id}/`, { method: 'PATCH', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ status: newStatus }), }); if (!response.ok) { throw new Error('Failed to update request status'); } const updatedRequest = await response.json(); setRequests(requests.map(req => req.id === selectedRequest.id ? updatedRequest : req )); setShowModal(false); } catch (err: any) { setError(err.message || 'Failed to update status'); } }; ** what other code would i need to share? the backend? -
How to create django site variables (NOT constants)?
I need to add a variable to Django. Important detail: I need a variable, not a constant, so simply adding it to settings.py is not an option. It is highly desirable to be able to change its value from the site admin panel. What is the most Django way to do this?