Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django sitemap.xml shows plain text
I have added sitemaps following Django 2.0 (I cannot upgrade for now) official documentation. When accessing my production site I get all the correct links with dates but as plaintext, without xml formatting. The google search console is not accepting this format. My sitemap.py code: from blog.models import Post from django.contrib.sitemaps import Sitemap from courses.models import Course, Interview, Lesson class PostSitemap(Sitemap): changefreq = 'weekly' priority = 0.9 def items(self): return Post.objects.all() def lastmod(self, obj): return obj.updated ... My urls.py code: path( "sitemap.xml", sitemap, {"sitemaps": { "courses": CourseSitemap, "posts": PostSitemap, "lessons": LessonSitemap, "podcasts": InterviewSitemap, }}, name="django.contrib.sitemaps.views.sitemap", ), How can I change it to XML format? -
Websocket connection with uvicorn/django/nginx not working
I am trying to establish a websocket connection in my app but I'm getting different errors. I'm using elasticache redis cache and my settings.py looks as follows: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": ["rediss://redis-m0rn9y.serverless.use1.cache.amazonaws.com:6379"], }, }, } I've configured my channel_layers numerous times but this one allows me to establish a connection at least before it closes: Feb 26 23:54:37 ip-172-31-40-162 python[9623]: INFO: 128.6.36.223:0 - "GET /app/api/get_user_inventory/ HTTP/1.0" 200 OK Feb 26 23:54:38 ip-172-31-40-162 python[9623]: INFO: 128.6.36.223:0 - "GET /app/api/check_session/ HTTP/1.0" 200 OK Feb 26 23:54:38 ip-172-31-40-162 python[9623]: Not Found: /app/inventory/styles.css.map Feb 26 23:54:38 ip-172-31-40-162 python[9623]: Not Found: /app/inventory/styles.css.map Feb 26 23:54:38 ip-172-31-40-162 python[9623]: INFO: 128.6.36.223:0 - "GET /app/inventory/styles.css.map HTTP/1.0" 404 Not Found Feb 26 23:54:38 ip-172-31-40-162 python[9623]: INFO: ('128.6.36.223', 0) - "WebSocket /ws/inventory/" [accepted] Feb 26 23:54:38 ip-172-31-40-162 python[9623]: WebSocket connected to the group 'inventory'. Feb 26 23:54:38 ip-172-31-40-162 python[9623]: INFO: connection open Feb 26 23:54:38 ip-172-31-40-162 python[9623]: ERROR: Exception in ASGI application Feb 26 23:54:38 ip-172-31-40-162 python[9623]: Traceback (most recent call last): Feb 26 23:54:38 ip-172-31-40-162 python[9623]: File "/home/ubuntu/venv/lib/python3.10/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 255> Feb 26 23:54:38 ip-172-31-40-162 python[9623]: result = await self.app(self.scope, self.asgi_receive, self.asgi_send) Feb 26 23:54:38 ip-172-31-40-162 python[9623]: File "/home/ubuntu/venv/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 84, in __call__ Feb … -
Expose host port 80 of a Dockerized Django app deployed on AWS Fargate
I have a very simple Django rest framework (DRF) app that is dockerized and deployed on AWS ECS with Fargate. I created a security group to expose the port 8000 on the inbound rules and was able to see the app at public IP 12.34.56:78:8000/ I wanted to have the app run on port 80, but don't know how to. Do I need to expose 80 on the Dockerfile and specify that port when creating the task definition? Or do I need to set up nginx to pass HTTP requests to port 8000 internally? Dockerfile: # Pull base image FROM python:3.12 # Set environment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /app # Install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . # Expose the Django development server port EXPOSE 8000 # # Start the Django development server CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] Task definition: { "taskDefinitionArn": "arn:aws:ecs:us-west-1:123:task-definition/app-task:12", "containerDefinitions": [ { "name": "container-name", "image": "dockerhub/app:latest", "cpu": 0, "portMappings": [ { "name": "default", "containerPort": 8000, "hostPort": 8000, "protocol": "tcp", "appProtocol": "http" } ], "essential": true, "environment": [], "mountPoints": [], "volumesFrom": [], "logConfiguration": { "logDriver": "awslogs", "options": … -
Is there a way to temporarily remove items from a session and re-add after code has run
I am working on an e-commerce site, using Django. I am trying to add a custom order to the bag which is happening, however now I cannot add other products to the bag when the custom order is in the bag. I was thinking if I removed the custom_order from the session, it would allow the other code to run, in order to add products to the bag. context.py from decimal import Decimal from django.conf import settings from django.shortcuts import get_object_or_404 from products.models import Product from custom_order.models import CustomOrder def bag_contents(request): bag_items = [] total = 0 bag = request.session.get('bag', {}) print(bag) if 'custom_order' in bag: custom_order_id = bag['custom_order'] custom_order = CustomOrder.objects.get(pk=custom_order_id) total += custom_order.price bag_items.append({ 'product_id': custom_order.product_id, 'custom_order_id': custom_order_id, 'category': custom_order.category, 'material': custom_order.material, 'individual_total': custom_order.price, 'quantity': 1, 'product_name': custom_order.product_name }) else: for product_id, quantity in bag.items(): product = Product.objects.get(pk=product_id) if isinstance(quantity, int) and isinstance(product.price, Decimal): total += quantity * product.price individual_total = quantity * product.price product_count += quantity bag_items.append({ 'product_id': product_id, 'quantity': quantity, 'product': product, 'individual_total': individual_total, }) grand_total = total context = { 'bag_items': bag_items, 'grand_total': grand_total, } return context View to add product to bag def add_to_bag(request, product_id): """ Add a quantity of the specified product to … -
How to save multiple values from dropdown with foreign key
I want to save multiple store ids in Test table in store_id column. What is the best way to design model to save multiple store ids in Test table models.py class Store(models.Model): store_name = models.CharField(max_length=100, verbose_name="store") def __unicode__(self): return '%s' %(self.name) def __str__(self): return self.name class Test(models.Model): store_id = models.ForeignKey(Store, on_delete=models.CASCADE, db_column='store_id') def __unicode__(self): return '%s' %(self.id) Forms.py class TestForm(ModelForm): def __init__(self, *args, **kwargs): self.fields['store_id'] = ModelChoiceField(queryset=Store.objects.all(), widget=SelectMultiple(attrs={'class':'form-control'}) class Meta: model = Test fields = ('store_id',) -
How to setup cookiecutter-django to run functional tests with Selenium?
I am using Cookiecutter Django with Docker and Webpack. I'm struggling to use Selenium for functional tests with the way Cookiecutter Django template is set up. I have added a Selenium container: selenium_chrome: image: selenium/standalone-chrome:latest container_name: local_selenium_chrome ports: - '4444:4444' volumes: - /dev/shm:/dev/shm I am using Django StaticLiveServerTestCase in my functional test. This is launching a live Django server on a random port, which I can access like this: self.browser.get(self.live_server_url). However, the static files are missing (CSS and JS) because they are served from a node container in the Cookiecutter Django local setup. What is the correct way to update my Cookiecutter Django template to be able to run Selenium tests with full static assets available? -
Djangosaml2 implementation with azure SSO with an existing Django app having independent Login
I am a new comer in Django field. I have an existing Django application with independent login implemented. The task is to integrate Azure AD Single Sign On using SAML protocol. The flow is user request for application url, it will redirect to the Azure portal, Signed in using federated credential automatically and redirect to the requested url or a specific app url after authorize. I am using djangosaml2 librery. I am able to redirect to the Azure portal but while authenticating I am getting "csrf verification failed" error. Basically I have zero knowledge about how django authentication works and how to integrate the response from azure in django. Any one please help me out with a through walkthrough of the SSO authentication process with SAML. How to get the attributes from SAML and how to authenticate and authorize. My current project structure is given below. my-project templates app1 login home proj settings.py remote_xml_metadata.xml urls.py views.py app1 urls.py views.py` -
How to pass AWS ELB health check with Django ALLOWED_HOSTS = [my-site.com]
I have a Django application deployed on AWS via ECS (Dockerized) using gunicorn and nginx. As the DEBUG=False for Django deployment I've configured a logging setting to receive logs on WARNINGs & above via mail_admins. With a standard setup on nginx configuration (below) I started to receive tons of logs (mails) with 'BadRequest' or 'DisallowedHost' errors (most probably scanning/scraping bots) which were rejected by Django as I have set my ALLOWED_HOSTS=[my-site.com]. nginx.conf upstream django-backend { server 172.17.0.1:8000; } server { listen 80; location / { proxy_pass http://django-backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_redirect off; } } I followed examples from following solutions to block the traffic hitting my Django application: by @Brent O'Connor from here by @Janusz Skonieczny from here nginx docs here Having ultimately nginx.conf updated with: server { listen 80; server_name ""; return 444; } server { listen 80; server_name my-site.com; # Rest of configuration } This worked quite well, however, I couldn't setup the nginx in such way to allow AWS ELB to perform the Health check and I had following logs in AWS: xxx.xx.xx.xx - - [26/Feb/2024:19:30:03 +0000] "GET /health HTTP/1.1" 444 0 "-" "ELB-HealthChecker/2.0" "-" xxx.xx.xx.xx - - … -
Are there any best practices for handling arbirary rules by US State?
This question is incredibly hard to google because of what state means in software development. I am creating a web app that handles specific laws based on State. These laws often have nothing to do with each other on a State by State bases. For example if it was laws on food sales, one State might say "you can only sell ice cream on Tuesdays" and another might say "every receipt for vegetable sales must be green". Are there any best practices for arbitrary specific rules in a code-base? Obviously, I could throw if statements in for every use case but it will make the code super messy. I am thinking of creating a service class that can point to the State requirements for different from one location but will keep State logic separate from the core shared logic. For reference it is a pretty typical infrastructure with a React-based front-end, Django back-end and mysql DB. -
I'm having trouble verifying my reCAPTCHA
I have a project with django, and I have a signup template, in this I put a recaptcha so that when it is completed it validates it, but when I was testing, I filled out the form and it told me "reCAPTCHA error, try again later" So I have view: def signup(request): if request.method == 'GET': return render(request, 'signup.html', {'form': UserSignUpForm()}) else: form = UserSignUpForm(request.POST) if form.is_valid(): if verificar_recaptcha(request.POST.get('g-recaptcha-response')): if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user( username=request.POST['username'], password=request.POST['password1'], first_name=request.POST['first_name'], last_name=request.POST['last_name'], email=request.POST['email'] ) user.save() login(request, user) return redirect('mensaje') except IntegrityError: return render(request, 'signup.html', { 'form': UserSignUpForm(), 'error': 'El usuario ingresado ya se encuentra registrado' }) else: return render(request, 'signup.html', { 'form': UserSignUpForm(), 'error': 'Las contraseñas no coinciden' }) else: return render(request, 'signup.html', { 'form': UserSignUpForm(), 'error': 'Error de reCAPTCHA. Por favor, inténtalo de nuevo.' }) else: return render(request, 'signup.html', {'form': form}) I have another file that does the verification import requests def verificar_recaptcha(token): secret_key = 'secretkey' url = 'https://www.google.com/recaptcha/api/siteverify' payload = { 'secret': secret_key, 'response': token } response = requests.post(url, data=payload) data = response.json() if data['success']: return True else: return False I tried changing the views but nothing happens. -
from django.urls import path ImportError: cannot import name 'path' from 'django.urls'
I am very beginner in Python. I have project in Python 3.8 and Django. When I try update my old Django to Django 1.11 i have error: ** from django.urls import path ImportError: cannot import name 'path' from 'django.urls' (/home/ds/.local/lib/python3.9/site-packages/django/urls/init.py)** My file: from django.urls import path from django.contrib.auth.views import login from .views import * urlpatterns = ['', path(r'^$', 'go.insurance.views.index'), path(r'^abc/', include('go.abc.urls')), path(r'^help/', include('go.help.urls')), path(r'^robots\.txt$', TemplateView.as_view(template_name='robots.txt')), ] if settings.DEBUG: urlpatterns += ['', path(r'^media/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), ] What i make: update: requirements/base.txt => Django==1.11.29 /mnt/c/Project/.venvs/bin/python3 -m pip install --upgrade pip /mnt/c/Project/.venvs/bin/pip3 install django==1.11 /.venvs/bin/python3 manage.py runserver in folder requrements When i run my app i have error: ./.venvs/bin/python3 manage.py runserver I have error: Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x7fdc2c9b91f0> Traceback (most recent call last): File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/core/management/base.py", line 356, in check all_issues = self._run_checks( File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/utils/functional.py", line 35, … -
TemplateDoesNotExist at Django python issue
I am new to Python and trying work on Django framework! as a basic I am trying to fetch values from HTML but I am getting the error "TemplateDoesNotExist at" My code is : def home(request): return render(request,'/templates/home.html') path of the file shown in this image is i am giving wrong path ? -
Django Content-Disposition not working as expected
I'm trying to build a functionality with Django, Gunicorn and Nginx where a user can request for a pdf download by submitting their email, after which a custom download link will be sent to their email. Clicking on the custom link should prompt the user to download the pdf. However, I keep getting "Page not found error". Below is my models.py file: from django.db import models import string import random class BrochureToken(models.Model): email = models.EmailField(blank=True) token = models.CharField(max_length=20, unique=True) # Random token is_used = models.BooleanField(default=False) # Flag to track if the token has been used def generate_token(self): length = 20 chars = string.ascii_letters + string.digits self.token = ''.join(random.choice(chars) for _ in range(length)) def save(self, *args, **kwargs): # Generate token before saving if it's not already set if not self.token: self.generate_token() super().save(*args, **kwargs) def __str__(self): return self.email Below is my views.py file: class BrochreRequest(generics.CreateAPIView): queryset = BrochureToken.objects.all() serializer_class = BrochureSerializers permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = BrochureSerializers(data=request.data) if serializer.is_valid(): print("Serializer is valid") serializer.save() email = request.data.get("email") token, created = BrochureToken.objects.get_or_create(defaults={'email': email}) download_link = f'https://api.mysite.com/api/filedownload/brochure/{token.token}' send_mail( 'Download The OIC Brochure', f'Click the link to download the brochure: {download_link}', settings.EMAIL_HOST_USER, [email], fail_silently=False ) return Response(serializer.data, status = status.HTTP_200_OK) else: return … -
Can we make copy of a static file in Django?
My requirement is to write into a sample excel (static) file, and download the copied static file in the device. The copy is required cause the sample file contains some formatting, which I need in the downloaded file as well. Directory Structure : Django Project - project - app - static - files -> sample.xlsx - css - js - manage.py Now, I need to create a copy of sample.xlsx file, write some details in it and download it. I've tried below code, in which I am creating a new file and copying the content from sample.xlsx to new_file.xlsx . But it does not copy the formatting from sample.xlsx def exportXLS(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="new_file.xlsx"' sample = load_workbook(sample_file_path) #opening sample.xlsx active_sheet = sample.worksheets[0] new_workbook = Workbook() #creating new excel file worksheet = wb.active worksheet.title = "Sheet Name" mr = active_sheet.max_row mc = active_sheet.max_column #copying values from sample.xlsx to new_file.xlsx for i in range (1, mr + 1): for j in range (1, mc + 1): c = active_sheet.cell(row = i, column = j) worksheet.cell(row = i, column = j).value = c.value new_workbook.save(response) return response ==> I would like to make a COPY of sample.xlsx first then write … -
Using Arrays vs Temp Tables for a user session
I am prototyping an event system app for a local organization. They are logging into the site and then API calls use their entered login info to retrieve information from other apps. The goal is to not store any long term "user data" since that is stored in the other apps. (by user data, I mean stuff for logins/settings/etc since its stored in those other apps). The info retrieved from the API calls is displayed to the user but is only needed for the length of the registration process. Once the user registers for the event, the data gotten from the API calls and such should be deleted and the only data saved long term is the data that makes its way to the separate event registration table. Is it better to do a temp table or to store the temporary information in a session variable/array? We are only anticipating maybe 500 concurrent users. -
GeoDjango endpoint is extremely slow
I'm trying to work with a list of 1.100 rows loaded in a PostgreSQL with PostGIS extension. Each row has the following fields: code (integer) name (char) mpoly (multipolygon) The idea is to have an endpoint that will be called from a VueJS app to print each geo data in a Leaflet managed map. The query is extremely slow when serializing it. How can I optimize it? I thought about having a geojson file, but each row has a manytomany table associated that indicate some groups that it belongs to. -
Problem RSA cryptographie in python [django]
I've following code in python, django, to share symetric cryptographie for encrypt/decrypt files, using RSA cryptographie, i can allready create RSA keys and store them in the member model, also I'm able to create the securit_key_relations, but then the private_key_relation in member model is empty, I tried everything and don't know why. models.py class Member(models.Model): private_key=models.TextField(blank=True, null=True) public_key=models.TextField(blank=True, null=True) private_key_relation=models.TextField(blank=True, null=True) dc_verification=models.CharField(max_length=50, blank=True, null=True) id=models.AutoField(primary_key=True) permission=models.TextField(default="") mma_classification=models.IntegerField(default=1) firstname=models.CharField(max_length=30, null=True) lastname=models.CharField(max_length=30, null=True) username=models.CharField(max_length=30, null=True, unique=True) password=models.CharField(max_length=1000, null=True) agentnr=models.CharField(max_length=11, null=True, unique=True) bezlogged=models.CharField(max_length=20, null=True) frei=models.BooleanField(default='FALSE') email=models.EmailField(max_length=50) code=models.CharField(max_length=50, null=True, unique=True) verify=models.BooleanField(default=False) ort=models.CharField(max_length=50, null=True) bereitschaftsort=models.CharField(max_length=50, null=True) land=models.CharField(max_length=4, default='ENG') phonenumber=models.CharField(max_length=20, default='0000000000') kategorie=models.CharField(max_length=9, default='agent') benachrichtigt=models.BooleanField(default='FALSE') abteilung=models.CharField(max_length=30, null=True) einsatztag=models.CharField(max_length=30, default='agent') status=models.CharField(max_length=1, default='5') api_user=models.BooleanField(default='False') dc_tag=models.CharField(max_length=100, null=True) support=models.CharField(max_length=100, default="no_support") prioritaet=models.CharField(max_length=1, default="1") pefw=models.BooleanField(default=False) device_code=models.TextField(default="X", max_length=1000) device_id=models.CharField(max_length=100, default='X') def __str__(self): return self.firstname + " " + self.lastname class security_key_rel(models.Model): id=models.AutoField(primary_key=True) gmid=models.TextField(blank=True, null=True) key=models.TextField(blank=True, null=True) purpose=models.TextField(blank=True, null=True) ` views.py `def byte_to_string(byte_obj): return byte_obj.decode('utf-8') def string_to_byte(string_obj): return string_obj.encode() def encrypt_file(filename, key): key = string_to_byte(key) f = Fernet(key) with open(filename, 'rb') as file: file_data = file.read() encrypted_data = f.encrypt(file_data) os.remove(filename) with open(filename, 'wb') as file: file.write(encrypted_data) def decrypt_file(filename, key): key = string_to_byte(key) f = Fernet(key) with open(filename, 'rb') as file: encrypted_data = file.read() decrypted_data = f.decrypt(encrypted_data) os.remove(filename) with open(filename, 'wb') as file: file.write(decrypted_data) def generate_RSA_key(): … -
Why is Heroku returning a 500 server error when Django DEBUG is set to False?
Working locally, I'm able to visit mysite.com. Hosted on Heroku, I'm only able to access mysite.com if I have DJANGO_DEBUG set to True in my config vars. The following is my settings.py file: from pathlib import Path import os from dotenv import load_dotenv import dj_database_url import django_heroku load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False' ALLOWED_HOSTS = ['myprojectwebsite.herokuapp.com', 'www.mysite.com', 'mysite.com', 'localhost', '127.0.0.1'] INSTALLED_APPS = [ 'myprojectwebsite', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_google_fonts', 'django.contrib.sitemaps', ] 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 = 'myproject.urls' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'detailed': { 'format': '{levelname} {asctime} {module} {message} {pathname}:{lineno}', 'style': '{', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'detailed', }, }, 'loggers': { 'script_logger': { 'handlers': ['console'], 'level': 'DEBUG', }, }, } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], # Global templates folder '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', 'django.template.context_processors.media', 'myprojectwebsite.context_processors.resorts_by_location', ], }, }, ] WSGI_APPLICATION = 'myproject.wsgi.application' if DEBUG: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', … -
Unable to split text received as POST request in django
i am facing a weird error. I am trying to split text sent via form in django. Here is my code in django from transformers import AutoTokenizer from langchain.text_splitter import CharacterTextSplitter tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased-finetuned-sst-2-english" ) text_splitter = CharacterTextSplitter.from_huggingface_tokenizer( tokenizer, chunk_size=256, chunk_overlap=0 ) def home(request): if request.method == 'POST': input_text = request.POST['input'] # Get input text from the POST request print("input_text",type(input_text)) splitted_text = text_splitter.split_text(str(input_text)) print("splitted_text_length_outside",len(splitted_text)) The length is always 1, which mean text is not split. I have checked that i am receiving text from html form and the type of text is str. But when i use the same code outside of django such as in jupyter notebook, it work well and split the text. In django I tried input_text.split() and that worked. But i am clueless why the langchain text splitter is not working. def home(input_text): splitted_text = text_splitter.split_text(input_text) print("splitted_text_length_outside",len(splitted_text)) Here is my html form <form action="{% url 'home' %}" method="post" id="myForm"> {% csrf_token %} <textarea name="input" id="input" rows="4" cols="50"></textarea> <br> <button type="submit">Submit</button> </form> Here is my ajax code $("#myForm").submit(function(event) { event.preventDefault(); let formData = $(this).serialize(); $.ajax({ "url": "/", "type": "POST", "data": formData, "success": function(response) { console.log("success"); }, "error": function(error) { console.log("error",error); } }); }); -
How to solve Model class django.contrib.contenttypes.models.ContentType
RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. And LookupError: No installed app with label 'admin'. Are the Errors i am facing so please help me to solve both. Error is Traceback (most recent call last): File "A:\Projects\ePlant\eplant_dj\manage.py", line 22, in <module> main() File "A:\Projects\ePlant\eplant_dj\manage.py", line 18, in main execute_from_command_line(sys.argv) File "A:\Projects\ePlant\venv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "A:\Projects\ePlant\venv\Lib\site-packages\django\core\management\__init__.py", line 382, in execute settings.INSTALLED_APPS File "A:\Projects\ePlant\venv\Lib\site-packages\django\conf\__init__.py", line 89, in __getattr__ self._setup(name) File "A:\Projects\ePlant\venv\Lib\site-packages\django\conf\__init__.py", line 76, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "A:\Projects\ePlant\venv\Lib\site-packages\django\conf\__init__.py", line 190, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ateyu\AppData\Local\Programs\Python\Python312\Lib\importlib\__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 995, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "A:\Projects\ePlant\eplant_dj\eplant_dj\settings.py", line 11, in <module> from account.authentication import CustomJWTAuthentication File "A:\Projects\ePlant\eplant_dj\account\authentication.py", line 1, in <module> from rest_framework_simplejwt.authentication import JWTAuthentication File "A:\Projects\ePlant\venv\Lib\site-packages\rest_framework_simplejwt\authentication.py", line 4, in <module> from django.contrib.auth.models import AbstractBaseUser File "A:\Projects\ePlant\venv\Lib\site-packages\django\contrib\auth\models.py", line 5, in <module> from django.contrib.contenttypes.models import ContentType File "A:\Projects\ePlant\venv\Lib\site-packages\django\contrib\contenttypes\models.py", line 139, in <module> class ContentType(models.Model): … -
Save the current user when saving a model in Django admin backend
I'd like to store the user that saved a model for the first time in one of the fields of that model. This is what I have. models.py: from django.conf import settings class Project(models.Model): [...] added_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.PROTECT) def save_model(self, request, obj, form, change): if not obj.pk: obj.added_by = request.user super().save_model(request, obj, form, change) settings.py: AUTH_USER_MODEL = 'auth.User' The request.user appear to be always empty (I'm logged in as root to the /admin). What am I missing? -
Django+Nginx having issue with SSE
I made an API on django rest framework, I have SSE via django-eventstream Deployed everything on the server (django in docker), wrote a config for nginx But for some reason the SSE query does not work, everything else works I even added print to the function from the module to check if the request reaches the api, everything is ok But in the postman there is an endless sending of the request, although I checked locally - everything worked Nginx conf location /events/orders/ { proxy_pass http://172.23.0.3:8005/events/orders/; proxy_set_header Host $host; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_buffering off; proxy_set_header Content-Type text/event-stream; proxy_cache off; proxy_buffers 8 32k; proxy_buffer_size 64k; } ASGI os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sushi_api.settings') application = get_asgi_application() -
Where the actual db fetch is done in drf list()
As you may know the querysets do the actual fetch data only when you evaluate them for ex iterating over them. I want to put that actual fetch inside celery so I need to catch the method in which that actual fetch data from db happens during drf lifecycle. what is it? I'm diving in drf source code but since I have not much time any help is appreciated. -
Social Authentication (dj_rest_auth) with multiple role user
#user_model: class User(AbstractUser, PermissionsMixin): class Role(models.TextChoices): SELLER = "seller" BUYER = "buyer" SUPER = "super" name = models.CharField(max_length=100) phone = models.CharField(max_length=15) email = models.EmailField() created_at = models.DateTimeField(default=timezone.now) shipping_address = models.CharField(max_length=100, blank=True, null=True) role = models.CharField( max_length=100, default=Role.SELLER.value, choices=Role.choices ) updated_at = models.DateTimeField(default=timezone.now, null=True) first_name = None last_name = None profile_picture = models.ImageField( default="profile 1.jpg", upload_to="profile_images" ) is_staff = models.BooleanField(default=False) is_blocked = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) username = models.CharField(max_length=30, unique=True) USERNAME_FIELD = "username" REQUIRED_FIELDS = ["email", "name", "role"] objects = myUserManager() class Meta: unique_together = [("email", "role"), ("phone", "role")] ordering = ["id"] db_table = "users" I've implemented dj_rest_auth with Google Authentication, and it functions as intended. However, a limitation arises wherein it only supports users with a single role. For instance, if we create a user with the role of seller, it successfully creates an account and logs in the user. However, if we attempt to log in with a user role such as buyer, it erroneously returns the seller user and logs them in instead. #CustomSocialLoginSerializer: import requests from allauth.socialaccount.models import SocialAccount from dj_rest_auth.registration.serializers import SocialLoginSerializer from django.contrib.auth import get_user_model from django.core.files.base import ContentFile from rest_framework import serializers from rest_framework.response import Response User = get_user_model() class CustomSocialSerializer(SocialLoginSerializer): … -
Django The custom permissions granted in the admin site do not work
I created permissions for the drop-down list, gave the user permissions for the drop-down list on the administration page, so that after logging in he could see only item 1 and item 2. After logging in, the list is empty, no item is displayed. models.py from django.db import models class Main(models.Model): positions = [ ('1', 'Position 1'), ('2', 'Position 2'), ('3', 'Position 3'), ] drop_down = models.CharField(max_length=1, choices=positions) text = models.CharField(max_length=255, blank=True, null=True) forms.py from django import forms from .models import Main class main_input(forms.ModelForm): class Meta: model = Main fields = ['drop_down', 'text'] def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(main_input, self).__init__(*args, **kwargs) self.fields['drop_down'].choices = [] if self.user and self.user.has_perm('portal.can_see_position_1'): self.fields['drop_down'].choices.append(('1', 'Position 1')) if self.user and self.user.has_perm('portal.can_see_position_2'): self.fields['drop_down'].choices.append(('2', 'Position 2')) if self.user and self.user.has_perm('portal.can_see_position_3'): self.fields['drop_down'].choices.append(('3', 'Position 3')) class LoginForm(forms.Form): username = forms.CharField(max_length=50) password = forms.CharField(widget=forms.PasswordInput) views.py ct = ContentType.objects.get_for_model(Main) for position in Main.positions: codename = f'can_see_{position[1].replace(" ", "_").lower()}' name = f'Can see {position[1]}' if not Permission.objects.filter(codename=codename, content_type=ct).exists(): permission = Permission.objects.create(codename=codename, name=name, content_type=ct) @login_required(login_url='login') def view_input(request): if request.method == 'POST': form = main_input(request.POST or None, user=request.user) if form.is_valid(): symbol = form.cleaned_data['text'] if form.cleaned_data['drop_down'] == '1': return employee() return employee_csv(symbol) else: form = main_input(user=request.user) return render(request, 'index.html', {'form': form}) I've run …