Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
token authentication in django rest framewok is not working with digitalocean, but it is working perfectly in my local
i have deployed a django rest framework in digitalocean,eveything is working perfectly when make a post and get request with postman software,but when make a post request to this TestView which is bellow, it is showing this error : "Field 'id' expected a number but got <django.contrib.auth.models.AnonymousUser object at 0x7f10fecb2ed0>." in this line : score = Score.objects.get(user=request.user.id). this is the TestView : class TestView(APIView): authentication_classes = [TokenAuthentication] def get(self, request): questions = Question.objects.all() questions_serializer = QuestionsSerializer(questions,many=True,context={'request': request}) return Response(questions_serializer.data) def post(self, request): question_id = request.data.get('id') user_answer = request.data.get('answers') correct_answer = Answer.objects.filter(question=question_id, is_correct=True).values_list('answer', flat=True).first() if correct_answer is not None: if user_answer == correct_answer: try: score = Score.objects.get(user=request.user.id) print(self.user) score.score += 1 score.save() except Score.DoesNotExist: score = Score.objects.create(user=request.user, score=1) score_serializer = ScoreSerializer(score) return Response({'message': 'your answer was correct', 'score': score_serializer.data}, status=status.HTTP_200_OK) else: return Response({'message': 'your answer was incorrect'}, status=status.HTTP_400_BAD_REQUEST) else: return Response({'message': 'correct answer not found for this question'}, status=status.HTTP_404_NOT_FOUND) if hard coded the user id in this line of code like this: instead of this : score = Score.objects.get(user=request.user.id) changed to this : score = Score.objects.get(user=1) then it works. i also printed the print(request.user),print(request.user.id) and print(request.auth) they are null, but in my local print(request.user) is printing the user. i also contact … -
Postgres Database connection pooling in django
I want to implement database connection pooling in django.I have tried setting "CONN_MAX_AGE" to None and even to a number like 1800 but this does not seem to help also I have tried setting DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": env("POSTGRES_DB"), "USER": env("POSTGRES_USER"), "PASSWORD": env("POSTGRES_PASSWORD"), "HOST": env("POSTGRES_HOST"), "PORT": env("POSTGRES_PORT"), 'OPTIONS': { 'isolation_level': psycopg2.extensions.ISOLATION_LEVEL_READ_COMMITTED, 'conn_max_age': 600, }, } } but still I can't see database connections getting pooled. I have another question how will I check if database connection is getting pooled or not? tried above with no result -
Search for rows in the Sqlite database that contain certain words
I was making a killboard for EVE online and wanted to do a database search for certain words contained in the string. Here are all the column names of my database: id final_blow_name final_blow_ship_type victim_name victim_corporation victim_birthday victim_gender victim_security_status victim_ship_type sistem_security_status attackers_len I did it using LIKE and WHERE. But it gives the error "no such column: the name I was looking for". Here is my code: path = 'C:/Users/mrjol/PycharmProjects/myboard/board_veiw/database.db' connection = sqlite3.connect(path) cursor = connection.cursor() search_request = str(request.session.pop('search_request', 'None')) character_name_1 = search_request.partition(' ')[0] character_name_2 = search_request.partition(' ')[2] if character_name_2 != '': search_request = character_name_1 + '_' + character_name_2 search_answer = cursor.execute('SELECT final_blow_name FROM Killmails WHERE final_blow_name = Cosmo_Blink') connection.close() -
How can you use JavaScript to send a video blob to a Django view using a Django form?
In a nutshell How can I use JavaScript to get a blob of video data to a Django view through a Django form? Background I'm building a feature to record a webcam video. I've successfully figured this part out. I can use JavaScript to stream the user's camera and mic, record the stream, turning it into a blob, and then I'm able to turn the blob into a file. However, I don't want a file because I need users' videos to simply be sent to my backend, and I don't want users to interact with a video file (and I just learned that you can't programmatically assign <input type='file'> elements a file because of security reasons). This is why I'm looking to just send the binary data. What I've Tried (and what the result was) Like I said, I tried using a FileField in my Django form (but cuz inherent web security restrictions, no worky). Having users download and upload the file themselves does not work with project requirements. I've tried using a JSONField for my Django form and submitting the binary in JSON format. Perhaps this could still work, but I can't get the binary data into JSON format. … -
SearchVector is splitting hyphens in my UUID field
I have a django application and I am trying to use a field named external_id, that is a UUID string to build my SearchVector (from django.contrib.postgres.search) . The problem is that the search_vector being created in the Postgres DB is splitting the strings between the hyphens, for example: external_id = 5f4ffd5b-0738-4aa4-8961-3114b54d1e20 search_vector = '-0738':2 '-3114':6 '-4':3 '-8961':5 '5f4ffd5b':1 'aa4':4 'b54d1e20':7 So, when I am trying to search for the complete UUID, I do not get a match, but searching for the parts created in the search_vector matches, like: 5f4ffd5b or -8961. I have tried changing my Postgres search configuration using: CREATE TEXT SEARCH CONFIGURATION public.my_search_config (copy=simple); ALTER TEXT SEARCH CONFIGURATION public.my_search_config DROP MAPPING FOR hword, hword_part, word, word_part; CREATE MAPPING FOR asciiword, asciihword, hword_ascii WITH simple; but got: SQL Error [42601]: ERROR: syntax error at or near "MAPPING" Position: 8 I have also tried to modify the text search parser: ALTER TEXT SEARCH PARSER default_parser SET TOKEN_TYPE = 'word', START = 'a' , GETTOKEN = 'dsimple'; but got: SQL Error [42601]: ERROR: syntax error at or near "TOKEN_TYPE" Position: 45 -
error getting credentials - err: exec: "docker-credential-desktop": executable file not found in %PATH%, out: `
I am working on a django project in window 10 Home, with docker desktop. When trying to create a multiple container with the command docker compose up -d (or docker-compose up -d) it gives me the following error: $ docker compose up -d [+] Running 0/1 mysql Pulling error getting credentials - err: exec: "docker-credential-desktop": executable file not found in %PATH%, out: I have tried the following: -Change the path found in the PATH of the environment variables, the original is C:\Program Files\Docker\Docker\resources\bin, but if I change it to C:\Program Files\Docker\Docker\resources\ bin\docker.exe or C:\Program Files\Docker\Docker\resources\bin\docker-compose.exe, it gives me another error: $ docker compose up -d bash:docker:command not found -I have also changed the value "credsStore" to "credStore" in the config-options.json file, as some users suggest in other similar cases, but it has no effect I hope you can help me -
prefetch_related not working when using SerializedMethodField
I have four levels of nested models, the Company > Division > Team > TeamMember. The following code serializes everything correctly. My issue is when trying to use prefetch_related in views.py. Based on the SQL queries reported in the debugger, it looks like the Division and Team tables are being prefetched correctly, but there are hundreds of extra SQL queries for the TeamMember table. I suspect the issue might be that within CompanySerializer, I am using a SerializerMethodField to get Teams. Could it be that using Team.objects.filter(division__company=obj) is not compatible with prefetching? models.py class TeamMember(models.Model): name = models.CharField("Name", max_length=300, unique=True) team = models.ForeignKey("Team", on_delete=models.RESTRICT) class Team(models.Model): name = models.CharField("Name", max_length=300) division = models.ForeignKey("Division", on_delete=models.RESTRICT) class Division(models.Model): name = models.CharField("Name", max_length=300, unique=True) company = models.ForeignKey("Company", on_delete=models.RESTRICT) class Company(models.Model): name = models.CharField("Name", max_length=300) serializers.py class TeamMemberSerializer(ModelSerializer): class Meta: model = TeamMember fields = '__all__' class TeamSerializer(ModelSerializer): teammembers = TeamMemberSerializer(read_only=True, many=True, source="teammember_set") class Meta: model = Team fields = '__all__' class DivisionSerializer(ModelSerializer): teams = TeamSerializer(read_only=True, many=True, source="team_set") class Meta: model = Division fields = '__all__' class CompanySerializer(ModelSerializer): # I suspect the issue might here. I wish to return the company's divisions AND # teams in this fashion. When the SerializedMethodField is removed, the … -
Django always acesses default DB
I'm creating an API with a dynamic database (based on the client accessing it), but for testing purposes, I manually defined two in settings.py: DATABASES = { 'default': {}, 'test1': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'model_base1', 'USER': 'root', 'PASSWORD': '123', 'HOST': '127.0.0.1', 'PORT': '3306', 'OPTIONS': {'charset': 'utf8mb4'}, }, 'test2': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'model_base2', 'USER': 'root', 'PASSWORD': '123', 'HOST': '127.0.0.1', 'PORT': '3306', 'OPTIONS': {'charset': 'utf8mb4'}, }, } I have this view file: from rest_framework import generics from cadastro.models.enderecos import Enderecos from cadastro.serializers.enderecos import EnderecosSerializer class EnderecoListarCriarAPIView(generics.ListCreateAPIView): queryset = Enderecos.objects.using('test1').all() serializer_class = EnderecosSerializer and I have this serializer: from rest_framework import serializers from cadastro.models.enderecos import Enderecos class EnderecosWriteOnlyMixin: def get_fields(self): fields = super().get_fields() fields['id_referencia'].read_only = True fields['tipo_tabela_referencia'].read_only = True return fields class EnderecosSerializer(EnderecosWriteOnlyMixin, serializers.ModelSerializer): id_referencia = serializers.IntegerField() tipo_tabela_referencia = serializers.IntegerField() class Meta: model = Enderecos fields = [ "id_endereco", "id_referencia", "tipo_tabela_referencia", "cep", "logradouro", "numero", "complemento", "bairro", "cidade", "uf", ] def to_internal_value(self, data): # Aplicar uppercase para todos os campos for field_name, field_value in data.items(): if isinstance(field_value, str): data[field_name] = field_value.upper() return super().to_internal_value(data) Model.py of this view / serializer: from django.db import models from cadastro.validators.enderecos import * class Enderecos(models.Model): id_endereco = models.AutoField(primary_key=True) cep = models.CharField( max_length=10, blank=False, null=False, validators=[validate_cep] ) numero = models.CharField( … -
Encountering "Not Found" Error Only in Production Environment
Not Found The requested resource was not found on this server. I think the issue is in my setting.py file: from pathlib import Path import os import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', default='your secret key') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = 'RENDER' not in os.environ ALLOWED_HOSTS = [] RENDER_EXTERNAL_HOSTNAME = os.environ.get('RENDER_EXTERNAL_HOSTNAME') if RENDER_EXTERNAL_HOSTNAME: ALLOWED_HOSTS.append(RENDER_EXTERNAL_HOSTNAME) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'coreapi', 'tareas', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'calendar_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'calendar_app.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': dj_database_url.config( default='postgresql://postgres:postgres@localhost/postgres', conn_max_age=600) } # Password validation # https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = … -
Problem uploading multiple images to s3 with a single API call
I have a post API which receives an array of response objects from frontend. Each object consists of certain string fields and a 'pic' field which contains a pic. What happens at backend is an object is made from the string fields and the pic is stored in s3 bucket. I tested this whole flow on my local multiple times and it worked perfectly fine. However when I pulled the code on the AWS server, the submit API fails if the pic exists in request from frontend. Moreover if there is a pic in just one object from the request data it gets uploaded but multiple images fail to get uploaded. And this happens only on server, locally it worked fine. My API looks like: class QuestionResponseCreateView(generics.CreateAPIView): serializer_class = QuestionResponseSerializer authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def post(self, request, *args, **kwargs): print(request.user) responses = request.data print(request.data) saved_responses = [] for response_data in responses: try: # print(response_data) question_id = response_data['question_id'] outlet = response_data['outlet'] response = response_data['response'] image_data = base64.b64decode(response_data.get('pic')) image_file = BytesIO(image_data) remarks = response_data['remarks'] userName = response_data['userName'] question = Question.objects.get(id=question_id) photo_type = question.get_photo_type_label() current_datetime = timezone.now() year = current_datetime.year month = current_datetime.month day = current_datetime.day directory_path = f"{outlet}/{photo_type}" photo_name = … -
How to pull up a value when selecting a value from a list
we need the help of smart people. I have the following models class PCModel(models.Model): PC_name = models.CharField('Названние компьютера', max_length=60) CPU = models.ForeignKey('CPUModel', verbose_name='Процессор', on_delete=models.SET_NULL, blank=True, null=True) GPU = models.ForeignKey('GPUModel', verbose_name='Видеокарта', on_delete=models.CASCADE, blank=True, null=True) RAM = models.ForeignKey('RAMModel', verbose_name='Оперативная память', on_delete=models.CASCADE, blank=True, null=True) Motherboard = models.ForeignKey( 'MotherboardModel', verbose_name='Материнская плата', on_delete=models.CASCADE, blank=True, null=True ) HDD = models.ForeignKey('HDDModel', verbose_name='HDD', on_delete=models.CASCADE, blank=True, null=True) SSD = models.ForeignKey('SSDModel', verbose_name='SSD', on_delete=models.CASCADE, blank=True, null=True) Power_suppy = models.ForeignKey('Power_suppyModel', verbose_name='Блок питания', on_delete=models.CASCADE, blank=True, null=True) Case = models.ForeignKey('CaseModel', verbose_name='Корпус', on_delete=models.CASCADE, blank=True, null=True) purchase_price = models.IntegerField('Стоимость покупки', default=0) cost_of_sale = models.IntegerField('Стоимость продажи', default=0) profit = models.IntegerField('Прибыль', default=0) slug = models.SlugField(unique=True, blank=True, null=True) sold = models.BooleanField('Статус', default=False) def __str__(self): return self.PC_name def get_absolute_url(self): return reverse("pcmodel_detail", kwargs={"slug": self.slug}) def save(self, *args, **kwargs): self.slug = self.slug super(PCModel, self).save(*args, **kwargs) and class CPUModel(models.Model): manufacturer = models.CharField(max_length=15, choices=manufacturer_choice) name = models.CharField(max_length=50) number_of_cores = models.IntegerField('Количество ядер', choices=number_choice) number_of_threads = models.IntegerField('Количество потоков', choices=number_choice) base_frequency = models.IntegerField('Базовая частота', choices=frequency_choice) turbo_boost = models.IntegerField('Частота Turbo boost', choices=frequency_choice) socket = models.IntegerField('Сокет', choices=socket_choice) TDP = models.IntegerField('Тепловыделение (TDP)', choices=TDP_choice) RAM_type = models.CharField('Поддерживаемый тип памяти', choices=RAM_type_choice, max_length=5) purchase_price = models.IntegerField('Цена закупки') count = models.IntegerField('Количество') in_stock = models.BooleanField('Наличие', default=False) def __str__(self): return self.name def __int__(self): return self.purchase_price def get_purchase(self): return self.purchase_price There is a form class AddPCForm(forms.ModelForm): CPUModel … -
Best practices of implementing a computationally intensive task on a socket connection [closed]
The context is as follows: I am working on a specific widget on the dashboard of a SAAS product. The backend is in Django. The widget displays a line graph of certain measurements updated real time. This part is implemented using Django channels. Among the various buttons at the bottom of the widget is one that initiates a time consuming calculation, the result of which is another line graph overlaid on the same figure. Note: The dashboard has other widgets on their own socket connections. So unless I am mistaken this seems to be both a CPU bound as well as an IO bound problem. Initially I had decided to use celery to offload the calculation on a different process but after a bit of research it seems that one normally uses celery for fire-and-forget tasks where the end result of the process doesn't have to be returned to the user which doesn't fit my use-case since I have to feed the result of my computation back to the user. In my research I have also found a few libraries that may help but I am unclear about whether they are the way to go or too much for my … -
Saving formset related models by multi-room relationships in Django
Please tell me how to save a formset with two models related to the manytomanyfield relationship, it turns out while two forms are displayed when the page is opened, after filling in and clicking on the "Add" button, the "phone" and "client_name" fields are cleared and the form is not sent. In view class OrderCreateView(CreateView), checking client_formset.is_valid() returns False. Here is the code: models.py from django.db import models from django.contrib.auth.models import User class Client(models.Model): phone = models.CharField(max_length=20, verbose_name='Телефон') client_name = models.CharField(max_length=100, verbose_name='ФИО клиента') def __str__(self): return '%s %s' % (self.phone, self.client_name) class Meta: verbose_name = 'Клиент' verbose_name_plural = 'Клиенты' class Order(models.Model): author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, verbose_name='Принял', blank=True) date_of_creation = models.DateTimeField(auto_now=True, verbose_name='Дата создания') execution_date = models.DateField(verbose_name='Дата исполнения') address = models.CharField(max_length=200, verbose_name='Адрес') service = models.CharField(max_length=100, verbose_name='Услуга') master = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='master', null=True, verbose_name='Мастер', blank=True) client = models.ManyToManyField(Client, verbose_name='Клиент', blank=True) def __str__(self): return '%s %s %s' % (self.execution_date, self.address, self.service) class Meta: verbose_name = 'Заявка' verbose_name_plural = 'Заявки' forms.py from django import forms # from .models import Orders, Person, Phone from .models import Order, Client from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.models import User from django.forms import modelformset_factory class UserFullnameChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return obj.get_full_name() class OrderForm(forms.ModelForm): master = UserFullnameChoiceField(queryset=User.objects.all(), label='Мастер') class Meta: … -
Investigating Slow Performance in Adding Products to Django Oscar Basket via REST API
I'm currently facing performance issues when adding products to the shopping cart in a Django Oscar-based e-commerce application. The problem becomes particularly noticeable when the basket contains around 50 items. I'm using Django Oscar's REST API for adding products to the basket, which is called by JavaScript. The challenge is to identify the root cause of the slowdown and explore possible solutions. Observations: Adding products through product list views is slow. Adding products through the product detail page remains fast even with a considerable number of products in the cart. Details: API Endpoint: http://localhost:8000/en/api/basket/add-product/ Direct Adding via Detail Page: http://localhost:8000/en/basket/add/12787/ Offer Calculations: Offers are a significant concern, as adding a line to the basket triggers the calculation of all available offer conditions for each row. Investigation So Far: Middleware Approach: For direct adding via the detail page, offer calculations are handled in Django Oscar's BasketMiddleware during the redirect page load. This code might be better optimized compared to the custom code in the API. Offer Calculation in API: The problem intensifies when the basket consists of 30+ basket lines with different products. The query count increases linearly with the basket line count during API calls. Request for Help: I'm seeking … -
CreateView template not found
I am trying to create a CreateView in Django, but am facing a 'template not found' error (shown below) Currently, I have the following code: views.py: from django.shortcuts import render from django.views.generic import ( ListView, DetailView, CreateView, DeleteView ) from .models import EventPost class EventPostListView(ListView): model = EventPost template_name = "event_blog/home.html" context_object_name = "event_posts" ordering = ['-date_posted'] class EventPostDetailView(DetailView): model = EventPost class EventPostCreateView(CreateView): model = EventPost fields = ['name', 'location', 'locked', 'description', 'image'] urls.py: from django.urls import path from .views import * urlpatterns = [ path("", EventPostListView.as_view(), name="event-blog-home"), path("event/<int:pk>/", EventPostDetailView.as_view(), name="post-detail"), path("event/new/", EventPostCreateView.as_view(), name="post-create"), ] You can see I have already used a ListView and DetailView which has worked fine. The code from these views also extends 'event_blog/base.html' so I do not expect this to be the issue. Here is the directory for the files: And the HTML code for the template if you needed it: {% extends "event_blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New Event</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-secondary mt-3 mb-3" type="submit">Post</button> </div> </form> </div> {% endblock content %} Also the model: class EventPost(models.Model): name = models.CharField(max_length=100) location = … -
Building Issue When Deploying Django Project To Railway
When I upload my django project online to railway the following error appears: Dockerfile:20 18 | ENV NIXPACKS_PATH /opt/venv/bin:$NIXPACKS_PATH 19 | COPY . /app/. 20 | >>> RUN --mount=type=cache,id=s/585223ec-cc75-4dcd-9f98-7ab08bb3e77f-/root/cache/pip,target=/root/.cache/pip python -m venv --copies /opt/venv && . /opt/venv/bin/activate && pip install -r requirements.txt 21 | 22 | ERROR: failed to solve: process "/bin/bash -ol pipefail -c python -m venv --copies /opt/venv && . /opt/venv/bin/activate && pip install -r requirements.txt" did not complete successfully: exit code: 1 Error: Docker build failed **My Settings.py** """ Django settings for django2 project. Generated by 'django-admin startproject' using Django 4.2.6. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'bootstrap4', 'stdimage', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'django2.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'django2.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django2', 'USER': 'root', 'PASSWORD': 'django2023', 'HOST': 'localhost', 'PORT': '3306', } } # Static files (CSS, … -
Django Rest - Redirect Password Form?
I recently upgraded to Django 4.0 and upgraded django-allauth with alongside django-rest-auth. When a user fills out the password reset form under http://localhost:8000/api/dj-rest-auth/password/reset/ they get a link in the console that goes to: http://localhost:8000/users/reset/2n/bxggn2-05019c81f9d6dfda6a10b7cfec09e839/ The link provided gets me to this old form: How can I get this message in the console to point to accounts/password/reset/key/1-set-password/? That form looks like this: That’s where my allauth form lives and I’m not fully sure if this is the correct approach. Below is some of my settings and urls. Any help is gladly appreciated. Thanks! settings.py INSTALLED_APPS = [ # Local, 'api.apps.ApiConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.humanize', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.sites', 'users', # 3rd Party 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'allauth.socialaccount', 'dj_rest_auth', 'dj_rest_auth.registration', 'corsheaders', 'drf_yasg', ] AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAdminUser', 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' } urls.py from django.urls import path, include from allauth.account.views import ConfirmEmailView, EmailVerificationSentView urlpatterns = [ path('accounts/', include('allauth.urls')), path('', include('users.urls')), path('api/', include('api.urls')), path('api-auth/', include('rest_framework.urls')), path('api/dj-rest-auth/registration/account-confirm-email/<str:key>/', ConfirmEmailView.as_view()), # Needs to be defined before the registration path path('api/dj-rest-auth/', include('dj_rest_auth.urls')), path('api/dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('api/rest-auth/registration/account-confirm-email/', EmailVerificationSentView.as_view(), name='account_email_verification_sent'), path('', include('django.contrib.auth.urls')), path('users/', include('users.urls')), path('users/', include('django.contrib.auth.urls')), ] -
Django app cannot delete AWS S3 bucket items
DISCLAIMER: (I'll put it at the top so people don't just skip and not read) I just recently started using AWS so I still don't understand a lot of things and yes, I already did the research on this subject and every post I found said to "make the bucket publicly available" which is something I would like to avoid and that should not be the correct answer since, in the tutorial I was following, the guy used it as private blocking all outside access. The upload of an Images works without issues, so I would roule out any problem with the connection itself, but when I try to delete one I get the error An error occurred (AccessDenied) when calling the DeleteObject operation: Access Denied I was following a tutorial about how to connect the bucket to django. The steps I took: Created a bucket (not public like it said in the tutorial) Created a User Group with "AmazonS3FullAccess" policy Created a User inside the group with both the S3 full access and the "AWSCompromisedKeyQuarantineV2" policy Generated the necessary keys (secret and access) The S3FullAccess policy should be this one: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": … -
Django Model Inheritance: Every
In Django, I want to have several models of the same type: ANode, BNode, CNode are all of type "Node". In the database, you can look up a "Node" by id, then quickly get what kind of Node it is (ANode, BNode, CNode), and then reference that node. Every node is only of one specific node type, and there are node "Nodes", only "ANodes", "BNodes", "CNodes". There may be many kinds of Nodes (A-Z) each with different fields. I can picture the underlying SQL: there is a "Node" table with an ID column and an enum field keeping track of which type of Node it is. How can I implement that? -
How to let Django serve images when hosting on Vercel
I deployed a Django project on Vercel. The app is responsible for serving data to a Next.js frontend. However, the images don't get served while other data do. GET request to the images return NOT FOUND error after deploying to Vercel. I have studied all similar questions on this platform but none seems to solve my problem. I have this in my settings.py file: STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles_build', 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/article_photos') I'm serving only the article_photos. I have this in my project urls.py file: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is the structure of my media folder: I have struggled with this problem throughout the whole day. Any help will be appreciated. Update: This is my vercel.json file: { "builds": [{ "src": "core/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } }, { "src": "build_files.sh", "use": "@vercel/static-build", "config": { "distDir": "staticfiles_build" } }], "routes": [ { "src": "/static/(.*)", "dest": "/static/$1" }, { "src": "/(.*)", "dest": "core/wsgi.py" } ] } This is my my build_files.sh echo "BUILD START" python3.9 -m pip install -r requirements.txt python3.9 manage.py collectstatic --noinput --clear echo "BUILD END" Update 2: Below is the error returned: … -
Python Django and parallel process
I'm making a delayed messaging service in Django. I reached the task manager. In theory, it should be launched in parallel with Django, its task is to “read the database” and send messages. I used "multiprocessing Pool", the code was entered into manage.py. It confuses me that when starting, one of the processes fires twice, “ok” in the screenshot. Using a parallel process, the site is assembled and works properly. why is that? Are there any better practices? Result: не ok не ok Performing system checks... Watching for file changes with StatReloader System check identified no issues (0 silenced). November 10, 2023 - 16:55:45 Django version 4.2.6, using settings 'WhiteRabbit.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. ok 2023-11-10 16:56:44.743514 ok 2023-11-10 16:56:45.275028 manage.py: import os import sys from multiprocessing import Pool from automation.task_messanger import task_messanger def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WhiteRabbit.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': with Pool(processes=2) as pool: pool.apply_async(task_messanger, ) pool.apply_async(main(), ) # main() … -
How to generate ID card or certificate in Django with any kind of template as MS Word or PPT or PDF?
I need help to make a ID card or document in django to provide user their ID card or any dynamic documents such as certificates. And provide as PDF I tried, Python docx library. with that it is possible to create a docx file and even add an image. but if i use a template and when i want to replace a text in the docx and the text is in text-box in word then its not replacing. Btw, I solved that. but now i can't replate a image in appropriate place in word. SEE THE TEMPLATE IMAGE . Here if i want to add an image and the image i want to place is in the center Top. but i can't do it. So Please if you can help with this that's fine else , Please give a way that how can i edit a document template with python Just need to generate dynamic document. CODE : def myreplace(file, regex, replace): for p in file.paragraphs: if regex.search(p.text): inline=p.runs for i in range(len(inline)): if regex.search(inline[i].text): text=regex.sub(replace, inline[i].text) inline[i].text=text for table in file.tables: for row in table.rows: for cell in row.cells: myreplace(cell, regex, replace) def ReadingTextDocuments(fileName): doc = Document (fileName) completedText … -
Django Filter a Queryset based on Prefetched FK Relationsship
I have 2 models below, and I am trying to run a query on JournalLineItems that filters out entries that have no associated GeneralLedger entry. My queries are not able to find the right items as I am querying wrong. class JournalLineItem(SafeDeleteModel, UUID, TimestampModel): id = models.AutoField(primary_key=True) ... class GeneralLedger(SafeDeleteModel, UUID, TimestampModel): id = models.AutoField(primary_key=True) journal_line_item = models.ForeignKey('accounting.JournalLineItem', null=True, on_delete=models.CASCADE, related_name='general_ledger', db_index=True) Overall I can do this, but I want it done on the DB level with a queryset filter: for line_item in JournalLineItem.objects.filter().prefetch_related('general_ledger').using(client_url).order_by('-accounting_period', '-pk'): # only deal with ones that are not in the GL if not line_item.general_ledger.exists(): ... When I try this, the query is not right: JournalLineItem.objects.filter(general_ledger=None).prefetch_related('general_ledger') or JournalLineItem.objects.filter(general_ledger__is_null=True).prefetch_related('general_ledger') -
Not Logging the supplier when suppplier has more then 1 product in his list
this project is about supplier and client management system when we login to client it is working perfect but when I log in to supplier it is throwing error... if we add more than one product in supplier list then it's not logging in that account again. only allowing 1 order . this is the model of my code. # models.py from django.contrib.auth.models import User from django.db import models from django.shortcuts import render, redirect,HttpResponse from django.contrib.auth.models import User from .models import * from django.contrib.auth import authenticate, login,logout from django.contrib.auth.decorators import login_required from django.contrib import messages from django.contrib.auth import authenticate, login class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=15) address = models.CharField(max_length=255) class Supplier(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product_name = models.CharField(max_length=255) product_price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='products/') from here views.py start of start of the code def signup(request): if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') Confirm_Password = request.POST.get('Confirm_Password') user_type = request.POST.get('role') if password != Confirm_Password: return HttpResponse("Your password and confirm password are not the same!!") elif User.objects.filter(email=email).exists(): return HttpResponse("Email Already Exist") # Create the user elif user_type == 'client': # ... existing code for client registration ... mobile = request.POST.get('mobile') address = request.POST.get('address') … -
Make dynamic imports of ts module absolute path in js using Webpack
I'm using Webpack as a bundler. My project contains .ts files with dynamic imports. And everything works just fine. But It is Django project and compressor doesn't see modules to which path is build dynamically. Is there a way to make webpack not build path to module but put it as full string in .js file? This is how it looks now: const obj = await import('../components/MyComponent/MyComponent'); In bundled js: const e = await r.e(3802).then(r.bind(r, 73802)); It is building a path to this module. And I would like to have it as an absolute path. Is there a way to do so?