Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
502 Gateway error - ngnix on django application
I have an already running sites one is the main (user-facing) and one staging website. They're in django and have been running for years, but during one of my builds i started encountering a "502 bad gateway error" when I clicked on some of the pages. The changes I made were not towards any of the ngnix configs or even server changes. Before it used to run smoothly. However this issue remains on Chrome (works fine on safari) and when i clear cache on chrome it starts to work again for around 10 minutes and then something or the other gives bad gateway. Also if i copy paste the link into a different chrome profile it'll probably work and vice versa. (the different profiles on chrome don't have any different extension or different setting..). It honestly seems random and i don't know how to solve this at all. Any help/ tips would be appreciated -
Microsoft Graph API, cant retrieve profile picture with django
I'm having the issue that requesting the photo from the Microsoft Graph API does not retrieve the photo and actually returns a 404 error. xff/xd8/xff/xe0/x00/x10JFIF/x00/x01/x01/x01/x00%60/x00%60/x00/x00/xff/xdb/x00C/x00/x08/x06/x06/x07/x06/x05/x08/x07/x07/x07/t/t/x08/n/x0c/x14/r/x0c/x0b/x0b/x0c/x19/x12/x13/x0f/x14/x1d/x1a/x1f/x1e/x1d/x1a/x1c/x1c%20$./'%20%22, i get this is the base64 decoded jpeg, however i cant figure out how to use it to actually display an image in a html page. Here is the code in my views that is creating the request, which is in my initialize context view: def initialize_context(request): ## non relevant code ## graph_photo_endpoint = 'https://graph.microsoft.com/beta/me/photo/$value' headers = {'Authorization': 'Bearer ' + token} photo_response = requests.get(graph_photo_endpoint, headers=headers) if photo_response.status_code == 200: context['photo_data'] = photo_response.content photo_response.headers['Content-Type'] = 'image/jpeg' ## non relevant code ## return context Which is retrieved by my view that needs to load the photo, which the user needs to be signed in for to access: @azure_ad_login_required def profile(request): context = initialize_context(request) return render(request, 'profile.html', context) Here is the html code to define the photo: <img class="profile_pic" src="{{ photo_data }}" alt="Profile Picture" style="width:100%"> And this is what my graph_helper looks like: import requests import base64 from requests_oauthlib import OAuth2Session graph_url = 'https://graph.microsoft.com/v1.0' def get_user(token): # Send GET request to retrieve user information from Microsoft Graph API user = requests.get('{0}/me'.format(graph_url), headers={'Authorization': 'Bearer {0}'.format(token)}, params={'$select': 'displayName,mail,mailboxSettings,userPrincipalName,givenName,companyName,surName,jobTitle'}) user.headers['Content-Type'] … -
What does confirm_email() method do in django user model
I am writing email confirmation code for user signup in a django project. I see that each instance of user model has a confirm_email() method. what does it do and how to use it? Is it used to send a confirmation email? Here is an example object. >>> CU = CustomUser.objects.all() >>> dir(CU[0]) ['DoesNotExist', 'EMAIL_FIELD', 'Meta', 'MultipleObjectsReturned', 'REQUIRED_FIELDS', 'USERNAME_FIELD', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_check_column_name_clashes', '_check_constraints', '_check_default_pk', '_check_field_name_clashes', '_check_fields', '_check_id_field', '_check_index_together', '_check_indexes', '_check_local_fields', '_check_long_column_names', '_check_m2m_through_same_relationship', '_check_managers', '_check_model', '_check_model_name_db_lookup_clashes', '_check_ordering', '_check_property_name_related_field_accessor_clashes', '_check_single_primary_key', '_check_swappable', '_check_unique_together', '_do_insert', '_do_update', '_get_FIELD_display', '_get_expr_references', '_get_next_or_previous_by_FIELD', '_get_next_or_previous_in_order', '_get_pk_val', '_get_unique_checks', '_legacy_get_session_auth_hash', '_meta', '_password', '_perform_date_checks', '_perform_unique_checks', '_prepare_related_fields_for_save', '_save_parents', '_save_table', '_set_pk_val', '_state', 'check', 'check_password', 'clean', 'clean_fields', 'confirm_email', 'date_error_message', 'date_joined', 'delete', 'email', 'email_user', 'first_name', 'from_db', 'full_clean', 'get_all_permissions', 'get_deferred_fields', 'get_email_field_name', 'get_full_name', 'get_group_permissions', 'get_next_by_date_joined', 'get_previous_by_date_joined', 'get_session_auth_hash', 'get_short_name', 'get_user_permissions', 'get_username', 'groups', 'has_module_perms', 'has_perm', 'has_perms', 'has_usable_password', 'id', 'is_active', 'is_anonymous', 'is_authenticated', 'is_staff', 'is_superuser', 'last_login', 'last_name', 'ledgerentry_set', 'logentry_set', 'natural_key', 'normalize_username', 'objects', 'password', 'pk', 'prepare_database_save', 'refresh_from_db', 'save', 'save_base', 'serializable_value', 'set_password', 'set_unusable_password', 'unique_error_message', 'user_permissions', 'username', 'username_validator', 'validate_unique'] >>> I tried running it in the django shell and it did nothing >>> CU[0].confirm_email() >>> -
Format radio button like button in for loop
I am working on a school attendance system. Using radio buttons, teachers can mark students as one of the attendance types (pulled from the database). I would like to have my radio buttons formatted to look like buttons, but when I do so, I can only make a selection for the first student. Below is my embedded stylesheet: <style type="text/css"> .radio-button { margin: 10px;} .radio-button input[type="radio"] { opacity: 0; position: fixed; width: 0; } .radio-button label { display: inline-block; background-color: #ddd; padding: 10px 20px; font-family: sans-serif, Arial; font-size: 16px; border: 2px solid #444; border-radius: 4px; } .radio-button label:hover { background-color: #dfd; } .radio-button input[type="radio"]:focus + label { border: 2px dashed #444; } .radio-button input[type="radio"]:checked + label { background-color: #bfb; border-color: #4c4; } </style> Below is my code for the radio buttons: {% for student in list_of_students %} <tr> <td>{{student}}</td> <td> <div class="radio-button"> {% for attendanceType in list_of_attendanceTypes %} <input type="radio" name='{{student.ssystudentid}}_attendancetype' id={{attendanceType}} value={{attendanceType.attendancetypeid}}> <label for={{attendanceType}}> {{attendanceType}}</label> {% endfor %} </div> </td> I moved around the tags because I thought that they were the root of the problem, but it did not seem to work. Below is an image of how it looks right now: Any advice would be appreciated. -
I got error when ı set up docker with django
I want to set up docker container in my django app. But I failed when ı building docker. Can you help me or share some resources? how can fix problem. I used docker-compose build. Most probably requirements.txt not work well. I applied some logic but they did not work. Dockerfile FROM python:3.10-slim ENV PYTHONUNBUFFERED=1 ENV PYTHONDONTWRITEBYTECODE 1 RUN apt-get update RUN apt-get install python3-dev build-essential -y #pip requirements RUN pip install --upgrade pip RUN pip install virtualenv && python -m virtualenv venv ENV PATH="/venv/bin:$PATH" RUN pip install django COPY ./requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . /srv/app WORKDIR /srv/app docker-compose.yml version: '3.8' services: app: build: context: . dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:7000 log => [app 7/10] COPY ./requirements.txt . 0.1s => ERROR [app 8/10] RUN pip install --no-cache-dir -r requirements.txt 37.6s ------ > [app 8/10] RUN pip install --no-cache-dir -r requirements.txt: 3.098 Requirement already satisfied: asgiref==3.7.2 in /venv/lib/python3.10/site-packages (from -r requirements.txt (line 1)) (3.7.2) 3.099 Requirement already satisfied: Django==4.2.3 in /venv/lib/python3.10/site-packages (from -r requirements.txt (line 2)) (4.2.3) 3.442 Collecting django-environ==0.10.0 (from -r requirements.txt (line 3)) 3.785 Downloading django_environ-0.10.0-py2.py3-none-any.whl (19 kB) 4.632 Collecting djangorestframework==3.14.0 (from -r requirements.txt (line 4)) 4.747 Downloading djangorestframework-3.14.0-py3-none-any.whl (1.1 MB) 27.98 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ … -
In Wagtail 4.0, How do I query for revisions whose pages are not live?
I am upgrading some code from wagtail 3.0 to wagtail 4.0. My code has one problem query in it that I can not figure out how to fix. In the old code, the query looks like this: PageRevision.objects.filter(approved_go_live_at__isnull=False, page__live=False) With PageRevision being deprecated, I updated it to the following Revision.page_revisions.filter(approved_go_live_at__isnull=False, page__live=False) This resulted in an error, caused by a type mismatch in sql: ProgrammingError: operator does not exist: character varying = integer LINE 1: ...core_page" ON ("wagtailcore_revision"."object_id" = "wagtail... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. After reexamining the docs I changed it to: Revision.page_revisions.filter(approved_go_live_at__isnull=False, content_object__live=False) This just got a different error: FieldError: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. Now I am confused, because content_object is a field directly on Revision, so it shouldn't be a 'reverse` relation. Looking at Page, it seems like it does have a GenericRelation, (with related_query_name=page) pointing back to Revision. But that's what I tried to use the first time and got a sql type mismatch. The documentation talks about type casting, but … -
Django - what happens when re_path finds a match but hands off to an "include"d urls.py file?
I'm working on a Django site, but fairly new to Django and Python. I have a situation where there is a "higher level" urls.py file using re_path to do regex matching for subdirectories, and then include to pass off each subdirectory to its own urls.py file. Something like this: urlpatterns = [ re_path(r'^SUBDIR1/.*$(?i)', include('subdir1.urls'), re_path(r'^SUBDIR2/.*$(?i)', include('subdir2.urls'), re_path(r'^SUBDIR3/.*$(?i)', include('subdir3.urls') ] And then each of the subdirectories' urls.py basically has only one path/view hooked up: urlpatterns = [ path('', views.main_view, name='index') ] In one of them I'm trying to set up a second URL to go to a different view: urlpatterns = [ path('', views.main_view, name='index'), path('my_new_view/<parameter>/', views.my_new_view, name='my_new_view') ] But I can't seem to get my view called, every time I try a URL that should match my new pattern, I just get the main view again. I'm guessing I don't quite understand what's happening when re_path finds a match and hands off to the included urls.py file. I get that the regexes are basically saying "match the subdirectory name, a forward slash, and then any number of characters afterwards", but what happens to that "matched" string? Does the full match get passed to the include file for further processing, or … -
" 'AnonymousUser' object has no attribute 'Attribute_name' " while perfroming test
The test class : class UpadtePadlockTest(TestCase): username = "testusername" email = "testuser@name.com" username2 = "testusername2" email2 = "testuser2@name.com" def test_update_padlock(self): User = get_user_model() user1 = User.objects.create_user( self.username, self.email , ) user2 = User.objects.create_user( self.username2, self.email2 , user_locked_with=user1 ) user1.user_locked_with=user2 new_padlock= PadLock.objects.create(start_date=datetime.date(datetime.today()),motto_field="Jodo is my motto",creator=user1,modifier=user2) response = self.client.post( reverse('edit_padlock'), {'start_date':datetime.date(datetime.today()), 'motto_field':"Jodo is not my motto"}) self.assertEqual(response.status_code,302) new_padlock.refresh_from_db() self.assertEqual(new_padlock.motto_field,"Jodo is not my motto") The view that is causing the problem def edit_padlock(request): # dictionary for initial data with # field names as keys context ={} user = request.user # this is the attr that the AnonymousUser is lacking user2 = CustomUser.objects.get(username= user.user_locked_with) # fetch the object related to passed id try: obj = PadLock.objects.get(modifier=request.user) except Exception: obj = PadLock.objects.get(creator=request.user) # pass the object as instance in form form = PadLockForm(request.POST or None, instance = obj) # save the data from the form and # redirect to detail_view if form.is_valid(): user.lock_published = True user2.lock_published = True user.save() user2.save() form.save() try: padlock = PadLock.objects.get(modifier=request.user) padlock.active_state = True padlock.save() except: padlock = PadLock.objects.get(creator=request.user) padlock.active_state = True padlock.save() return HttpResponseRedirect("/") # add form dictionary to context context["form"] = form return render(request, "edit_padlock.html", context) My Custom User : class CustomUser(AbstractUser): age= models.PositiveBigIntegerField(null=True,blank=True) lock_status = models.BooleanField(default=False) lock_count = … -
Django/drf doesn't work correct with uvicorn for tests
When I'm starting Django server in docker via uvicorn used by the next command: uvicorn --host=0.0.0.0 --port=8000 --reload configs.asgi:application I get an error like this: raise AppRegistryNotReady("Apps aren't loaded yet.") instalike-backend-web-1 | django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. And when I'm adding the next lines into settings.py: import django django.setup() Server work correct, but I want to run some tests of API and when I'm trying to run it, I'm receiving an error like this: ImportError while loading conftest '/app/conftest.py'. conftest.py:5: in <module> from users.tests import factories users/tests/factories.py:4: in <module> from users import models users/models/__init__.py:2: in <module> from .instagram_client import * # noqa users/models/instagram_client.py:6: in <module> class InstagramClient(models.Model): /usr/local/lib/python3.10/site-packages/django/db/models/base.py:134: in __new__ raise RuntimeError( E RuntimeError: Model class users.models.instagram_client.InstagramClient doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. users app in the INSTALLED_APPS list already. I was trying to resolve this problem the next way: To each model I added: class Meta: app_label = "users" After all, Django raised the same error(Import Error) but for ContentType model. Maybe someone know the solution of this problem -
Adding a new field to a existing model in django
I created a model in django. Migrated, then forgot I'd missed a field. I've added that field in (author) and now I am getting an error. I've tried make migrations again but I get this... gitpod /workspace/bookends (main) $ python3 manage.py makemigrations books You are trying to add a non-nullable field 'author' to books without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py Select an option: When I run the server in admin then click on books I get this error message. enter image description here This is my model code enter image description here This is my admin.py code enter image description here -
How to override default error messages in a django.forms subclass? - django 4.2.3
I am in a spanish language country, so I need to show messages in spanish, can't use defaults error messages. I am making tests, so I create a django.forms subclass with 1 char field, set it to required, set a min and max length. Used the error_messages parameter to set errors in spanish but still showing default messages. I don't know what am I doing wrong. Data is saved correctly the only problem is the error messages. forms.py from django import forms class CreateNewList(forms.Form): nombre = forms.CharField(label="Nombre", max_length=200, min_length=3, required=True, error_messages = { 'required': "El campo nombre es requerido", 'min_length': "El campo nombre debe ser minimo de 3 caracteres", 'max_length': "El campo nombre debe ser menor a 200 caracteres" }) views.py def crear(response): form = CreateNewList(response.POST or None) if response.method == "POST": if form.is_valid(): n = form.cleaned_data["nombre"] t = ToDoList(nombre=n) t.save() return render(response,"main/crear.html", {"form": form}) With and empty input (https://i.stack.imgur.com/DIIsm.png) Any help will be very appreciated. -
Is there a way to paginate Django's admin page that uses the django-nested-admin lib?
I have an admin page using NedstedStackedInLine, and the problem is that in the inside model, i have to many occurrences of the secondary model. Is there a way to paginate the inside models to not cause 502 error when the users tryng to access the page in a production scenario. Running localy the page is loaded, but with many seconds because of the large amount of occurences? Here is the code to ilustrate the problem. class CityInlineAdmin(NestedStackedInline): model = City class NestedStateAdmin(NestedStackedInline): model = State inlines = (CityInlineAdmin,) class CountryAdmin(NestedModelAdmin): inlines = (NestedStateAdmin,) I have already tried the django-admin-inline-paginator, but appears that this lib does not suport the Nested case. -
Why do I get response of an API request handled by an (exited) gunicorn worker?
Gunicorn config (only for testing): workers = 1 max_requests = 2 timeout = 30 graceful timeout = 1 (all other unspecified/default) Log events: FIRST REQUEST: [2023-07-25 16:01:29 +0000] [9485] [DEBUG] [pre_request] POST <API> - worker pid **9485**|ppid 29517|age 3|nr 0|max_requests 2|alive True|nr_pre 1|nr_post 0|sub_p_count 0 RESPONSE OF FIRST REQUEST: [2023-07-25 16:01:44 +0000] [9485] [DEBUG] [post_request] POST <API> - worker pid **9485**|ppid 29517|age 3|nr 1|max_requests 2|alive True|nr_pre 1|nr_post 1|sub_p_count 0 SECOND REQUEST: [2023-07-25 16:01:51 +0000] [9485] [DEBUG] [pre_request] POST <API> - worker pid **9485**|ppid 29517|age 3|nr 1|max_requests 2|alive True|nr_pre 2|nr_post 1|sub_p_count 0 WORKER EXIT: [2023-07-25 16:01:51 +0000] [9485] [INFO] Autorestarting worker after current request. (graceful timeout of 1s) [2023-07-25 16:01:53 +0000] [9485] [INFO] Worker exiting (pid: **9485**) [2023-07-25 16:01:53 +0000] [9485] [DEBUG] Worker exited RESPONSE OF SECOND REQUEST: [2023-07-25 16:02:04 +0000] [9485] [DEBUG] [post_request] POST <API> - worker pid **9485**|ppid 29517|age 3|nr 2|max_requests 2|alive False|nr_pre 2|nr_post 2|sub_p_count 0 Unable to figure out if it is the expected behavior? -
Kafka Producer not producing through gunicorn and supervisor
I'm facing an odd situation because i can't seem to make my Kafka Producer work through my normal application flow. So in my `settings.py` file I create a global producer by calling this function: def init_producer(broker_url, delivery_timeout, retry_interval): try: return Producer( { "bootstrap.servers": broker_url, "delivery.timeout.ms": delivery_timeout, "request.timeout.ms": retry_interval, } ) except Exception as exception: logger.error( f"Couldn't connect to broker {broker_url} because of exception {exception}" ) and then I do this in `settings` file : producer = init_producer( KAFKA_BROKER_URL, KAFKA_DELIVERY_TIMEOUT, KAFKA_RETRY_INTERVAL ) After that I then have a `post_save` signal in my model that runs the producing message when an instance of my model is saved in the database: @receiver(post_save, sender=MyModel) def update_report(sender, instance, **kwargs): produce_message(instance.id) Then in my `produce_message` file I do the following: def produce_message(instance_id): try: data = json.dumps( { "id": instance_id, "client": CLIENT, "database": "NAME", } ) producer.produce( KAFKA_REPORT_TOPIC, data.encode("utf-8"), on_delivery=report_transaction_handler, ) producer.poll(1) except Exception as error: logger.log( "MONITORING", f"Error {error} on producing message for Instance {instance_id}", ) My handler function does the following: def report_model_handler(err, msg): """Called once for each message produced to indicate delivery result. Triggered by poll() or flush().""" if err is not None: value = simplejson.loads(msg.value().decode()) logger.log( "MONITORING", f"Couldn't produce message {msg.value()} to topic … -
Django Celery and Celery Beat Daemon Documentation
I am working on deploying a django app with celery/celery beat to production. I can run everything just fine with celery running as a daemon with systemctl after following the documentation: https://docs.celeryq.dev/en/stable/userguide/daemonizing.html#example-django-configuration. But the documentation is a bit confusing...do celery and celery beat need to be setup as a service with systemctl if you are using django? Or is the documentation showing that you need to configure both the service and django as it shows? -
i am using postgresql shell (this file and directory is not found) help please?
You are now connected to database "test" as user "postgres". test=# \i C:/Users/ANUJ MISHRA/Downloads/human.sql C:/Users/ANUJ: No such file or directory i am feeling very tired to solve this problem, i expecting my problem will solve here -
Django adding and showing favorites
I want the logged in user to click the favorite me button and it adds the food item to the users dashboard. Here's the model class Favorite(models.Model): consumable_id = models.ForeignKey(Consumable, on_delete=models.CASCADE) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.name Here's the template for favorite me <div class="fav-me"> <hr /> <button id="fav-btn">Favorite Me</button> </div> Here's the template for user dashboard <div class="dash-header"> <h2>Your favorite items</h2> <div class="fav-item"> {% if favorites %} {% for favorite in favorites %} <h4>Name:{{ cunsumable.name }}</h4> <p>${{ consumable.price }}</p> <button>X</button> {% endfor %} {% else %} <p>You don't have any favorites</p> {% endif %} </div> </div> Here's my views def dashboard(request, consumable_id): fav_consumables = Favorite.objects.order_by('-id') favorite_consumables = [] for fav in fav_consumables: favorite_consumables.append(Consumable(id=fav.consumable_id)) context = { 'favorites' :fav_consumables } return render(request, 'accounts/dashboard.html', context) -
How to completly delete a Django application which has dependencies with another app?
My Django project has several applications and I would like to delete one of them. To do that, I removed the models of this app and everything was fine, but after I removed the application from INSTALLED_APPS and its files, Django complains about dependencies with another application. django.db.migrations.exceptions.NodeNotFoundError: Migration anotherapp.0009_entitystatus dependencies reference nonexistent parent node ('apptodelete', '0002_alter_anotherapp_code') I've tried to reverse migrations for the app I want to remove with the zero option and Django unapplied migrations, but then after I remove the files it keeps complaining because dependencies are still present in the migration files of the other application. $ python manage.py migrate apptodelete zero What is the proper way to do that ? -
How to intergate a Django app into a Wagtail CMS
I have a small django app with some CBV's (f.i. a HTMX/ListView) I want to integrate this app in an exciting Wagtail site: So it is part of Wagtail pages, the menu structure and I can make use of Streamfields on those Django app pages. How can I achieve this? Looking for an example. Lot of examples how to integrate Wagtail into a Django app, but not the other way around. -
Frameworks for beginners [closed]
As a beginner which framework should I learn first, and which is the framework that is a must to learn. I know languages like python, java, javascript, c/c++, etc. I heard about Flask & Django but I am not sure which one to learn first. -
django restframework channels send multiple socket messages at in one go
I want to send an update message to the screen every time its details update. problem is frequent updates end up sending multiple messages to the screen. I want to wait 1 minute to watch for all the changes and send one message to the screen. I am using the Django signal to watch for changes in the database. Here is my code. //views.py class ScreenWebListCreateView(PermissionOrganizationMixins, OrganizationQuerySetMixin, generics.ListCreateAPIView): queryset = ScreenWeb.objects.all() serializer_class = ScreenWebSerializer def perform_create(self, serializer): serializer.save(organization=self.request.organization) # retrieveupdatedestroyapiview class ScreenWebRetrieveUpdateDestroyView(PermissionOrganizationMixins, generics.RetrieveUpdateDestroyAPIView): queryset = ScreenWeb.objects.all() serializer_class = ScreenWebSerializer lookup_field = 'pk' def perform_update(self, serializer): serializer.save(organization=self.request.organization) //signals.py @receiver(post_save, sender=ScreenWeb) def send_socket_message_on_screen_web_update(sender, instance, created, **kwargs): send_update_message_socket_tv(instance.screenCodeApp) @receiver(post_delete, sender=ScreenWeb) def send_socket_message_on_screen_web_delete(sender, instance, **kwargs): send_update_message_socket_tv(instance.screenCodeApp) is there a way to wait for some time to include all changes and then send an update message? -
How to select multiple relative objects of a single object at once Django ForeignKey
So I have two classes one is Book and another one is Category initially I have add the foreign key in Book which points to Category. class Category(models.Model): class Meta: verbose_name_plural = "Categories" category = models.CharField(max_length=20) def __str__(self): return self.category class Book(models.Model): book_title = models.CharField(max_length=20) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.book_title And it works fine I was able to select a category from a selected book inside the admin panel But now I want to select books from category section so that I can select all the books which are of that single category. And for that I changed the code in the following way class Book(models.Model): book_title = models.CharField(max_length=20) def __str__(self): return self.book_title class Category(models.Model): class Meta: verbose_name_plural = "Categories" category = models.CharField(max_length=20) book = models.ForeignKey(Book, on_delete=models.PROTECT) def __str__(self): return self.category The upper code returns tons of errors. Let suppose I have four books in Book table and one category in Category table. so now I want to relate all those books to that category in Category table by just opening a single category. What happening right now is that I have to open each book entry and relate to it's category. But I want a drop … -
How to fix the following group_send communication issue in Django
I want to create a websocket which will send a group message, but the following code does not seem to be working. The function that must be called is not being called, and wrapping it in a async_to_sync, results in a error. Here is the code: async def receive(self, text_data): # Store the message in the database message = json.loads(text_data) name = message['name'] text = message['message'] document = {'name': name, 'message': text} # Send the message to all connected clients # await self.send(text_data=json.dumps(message)) await self.channel_layer.group_send( self.room_group_name, { 'type':'chat_message', 'message':message } ) collection.update_one( {}, {'$push': {'text': document}} ) async def chat_message(self, event): # Send the message to all connected clients print("Message sent to group") message = event['message'] await self.send(text_data=json.dumps({'type':'chat','message': message})) However when I use await self.send(text_data=json.dumps(message)) It does work, only the group_send is not working. Below is the frontend(SvelteKit) code if needed: socket = new WebSocket("ws://127.0.0.1:8000/ws/chat"); socket.addEventListener("open", () => { console.log("Connection is successful!"); }); socket.onmessage = (e) => { const message = JSON.parse`your text`(e.data); console.log("Received message:", message); messages = [...messages, message]; }; });``` -
Django project is not displaying web page [closed]
When I include the Jinja syntax in my django project, the content of the webpage will not display so I viewed the page source and found out that some of the code are missing but when I remove the Jinja it will display but without fetching data from the database {% extends 'shop/base.html' %} {% load static %} {% block title %}Address{% endblock title %} {% block main-content %} <div class="container my-5"> <div class="row"> <h3>Welcome <span class="text-capitalize">{{request.user}}</span></h3> <div class="col-sm-2 border-end"> <ul class="list-unstyled"> <li class="d-grid"><a href="{% url 'profile' %}" class="btn ">Profile</a> </li> <li class="d-grid"><a href="{% url 'address' %}" class="btn btn-primary" >Address</a> </li> </ul> </div> <div class="col-sm-8 offset-sm-1"> <div class="row"> {% for ad in add %} <div class="col-sm-6"> <div class="card m-2"> <div class="card-body"> <h3> Address {{forloop.counter}}</h3> <p>Name: {{ad.name}}</p> <p>Locality: {{ad.locality}}</p> <p>Mobile: {{ad.mobile}}</p> <p>City: {{ad.city}}</p> <p>State: {{ad.state}}</p> <p>Zipcode: {{ad.zip_code}}</p> </div> </div> </div> {% endfor %} </div> </div> {% endblock main-content %} -
How to stop/cancel the celery task by passing 'task_id' to a python function in django?
I have celery task Id, I want to send it as query param to a django url endpoint and cancel/revoke the task using that task_id. Is it possible? If so, how?