Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems trying to improve performance on ModelResource
We have a model, with almost 200k objects and an Export button on Admin that was getting timeout. The resource was dehydrating properties and accessing to DB many times, so I thought that create annotations to those known fields should fix I tried to override the get_queryset on my class that extends from resources.ModelResouce but without success, this override never had been called, I tried next to override the admin.ModelAdmin.get_queryset and then I had some changes and the export was way better than before, but the load on this Admin became to be too slow What is the better way to keep Admin on same performance and apply the annotations only on Resource class? -
TypeError: reverse() takes exactly 2 arguments (1 given)
For some weird reason, reverse function is not working even though my url has no arguments. Url.py: from django.urls import path from . import views urlpatterns = [ path("api/v2/app/nextdialog", views.NextDialog.as_view(), name="app-next-dialog"), ] views.py: class StartAssessment(generics.GenericAPIView): def post(self, request, *args, **kwargs): data = request.data request = build_rp_request(data) response = post_to_app_start_assessment(request) path = get_path(response) step = get_step(response) data["path"] = path data["step"] = step request = build_rp_request(data) app_response = post_to_app(request, path) message = format_message(app_response) return Response(message, status=status.HTTP_200_OK) functions.py: def get_endpoint(payload): head = { "Content-Type": "application/json", } url = reverse("app-next-dialog") response = requests.post(url, data=json.dumps(payload), headers=head) return response When I run this I get the following error. url = reverse("app-next-dialog") TypeError: reverse() takes exactly 2 arguments (1 given) Please does anyone have an idea what's wrong here. I wouldn't think I need to add any other arguments. Thanks -
Django & HTMX - after GET show only section of html template
I want to create an instagram clon. I created a post.html which includes a post-card.html file for all posts and a post-filter.html to filter the posts. <!-- simple post.html view --> <div> <div> {% include '_includes/bars/post-filter.html' %} </div> <div id="more-posts-wrapper"> {% for post in posts %} {% include '_includes/cards/post-card.html' %} {% endfor %} </div> </div> Now I added htmx to load more posts after clicking load more button. I tried to load the new posts after the existing one inside the div with id=more-posts-wrapper: <div> <div> {% include '_includes/bars/post-filter.html' %} </div> <div hx-get="?page={{ page_obj.next_page_number }}" hx-trigger="click" hx-swap="innerHTML" hx-target="#more-posts-wrapper"> <p>LOAD MORE</p> </div> <div id="more-posts-wrapper"> {% for post in posts %} {% include '_includes/cards/post-card.html' %} {% endfor %} </div> </div> Unfortunately, if I press the button, the correct reponse post gets delivered but the whole post.html document gets loaded after the div with id=more-posts-wrapper. I only want to load the post-card.html file and not reload the post-filter.html file. Does anyone know what I can do? -
My sheduled emails(django_q) not working on heroku
I want to mention that everything runs perfectly on my machine localy: I run py manage.py runserver with py manage.py qcluster and then I'm creating task with a deadline and getting an email at certain time, when my task is approaching the deadline, but it is not working on heroku. The problem is certainly not in smtp settings, because I'm getting regular mails through my app I'm using django_q library and sqlite3 as my db. I never deployed any apps before, so I was expecting issues, but I can't find any soution that works for me. I've just started to learn about async tasks, so I would also appreciate any good book/guide/etc. that can clarify how to work with schedulers and deploy all this stuff. Here is my settings.py: from pathlib import Path import os import sys # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent sys.path.insert(0, os.path.join(BASE_DIR, 'apps')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-*z=f*cev*k!rz(g7z9_m3m*%%6%^0box%9sey+5^l520_b-h(q' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True #heroku and localhost ALLOWED_HOSTS = ['ttl-nosov.herokuapp.com', '127.0.0.1'] … -
Django + Celery. Communication of microservices
I have 2 separate microservices. One django server and the other is a celery beat which should send an API request to django once a minute. Docker-compose version: '3' services: # Django application web: build: ./WebService container_name: web_mysite command: python manage.py runserver 0.0.0.0:8000 volumes: - ./WebService/:/Microservices/first/WebService/ ports: - "8000:8000" depends_on: - db_1 env_file: - ./WebService/.env networks: - main # PostgresSQL application db_1: image: postgres:latest container_name: web_postgres restart: always volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=password - POSTGRES_DB=user_balance ports: - "5432:5432" networks: - main # Redis Broker application redis: image: redis container_name: redis ports: - "6379:6379" networks: - main # Celery application celery_worker: restart: always build: context: ./StatisticsService container_name: celery_worker command: celery -A celery_app worker --loglevel=info volumes: - ./StatisticsService/:/Microservices/first/StatisticsService/ - .:/StatisticsService/data depends_on: - redis - db_2 networks: - main # Celery-Beat application celery_beat: restart: always build: context: ./StatisticsService container_name: celery_beat command: celery -A celery_app beat --loglevel=info volumes: - ./StatisticsService/:/Microservices/first/StatisticsService/ - .:/StatisticsService/data depends_on: - redis - db_2 networks: - main volumes: postgres_data: networks: main: Celery-beat func @celery.task() def monitoring(): print("Monitoring balance...") with requests.Session() as session: res = session.get("http://127.0.0.1:8000/api/v1/transaction/current_balance/", data={"user_id": total}) if res.status_code == 200: res_json = res.json() print(res_json) And in celery worker and beat i got Error: requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8000): Max … -
Is the server running on host "db" (172.28.0.2) and accepting TCP/IP connections on port 5432? Docker
django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "db" (172.28.0.2) and accepting TCP/IP connections on port 5432? docker-compose version: '3.9' services: backend: build: ./backend command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - ./backend:/app/backend ports: - "8000:8000" env_file: - backend/.env.dev depends_on: - db db: image: postgres:14-alpine volumes: - postgres_data:/var/lib/postgresql/data/ ports: - "5432:5432" env_file: - backend/.env.dev volumes: postgres_data: Dockerfile: FROM python:3.9.10-alpine ENV PYTHONUNBUFFERED 1 WORKDIR /app/backend COPY requirements.txt /app/backend RUN pip install --upgrade pip RUN apk add --update --no-cache postgresql-client RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev RUN pip install -r requirements.txt RUN apk del .tmp-build-deps EXPOSE 8000 CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] Database setting: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": os.environ.get("POSTGRES_DB"), "USER": os.environ.get("POSTGRES_USER"), "PASSWORD": os.environ.get("POSTGRES_PASSWORD"), "HOST": os.environ.get("POSTGRES_HOST"), "PORT": 5432, } } .env : POSTGRES_USER=user POSTGRES_PASSWORD=password POSTGRES_DB=my_db POSTGRES_HOST=db -
Django QuerySet Regex with MongoDB
I am trying to use Django QuerySet/Filter with Regular Expression to filter the records in my MongoDB database. For the Python packages, I'm using: Django 4.0.3 djongo 1.3.6 pymongo 3.12.6 Here's my current attempt (code): import re from .models import User regex = re.compile(pattern) result = User.objects.filter(name__iregex=regex.pattern) However, I get djongo.exceptions.SQLDecodeError every time I use the filter like above. After looking through StackOverflow, I find out that I can filter by using Django raw but I still want to know if there are any other ways to make the above codes viable. -
Django Cookiecutter Channels3 - connection opens, doesn't send
I started a a project with Django Cookiecutter w/ Docker: https://cookiecutter-django.readthedocs.io/en/latest/ I'm trying to add Channels and follow the tutorial in their docs: https://channels.readthedocs.io/en/stable/tutorial I added Channels 3.0.4 to requirements.txt, rebuilt the docker container. I added channels to settings/base.py, and this: WSGI_APPLICATION = "config.wsgi.application" ASGI_APPLICATION = "config.asgi.application" I updated my config/asgi.py file: import os import sys from pathlib import Path from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from the_pub.chat import routing ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent sys.path.append(str(ROOT_DIR / "the_pub")) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") django_application = get_asgi_application() from config.websocket import websocket_application # noqa isort:skip application = ProtocolTypeRouter({ "https": django_application, "websocket": AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns ) ), }) async def application(scope, receive, send): if scope["type"] == "http": await django_application(scope, receive, send) elif scope["type"] == "websocket": await websocket_application(scope, receive, send) else: raise NotImplementedError(f"Unknown scope type {scope['type']}") created a config/websocket.io file async def websocket_application(scope, receive, send): while True: event = await receive() if event["type"] == "websocket.connect": await send({"type": "websocket.accept"}) if event["type"] == "websocket.disconnect": break if event["type"] == "websocket.receive": if event["text"] == "ping": await send({"type": "websocket.send", "text": "pong!"}) views: # chat/views.py from django.shortcuts import render def index(request): return render(request, 'chat/index.html') def index(request): return render(request, 'chat/index.html', {}) def room(request, room_name): return render(request, 'chat/room.html', { 'room_name': … -
display data in a Multiplechoicefield using a database, forms and bootstrap template
I'm new to Django. I would like to know how to do this manipulation. I have data in my database that I would like to retrieve in a SELECT using forms.py and display that on template (control-form) how to proceed? Thank you I'm a beginner, I want to know -
Intregrity Error In Django after removing one filed
After removing one column from one table i am getting Intregrity error,How to solve the issue, from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('cricket', '1_tennis_ball'), ] operations = [ migrations.RemoveField( model_name='movie', name='application', ), ] -
Chart js multiple pie chart on one page
Iam building my portfolio website and i build a simple stocktracker. I added some charts from Chart.js, but somehow only one gets rendered when I excecute the code. I managed to assign all the divs and data dynamically by making the variables dynamic. I did this by adding the portfolio id in the for loop. I can't figure out why its not working. Appreciate any help. {% extends 'base.html' %} {% block page_content %} {% if user.is_authenticated %} <body> <div class="container"> <div class="row"> <div class="col-12"> <h2> Welcome to the stocktracker </h2> <p>I build this stocktracker app to learn database operations. To get current stock data, I linked this to the free API from Polygon.io. It's only possible to do 5 API calls per minute. You will see an error message whenever the api calls are exceeded. <br><br>Current features are: <ol> <li>Basic CRUD database operation</li> <li>Adding portfolio's linked to user</li> <li>Only show portfolio's linked to user</li> <li>Show general KPI's in portfolio overview</li> <li>KPI's calculated based on positions in portfolio</li> <li>Adding position to portfolio</li> <li>API connection with Polygon.io to get live stock data</li> <li>Chart.js integration for visual representation of portfolio metrics</li> </ol> </p> </div> </div> <div class="row"> <div class="col-8"> <h2>Select your portfolio</h2> … -
How to solve error on using tomtom mapfit?
According to this guide:https://developer.tomtom.com/blog/build-different/adding-tomtom-maps-django-app-building-front-end-map I'm trying to use the tomtom for my django project and everything is working well except the zoom part where the map should zoom according to the accordinates I gave it. The error I get the on explorer consol log is: Uncaught (in promise) Error: `LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, an object {lon: <lng>, lat: <lat>}, or an array of [<lng>, <lat>] The code I tried to run: // create the map tt.setProductInfo('Google Map', '1.0'); let map = tt.map({ key: 'uQInAdnkd8siEnOQdsXUcFi36iHwrgGF', container: 'map' }); // add store markers let bounds = [] let storeLocations = JSON.parse("{{ locations|escapejs }}"); for (let storeLocation of storeLocations) { let coordinates = [storeLocation.longitude, storeLocation.latitude]; bounds.push(coordinates); // create popup to display store information when the marker is clicked let popup = new tt.Popup().setHTML(` <div class="locator-popup"> <h6>Store Name</h6> <p>${storeLocation.name}</p> <h6>Address</h6> <p>${storeLocation.address}</p> </div> `); let marker = new tt.Marker() .setLngLat(coordinates) .setPopup(popup) .addTo(map); } // zoom the map to fit all markers map.on('load', () => { console.log(bounds) map.fitBounds(bounds, { padding: { top: 50, bottom:50, left: 50, right: 50 } }); }) Note: I was thinking that's maybe because of the 'bounds'. So, Checked the output … -
Folders statics not found in server google - Django
Django cannot find the static files on the google server, the python manage.py collectstatic command has already been used with the settings.py configured. To solve this problem I followed several tutorials that showed us how to deploy static files, including the documentation itself. However, none got results. It is worth mentioning that this same code and configuration worked in the homolog version of the system. -
How to add django-crontab in docker container with user django project
Problem ? I am using django-crontab. I can't run it as an authorized user on Docker alpine. I get the following error no crontab for app adding cronjob: (6e4989c275eb1a7f1e4c58d3442c53fe) -> ('*/1 * * * *', 'core.cron.hello') initgroups failed: app Operation not permitted unable to read replacement file /tmp/tmp1ehdmy4i% Docker File FROM python:3.9-alpine3.13 LABEL maintainer="mrfk" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt COPY ./app /app COPY ./scripts /scripts WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apk add --update --no-cache postgresql-client && \ apk add --update --no-cache --virtual .tmp-deps \ build-base postgresql-dev musl-dev linux-headers && \ /py/bin/pip install -r /requirements.txt && \ apk del .tmp-deps && \ apk add --update busybox-suid && \ apk --no-cache add dcron libcap && \ adduser --disabled-password --no-create-home app && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/media && \ chown -R app:app /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts && \ chmod 755 /usr/bin/crontab* ENV PATH="/scripts:/py/bin:$PATH" USER app CMD ["run.sh"] Run.SH File #!/bin/sh set -e ls -la /vol/ ls -la /vol/web whoami service cron start python manage.py wait_for_db python manage.py collectstatic --noinput python manage.py migrate uwsgi --socket :9000 --workers 4 … -
django.db.utils.OperationalError: could not translate host name "db" to address: Name does not resolve?
django.db.utils.OperationalError: could not translate host name "db" to address: Name does not resolve ? Where should be a error? docker-compose.yml version: '3.9' services: backend: build: ./backend command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - ./backend:/app/backend ports: - "8000:8000" env_file: - backend/.env.dev depends_on: - db db: image: postgres:13-alpine volumes: - postgres_data:/var/lib/postgresql/data/ ports: - "5432:5432" env_file: - backend/.env.dev Dockerfile ENV PYTHONUNBUFFERED 1 WORKDIR /app/backend COPY requirements.txt /app/backend RUN pip install --upgrade pip RUN apk add --update --no-cache postgresql-client RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev RUN pip install -r requirements.txt RUN apk del .tmp-build-deps EXPOSE 8000 CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] -
when migrating django codes to the database Errno 2 No such file
I am connecting my database with Django codes so when I use python manage.py makemigrations I get the error as no such file -
Whatsapp conversations on the left side with Django Channels
I'm developing a project with django channellers, but when new messages comes, I can't update the messages on the left side like in whatsapp. I can have a one to one conversation by creating a room, but I cannot see the messages I receive unless I click on the conversation. How should I go about this? -
ValueError: invalid literal for int() with base 10
I'm struggling to understand why I have this error for the custom uuid text field. Data: { "contact_uuid": "49548747-48888043", "choices": "", "value": "1", "cardType": "TEXT", "step": 1, "optionId": "", "path": "/app/e120703e-2079-4e5f-8420-3924f9e0b9c8/page1/next", "title": "Welcome to my app" } View: The important bit here is the line that saves the data so you can gloss over the rest of the code. class NextDialog(generics.GenericAPIView): permission_classes = (permissions.AllowAny,) def post(self, request, *args, **kwargs): data = request.data contact_uuid = data["contact_uuid"] step = data["step"] value = data["value"] optionId = data["optionId"] path = get_path(data) request = build_rp_request(data) app_response = post_to_app(request, path) response_data = AppAssessment(contact_uuid, step, value, optionId) response_data.save() try: report_path = app_response["_links"]["report"]["href"] response = get_report(report_path) return Response(response, status=status.HTTP_200_OK) except KeyError: pass message = format_message(app_response) return Response(message, status=status.HTTP_200_OK) Model: class AppAssessment(models.Model): contact_uuid = models.CharField(max_length=255) step = models.IntegerField(null=True) optionId = models.IntegerField(null=True, blank=True) user_input = models.TextField(null=True, blank=True) title = models.TextField(null=True, blank=True) # description = models.TextField(null=True, blank=True) def __str__(self): return self.contact_uuid When the response_data.save() line runs in the view, I get the following error: File "/home/osboxes/ndoh-hub/venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 972, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '49548747-48888043' -
How to Generate a unique Coupon Code In the Django Admin panel for bulk
#i have used this code in models.py #im getting errror of Gift is not defined and models are not shwoing in the Django admin panel# from django.db import models import secrets from django.db.models.signals import post_save class UniqueCodes(models.Model): """ Class to create human friendly gift/coupon codes. """ # Model field for our unique code code = models.CharField(max_length=8, blank=True, null=True, unique=True) @classmethod def post_create(cls, sender, instance, created, *args, **kwargs): """ Connected to the post_save signal of the UniqueCodes model. This is used to set the code once we have created the db instance and have access to the primary key (ID Field) """ # If new database record if created: # We have the primary key (ID Field) now so let's grab it id_string = str(instance.id) # Define our random string alphabet (notice I've omitted I,O,etc. as they can be confused for other characters) upper_alpha = "ABCDEFGHJKLMNPQRSTVWXYZ" # Create an 8 char random string from our alphabet random_str = "".join(secrets.choice(upper_alpha) for i in range(8)) # Append the ID to the end of the random string instance.code = (random_str + id_string)[-8:] # Save the class instance instance.save() def __str__(self): return "%s" % (self.code,) post_save.connect(Gift.post_create, sender=UniqueCodes) -
Internal server error 500 while using application
Please find below event viewer log,can anyone help me why am getting this error(sometimes) Environment details: Django framework IIS application Python 3/7 Faulting application name: python.exe, version: 3.7.3150.1013, time stamp: 0x5c9954fa Faulting module name: _ctypes.pyd, version: 3.7.3150.1013, time stamp: 0x5c9954c9 Exception code: 0xc0000005 Fault offset: 0x000000000000f365 Faulting process id: 0x1938 Faulting application start time: 0x01d839ca6dc31b14 Faulting application path: D:\qm_env\Scripts\python.exe Faulting module path: d:\python37\DLLs_ctypes.pyd Report Id: 8701a9d7-3cc9-4a91-b8c5-ff04fb2b2a59 Faulting package full name: Faulting package-relative application ID: -
Cannot assign "str" must be a "User" instance
I'm trying to make a post request to django rest api from reactjs but the traceback shows, ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x00000247410D3670>": "BuildingClearance.resident_number" must be a "User" instance. models.py class BuildingClearance(models.Model): resident_number = models.ForeignKey(to=User, to_field="resident_number", on_delete=models.CASCADE) request_number = models.AutoField(primary_key=True) maintenance_type = models.CharField(max_length=100, blank=False) approval = models.BooleanField(default=False) views.py class BuildingClearanceList(ListCreateAPIView): permission_classes = [AllowAny] serializer_class = BuildingClearanceSerializer queryset = BuildingClearance.objects.all() def perform_create(self, serializer): return serializer.save(resident_number=self.request.user) def get_queryset(self): return self.queryset.filter(resident_number=self.request.user) class BuildingClearanceView(RetrieveUpdateDestroyAPIView): serializer_class = BuildingClearanceSerializer queryset = BuildingClearance.objects.all() def perform_create(self, serializer): if self.request.user.is_authenticated: return serializer.save(resident_number=self.request.user) def get_queryset(self): return self.queryset.filter(resident_number=self.request.user) serializers.py class BuildingClearanceSerializer(ModelSerializer): class Meta: model=BuildingClearance exclude = ['resident_number'] If i set the permission_classes to [isAuthenticated], the error message will be 401 unauthorized (Authentication credentials were not provided) even though i included the right headers: services.js const API_URL = "http://127.0.0.1:8000/api/forms/"; buildingClearance(maintenance_type) { var token = JSON.parse(localStorage.getItem('user')).access; console.log(token) return axios .post(API_URL + "building/", { headers:{ Accept: 'application/json', Authorization: 'Bearer ' + token }, maintenance_type }) } -
django celery error: Unrecoverable error: AttributeError("'EntryPoint' object has no attribute 'module_name'")
I am perplexed,from a weird error which i have no idea as i am new to celery, this error occurs on just the setup phase, every thing is simply configured as written in the celery doc https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html the tracback is: (env) muhammad@huzaifa:~/Desktop/practice/app$ celery -A app worker -l INFO [2022-04-04 16:21:40,988: WARNING/MainProcess] No hostname was supplied. Reverting to default 'localhost' [2022-04-04 16:21:40,993: CRITICAL/MainProcess] Unrecoverable error: AttributeError("'EntryPoint' object has no attribute 'module_name'") Traceback (most recent call last): File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/app/base.py", line 1250, in backend return self._local.backend AttributeError: '_thread._local' object has no attribute 'backend' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/worker/worker.py", line 203, in start self.blueprint.start(self) File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/bootsteps.py", line 112, in start self.on_start() File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/apps/worker.py", line 136, in on_start self.emit_banner() File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/apps/worker.py", line 170, in emit_banner ' \n', self.startup_info(artlines=not use_image))), File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/apps/worker.py", line 232, in startup_info results=self.app.backend.as_uri(), File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/app/base.py", line 1252, in backend self._local.backend = new_backend = self._get_backend() File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/app/base.py", line 955, in _get_backend backend, url = backends.by_url( File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/app/backends.py", line 69, in by_url return by_name(backend, loader), url File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/app/backends.py", line 47, in by_name aliases.update(load_extension_class_names(extension_namespace)) File "/home/muhammad/Desktop/practice/env/lib/python3.8/site-packages/celery/utils/imports.py", line 146, in load_extension_class_names yield ep.name, ':'.join([ep.module_name, ep.attrs[0]]) AttributeError: 'EntryPoint' object has no attribute 'module_name' the init file … -
A Model is linked to two other models. How do I access the properties of that two other models in django
I am in a process of creating a Room Booking Management System using Django. I have faced an issue in accessing models. Here is my Room Model class Room(models.Model): name = models.CharField(max_length=30) date = models.DateField() defined_check_in_time = models.IntegerField() defined_check_out_time = models.IntegerField() booked = models.BooleanField(default = False) USERNAME_FIELD = 'name' class Meta: ordering = ['date', 'defined_check_in_time'] def __str__(self): return self.name def is_booked(self): return self.booked def set_booked(self): self.booked = True Here is my Booking Model class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) def __str__(self): return f'{self.user} has booked {self.room} from {self.room.defined_check_in_time} to {self.room.defined_check_out_time} on {self.room.date}' I have linked the User model and Room model in the Booking model using a foreign key when a user books a room. User model is defined in another file. I have not included that model code here. When a user books a room, the corresponding room object and user object is linked to the booking object. To display the bookings of the user, I need to query the Booking model using a User object. Here, my question is how i can access user and room object attributes inside the booking object? -
dj-rest-auth logout view returns `CSRF: Failed` while login view works
I'm integrating with dj-rest-auth for my rest api and testing via Postman right now. The login-view works just fine and returns the token, however the logout view returns "detail": "CSRF Failed: CSRF token missing." #urls.py from django.urls import path, include urlpatterns = [ path('auth/', include('dj_rest_auth.urls')), ] Both endpoints expect a POST request which I use accordingly. So why does the logout view bark? -
DRF and Knox Authentication: Demo accounts where user doesn't have to input credentials
I'm making an app with React as the front end and am handling authentication with knox. Everything is working fine but I require the ability for users to login to premade demo accounts without inputting any credentials. I can't figure out how to do this with Knox on the backend and I can't have the login info stored in my javascript. Any ideas how to accomplish this? Knox: class LoginAPI(KnoxLoginView): authentication_classes = [BasicLikeAuthentication] def get_post_response_data(self, request, token, instance): user = request.user data = { 'expiry': self.format_expiry_datetime(instance.expiry), 'token': token, 'user': user.username, 'role': user.roles.assigned_role } return data Front end for regular login: const handleSubmit = (event) => { event.preventDefault(); const data = new FormData(event.currentTarget); const credentials = btoa(`${data.get('username')}:${data.get('password')}`); const requestOptions = { method: "POST", credentials: 'include', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', "Authorization": `Basic ${credentials}` }, body: JSON.stringify({}) } fetch('http://127.0.0.1:8000/api/login/', requestOptions) .then(response => { if (response.status === 401) { setFailedLogin(true) } return response.json() }) .then(data => { localStorage.setItem('token', data['token']) }) .then(fetchCurrentUser) .then(() => { localStorage.getItem('role') == "Admin" ? navigate("/manage") : navigate("/maindash") }) .catch(error => console.log(error)) }