Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Model Creation Freezing Django (or Django Rest Framework)
I have this model: class AllowedUser(models.Model): PLACE_CHOICES = ( (1, 'Loc1'), (2, 'Loc2'), (3, 'Loc3'), (4, 'Loc4'), (5, 'Loc5'), ) id = models.CharField(primary_key=True, max_length=8, unique=True, default=generate_unique_id) name = models.CharField(max_length=60) place = models.IntegerField(choices=PLACE_CHOICES) current_version = models.CharField(max_length=8, default="0.0.1") last_updated = models.DateTimeField(default=datetime.datetime(1970,1,1,0,0,0)) def __str__(self): return self.id + ' - ' + self.name And when I try it in shell, or even in runtime with DRF, it just does nothing. In DRF, it stops with no error right after serializer.save(), in Shell it freezes (not actually freeze, but waits for something) right after AllowedUser(...Data...). I'm using SQLite3 as database. I actually don't know what's the root problem here. Anyone got an idea on what's causing it to hold? Thanks in advance. -
How do I get return value on different color in front end
I have backend code written in python where it returns a number, I want to show the number in different color for certain threshold. For example if the number is 15 and above it should show in red color Here is the code: def zulu_extracts(weather_input,datis=None): # This could be work intensive. Make your own conversion if you can avoid using datetime raw_utc = Root_class().date_time(raw_utc='HM')[-4:] raw_utc_dt = datetime.strptime(raw_utc,"%H%M") if datis: zulu_item_re = re.findall('[0-9]{4}Z', weather_input) else: zulu_item_re = re.findall('[0-9]{4}Z', weather_input) if zulu_item_re: zulu_weather = zulu_item_re[0][:-1] zulu_weather_dt = datetime.strptime(zulu_weather,"%H%M") diff = raw_utc_dt - zulu_weather_dt diff = int(diff.seconds/60) return diff else: zulu_weather = 'N/A' return zulu_weather The front end is based on html,css and JS I already searched on google and tried chat GPT but nothing seems to work -
Does Django formsets prevent editing hidden fields with id?
Formset is created with modelformset_factory and uses regular ModelForm, I'm also using django-crispy-forms. Why modifying form-X-id hidden field value from A to B (both A and B ids exist in database) does not modify that record? Inside view form_valid method I can see that field value is B, so I would expect that record A attributes would be the same as record B, but thankfully it does not happen, instead view proceeds as if nothing went wrong, why is that? -
Why are Django related object queries not cached?
I have the following unit test: def test_cache(self): with self.assertNumQueries(1): print(database.records.all()) print(database.records.all()) print(database.records.all()) The test fails because 3 queries are made: Captured queries were: 1. SELECT "store_record"."id", "store_record"."key", "store_record"."database_id", "store_record"."user_id", "store_record"."organization_id", "store_record"."data", "store_record"."created_at", "store_record"."updated_at" FROM "store_record" WHERE "store_record"."database_id" = '7d86d143-9e4e-4420-801c-3d3c5e6875fb'::uuid LIMIT 21 2. SELECT "store_record"."id", "store_record"."key", "store_record"."database_id", "store_record"."user_id", "store_record"."organization_id", "store_record"."data", "store_record"."created_at", "store_record"."updated_at" FROM "store_record" WHERE "store_record"."database_id" = '7d86d143-9e4e-4420-801c-3d3c5e6875fb'::uuid LIMIT 21 3. SELECT "store_record"."id", "store_record"."key", "store_record"."database_id", "store_record"."user_id", "store_record"."organization_id", "store_record"."data", "store_record"."created_at", "store_record"."updated_at" FROM "store_record" WHERE "store_record"."database_id" = '7d86d143-9e4e-4420-801c-3d3c5e6875fb'::uuid LIMIT 21 Why is the records field not cached? What is telling Django to do refetch the data from the database? -
File path not saved in database, but it is in storage. Collision? Django rest framework
Hey im trying to handle file upload with use of celery tasks. However after all tasks complete, file appears to be in storage and not in database when i query /files. Thumbnail (which is generated as second task, but is much faster) is both saved in storage and database. What could be the issue? views.py @extend_schema( description="Upload file", request=FileSerializer, responses={201: FileSerializer}, ) def post(self, request, *args, **kwargs): file = request.data["file"] total_sum = File.objects.filter(owner=request.user).aggregate(models.Sum("size")) total_sum = total_sum["size__sum"] if total_sum["size__sum"] else 0 if total_sum + file.size > request.user.storage_limit: return Response( {"error": "Storage limit exceeded"}, status=status.HTTP_400_BAD_REQUEST ) request.data["size"] = file.size serializer = FileSerializer(data=request.data) if serializer.is_valid(): serializer.save(owner=request.user, size=file.size) FileService.upload_file(serializer.data["id"], file.read(), file.content_type) return Response(serializer.data, status=status.HTTP_202_ACCEPTED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) services.py import base64 import mimetypes from common.service import Service from storage.tasks import UploadHandler, ThumbnailHandler class FileService(Service): # Service is empty class, just class Service: ... handlers = [UploadHandler, ThumbnailHandler] handler = handlers[0]() for next_handler in handlers[1:]: handler.set_next(next_handler()) @staticmethod def get_file_extension(mimetype: str): return mimetypes.guess_extension(mimetype) @staticmethod def upload_file(file_id: str, file: bytes, mimetype: str): file_bytes = base64.b64encode(file) extension = FileService.get_file_extension(mimetype) FileService.handler.handle((file_id, extension, file_bytes)) tasks.py import base64 from celery import shared_task from django.conf import settings from django.core.files.base import ContentFile from services.grpc_client import Client from common.chain import AbstractHandler from storage.models import File … -
Django ORM groupby
row_1(PK) row_2 row_3 1 row one 2 row two 3 row three Data from my database table looks like the above table. SELECT GROUP_CONCAT(row_3) FROM table_ WHERE row_2 = 'row' GROUP BY row_2; My Django query to achieve above mysql query table_.objects.filter( row_2='row' ).annotate( val=GroupConcat('row_3', '') ).values('val') When converting the above ORM to raw mysql query, it's grouing by primary key (row_1). I want to group by 'row_2' column . -
How to get the image path when applying UUID to the image file name
I've implemented a function that applies a UUID-based name to images in my Django project. The function is used as the 'upload_to' parameter for the ImageField in my 'Image' model. Here's the code: models.py def image_file_path(instance, filename): """Generate file path for new image""" ext = os.path.splitext(filename)[1] filename = f'{uuid.uuid4()}{ext}' return f'{instance.category.name}-{filename}' class Image(models.Model): """Image model""" user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) category = models.ForeignKey('category', on_delete=models.PROTECT, null=False, blank=False) image = models.ImageField( upload_to=image_file_path, null=False, blank=False ) results = models.TextField(default=None) created_at = models.DateTimeField(auto_now_add=True) def calculate_results(self): from .preprocessing.brain.preprocess_image import get_image_results print("Image URL:", self.image) # Returns the original image name self.results = get_image_results(self.image.path, target_size=(150, 150)) return self.results def __str__(self): return f"{self.category.name}-{self.created_at}" views.py @method_decorator(login_required(login_url='login'), name='dispatch') class CreateImageView(CreateView): model = Image form_class = ImageForm template_name = 'home.html' success_url = reverse_lazy('upload_homepage') def form_valid(self, form): form.instance.user = self.request.user form.instance.calculate_results() return super().form_valid(form) templates/home.html {% if image %} <img src="/static/media/{{ image.url }}"> {% endif %} However , when I try to access image.url in the home.html, I retrieve the original image name upon upload, not the one with the newly generated UUID. How can I modify this to obtain the correct name to display in the template? -
Slack message is not getting sent when python code is connected to celery
I have created a django project to upload articles. In that I have created a functionality where if the user did not upload article before 11:00 a.m. a message will be sent on slack to upload the article. The problem is that if I do not add the task to celery and execute it independently it works. But when combined with celery it does not. The celery worker gives message : [2024-02-06 20:49:49,015: INFO/MainProcess] Task account.tasks.check_articles_and_send_slack_message[fdc4f121-f123-4697-85c2-ce2bb57e6004] received [2024-02-06 20:49:49,017: INFO/MainProcess] Task account.tasks.check_articles_and_send_slack_message[fdc4f121-f123-4697-85c2-ce2bb57e6004] succeeded in 0.**strong text** but still no slack message is sent. This is the tasks.py which is in the accounts app: from celery import shared_task from django.utils import timezone from slack_sdk import WebClient from slack_sdk.errors import SlackApiError from writer.models import Article @shared_task def check_articles_and_send_slack_message(): articles = Article.objects.filter(date_posted__date=timezone.now().date()) for article in articles: if article.date_posted.time() < timezone.time(11, 0, 0): send_slack_message(article.user) def send_slack_message(user): client = WebClient(token='dummy-token') try: response = client.chat_postMessage( channel='#qa', text=f"Hi @{user.first_name}, please upload your article before 11:00 a.m. today." ) print("Slack message sent successfully") except SlackApiError as e: print(f"Error sending Slack message: {e.response['error']}") This is my celery.py which is in the project called cron: from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab … -
how to fetch data multiple times in React
I've been working a full stack app, in frontend I am using react,and for Backend I am using Django.... what I want to do is when the user login it will automatically render all the posts for users he is following, I got three models, Post, User, Following first I must fetch data to get all followings id's , and then I must fetch data again to get all Posts that is related to the followings ,, I tried to do this: Home.js const [following,setFollowing]=useState([]); const getFollowing = async()=>{ if(authToken){ console.log("TOKEN : ",authToken.access); try{ let response= await fetch(`${BASE_URL}profile/following/`,{ method:"GET", headers:{ "Content-Type":"application/json", "Authorization":`Bearer ${authToken.access}`, } }) let data= await response.json() setFollowing(data) }catch(error){ console.log(error); } } //for getting posts const getPost= async (num)=>{ let response= await fetch(`${BASE_URL}post/${num}`,{ method:"GET", headers:{ "Authorization":`Bearer ${authToken.access}`, "Content-Type":"application/json" }, }) let data= await response.json() console.log("Fetched Posts : ", data); } //loop to fetch all posts const getAllPosts=()=>{ let values=Object.values(following) values.map(value=>( posts.push(value[Object.keys(value)[0]]) )) var arrayLength=posts.length-1 while(arrayLength=>0){ getPost(posts[arrayLength]) arrayLength-=1 }} what I don't undersatand is how to fetch data multiple times, like if I have followings id's=[4,3] how to send them to getPost method -
Django application handling for multiple tabs
I have a django based application integrated with login. When I open the application for the first tab and login, this tab logs out automatically when the application is opened in another tab of the same browser. When the sessions created for each tab is separate, why this logs out the old tabs. And the behaviour is not consistent too. I tried to add the settings SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_SAVE_EVERY_REQUEST = True and this seems to be not working -
Django tables2: Skipping object from queryset possible?
A database table contains a column "body" of type "text". This column contains valid JSON data. Displaying data from this table using django-tables2 should skip objects depending on JSON elements in this text field. This filter is obviously not possible using the usual Django QuerySet mechanisms. Therefore, I want to skip an object before rendering it into the table. Something like "before_render_row()" with the possibility to e.g. "return None" to skip the object. Is there any possibility to do that? Thanks! -
How to Speed Up Aggregation in Django
I have a pretty complex query I am running for a Trial Balance report that gathers current and prior debit and credit amounts and aggregates the Sum. In Django I use the ORM to create the query, and it takes about 5-6 seconds to load. I was figuring this was an ORM thing, and attempted the pure SQL in PGAdmin and the time for the query is the same, I am trying to see how I can improve the speed. Note I have indexes on date_entered, property, and is_voided so this should not be a bottleneck. There are also over a million rows in the table being queried. Here is the SQL: SELECT "accounting_glaccount"."deleted", "accounting_glaccount"."date_entered", "accounting_glaccount"."last_update", "accounting_glaccount"."uuid", "accounting_glaccount"."deleted_by_cascade", "accounting_glaccount"."id", "accounting_glaccount"."account_name", "accounting_glaccount"."account_identifier", "accounting_glaccount"."sortable_account_identifier", "accounting_glaccount"."account_type", "accounting_glaccount"."account_designation", "accounting_glaccount"."balance_type", "accounting_glaccount"."report_type", "accounting_glaccount"."report_designation", "accounting_glaccount"."description", "accounting_glaccount"."last_edited_by_id", "accounting_glaccount"."submitted_by_id", ( SELECT SUM(U0."credit_amount") AS "aggregation" FROM "accounting_generalledger" U0 WHERE ((U0."date_entered")::date >= '2024-02-06'::date AND (U0."date_entered")::date <= '2024-02-06'::date AND U0."property_id" = 20 AND NOT U0."is_voided" AND U0."account_id" = ("accounting_glaccount"."id") AND U0."deleted" IS NULL) GROUP BY U0."account_id" ) AS "current_credit", ( SELECT SUM(U0."debit_amount") AS "aggregation" FROM "accounting_generalledger" U0 WHERE ((U0."date_entered")::date >= '2024-02-06'::date AND (U0."date_entered")::date <= '2024-02-06'::date AND U0."property_id" = 20 AND NOT U0."is_voided" AND U0."account_id" = ("accounting_glaccount"."id") AND U0."deleted" IS NULL) GROUP BY … -
Django model if constructor called with None then set to chosen value
I have: class Scanned(models.Model): time = models.DateTimeField(default=datetime.now(timezone.utc), null=False) and in my unit tests I have instantiations of the form: Scanned(time=None) I would like to have that instantiation set the time value to datetime.now(timezone.utc) I have tried: time = models.DateTimeField(auto_now_add = True) and time = models.DateTimeField(auto_now = True) I also looked at validators but could not find a way to pass datetime.now() as the value if None. -
LOGOUT_REDIRECT_URL doesn't redirect to the desired page
I'm new to Django and run to the problem that I want to logout from an account by one click using 'django.contrib.auth.urls'. Here is my 'urls.py' path("accounts/", include('django.contrib.auth.urls')), home.html {% if user.is_authenticated %} <p>Hi, {{ user.username }}</p> <p><a href="{% url 'logout' %}">Log out</a></p> {% else %} <p>You are not logged in</p> <p><a href="{% url 'login' %}">Log In</a></p> {% endif %} settings.py LOGOUT_REDIRECT_URL = "home" LOGIN_REDIRECT_URL = "home" I know that by default I should be redirected to /accounts/logout, when I click on href link, but I set LOGOUT_REDIRECT_URL to home. LOGIN_REDIRECT_URL = "home" on the other hand works perfectly I read a lot of topics on this problem but none of the solutions helped me I tried setting path manually. It worked in a sense that it I stayed at the same page, but I didn't log out from my account path('', auth_views.LogoutView.as_view(next_page=settings.LOGOUT_REDIRECT_URL), name='logout'), -
Why in Django the post method considers an empty form and returns the code 200?
When the blank form is sent. Instead of skipping the conditions and rendering the same form. Instead, it returns an empty form and gives code 200 class ContactView(View): def get(self, request): form = ContactModelForm() return render(request, 'contact/contact_us.html', {'forms': form}) def post(self, request): if request.method == 'POST': form = ContactModelForm(request.POST) if form.is_valid(): form.save() return redirect('home') form = ContactModelForm() return render(request, 'contact/contact_us.html', {'forms': form}) -
How to allow public url access to Ubuntu Server installed in windows 10 as subsystem and using Ngnix with a Python Django & VueJS app
I have successfully installed Ubuntu 22.04.6 on Windows 10 as a subsystem. I have an app which runs with Python, Django, VueJS, Postgres using Nodejs. I am using Ngnix Web Server and am able to get the "Welcome to Nginx!" message. I have managed to get the app running on local ip http://127.0.0.1:8000. I am stuck at getting the app running using the public ip for remote access. I don't have a domain name. I am hoping to use my Windows 10 PC as a web server till the time the app gets completely tested and functional. I have followed steps as shown in: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04 The connection code is as below: /etc/systemd/system/gunicorn.socket: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=bitrun Group=www-data WorkingDirectory=/home/bitrun/SAFE_ERP ExecStart=/home/bitrun/SAFE_ERP/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ SAFE_ERP.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-available/SAFE_ERP: server { listen 80; server_name 103.122.201.91; location = /static/favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/bitrun/SAFE_ERP; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } ufw status: To Action From -- ------ ---- 80/tcp ALLOW Anywhere 80 ALLOW Anywhere 443 ALLOW Anywhere 8000/tcp ALLOW Anywhere Nginx Full ALLOW Anywhere 8000 ALLOW … -
How To Get Netbox Plug-in Specific Filterset Values?
I’m building a Netbox plug-in, and have a filter form that looks the way that I want. But I want to give the user drop down options for each of the fields with the specific options that are available, and am unsure how to restrict the options to specific fields. I found a way to show options via drop-down, but it doesn’t show the options specific for that field. It works so that if there are 20 fields for value D, but 30 total values (10 aren’t present), how would I build the filterset to only get those 20 values? What about if they are foreign keys? -
How to return only one value in the field and not all the values in the django table?
I want only one representative of each telegram to be shown, and not all the tuples Where it is marked all the values from the messega bot table appear, if you have 50 tuples from the same Telegram group then you would have 50 options for you to choose from. How do you ensure there is only one representative? Example: 5X Group x, id =1; 10X Group y, id =2; but only one of each appears: Group x, id =1; Group y, id =2; code: class MessageBot(models.Model): chat_id = models.BigIntegerField() chat_group = models.CharField(max_length=30) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=60) date = models.DateTimeField(auto_now_add=True) messageUser = models.TextField() self.client = client super().save(*args, **kwargs) def __str__(self): return f"{self.chat_id} - {self.chat_group}" class MainGroup(models.Model): client = models.ForeignKey(Client, on_delete= models.CASCADE) telegram = models.ForeignKey('MessageBot', on_delete= models.CASCADE, null=False) def __str__(self): return f"{self.telegram}" -
nginx blocks outgoing requests
The situation: I launched django and nginx via docker-compose on ubuntu vps hosting. nginx supports ports 80 and 443. The project opens by domain and redirects to https. Problem: Endpoints that send requests to other servers (to remote APIs) do not work. After sending, there is always a waiting timeout. Here are some settings: #nginx.conf user nginx; worker_processes 1; events { worker_connections 1024; } http { upstream app { server backend:8000; } server { listen 80; server_name eternitydigital.ru; return 301 https://$host$request_uri; } server { listen 443 ssl; server_name eternitydigital.ru; ssl_certificate /etc/nginx/ssl/certs/cert.crt; ssl_certificate_key /etc/nginx/ssl/private/private.key; location / { proxy_pass http://backend:8000; } } } #Dockerfile nginx FROM nginx:1.10.2 COPY nginx.conf /etc/nginx/nginx.conf CMD ["nginx", "-g", "daemon off;"] #docker-compose version: '3.4' services: django_app: build: ./django ports: - "8000:8000" image: backend container_name: backend nginx: build: ./nginx volumes: - ./nginx/ssl/cert.crt:/etc/nginx/ssl/certs/cert.crt - ./nginx/ssl/private.key:/etc/nginx/ssl/private/private.key ports: - "80:80" - "443:443" depends_on: - django_app image: nginx container_name: nginx P.S. At first there were more settings, but I have not been able to fix the problem for 2 days, so I removed a lot of things to at least make it work What did you find out: requests/responses are successful directly from the system via curl I raised the same docker-compose on … -
dynamic block branding on django admin start page
I want to customize the admin home screen. I tried overwriting templates/admin/base.html like this: {% extends "admin/base.html" %} {% load static %} {% block extrahead %} TEST #1 {% endblock %} {% block branding %} TEST #2 {{ block.super }} {% endblock %} like suggested in the docs but while TEST #1 works, TEST #2 does not show up on the admin home page. First question: Why can I not overwrite my branding block, or is this simply the wrong block? Second question: I wish to show information on the main page that comes from the backend - let's for simplicity just say the output of timezone.now() - can this be done using a normal view in the admin? -
How to register a Django model for a specific database only
I am building a DJango multi-tenant web app that separates the tenants by giving them each their database. The app identifies the source and destination of the requests by checking the hostname. The localhost is the default tenant(me) using the default database and the subdomains from that are the tenants using their databases. There is a model Tenants that I am using to create tenants and store their data. I want it to be only registered in the default database so that only I can edit it from the localhost admin but the tenant's admin can't. I tried this and the only output was: ------------------------------TenantAdmin------------------------------ admin.py from django.contrib import admin from .models import Tenant from .utils import hostname_from_the_request # Register your models here. class TenantAdmin(admin.ModelAdmin): print("------------------------------TenantAdmin------------------------------") def get_form(self, request, obj=None, **kwargs): # Get the hostname from the request current_hostname = hostname_from_the_request(request) print("------------------------------Current hostname B4------------------------------", current_hostname) # Check if the hostname is 'localhost' if current_hostname == 'localhost': return super().get_form(request, obj, **kwargs) else: print("------------------------------Current hostname------------------------------", current_hostname) return None # Returning None effectively hides the model in the admin # Register the Tenant model with the custom admin class admin.site.register(Tenant, TenantAdmin) So I also tried interfering with the migrations in the routers: routers.py … -
csrfmiddlewaretoken included in the search url query
The problem is I have 2 searches, one is a search for job seekers to find jobs and another is a search for companies to find job seekers. The expected result is to have http://localhost:8000/search-job-seeker/?&q=searchquery but what I'm getting is http://localhost:8000/search-job-seeker/?csrfmiddlewaretoken=pF6HWEH2rOTvZTRsXzaDuQ9GiGw9ChmukeCYUSND15gzFPCKWmRtRGvVecMHIWKK&q=searchquery I don't see any error messages when I debug in the console or in the terminal. I've tried to use get in the form which results in the http://localhost:8000/search-job-seeker/?csrfmiddlewaretoken=pF6HWEH2rOTvZTRsXzaDuQ9GiGw9ChmukeCYUSND15gzFPCKWmRtRGvVecMHIWKK&q=searchquery but when I use post method in the form, I get http://localhost:8000/search-job-seeker/ and the search result comes out with out the q=searchquery in the url. My view for this is: class JobSeekerSearchView(LoginRequiredMixin, View): template_name = "core/job_seeker_search.html" form_class = JobSeekerSearchForm def post(self, request, *args, **kwargs): """ Handle HTTP POST requests, process form data, search for job seekers, and render the template. Args: self: the instance of the class request: the HTTP request object *args: variable length argument list **kwargs: variable length keyword argument list Returns: HTTP response object """ form = self.form_class(request.POST) job_seeker_results = [] if form.is_valid(): query = form.cleaned_data["q"] # Search for job seekers using PostgreSQL full-text search and icontains job_seeker_results = Seeker.objects.annotate( search=SearchVector("seekerprofile__pk", "seekerprofile__headline"), ).filter( Q(search=SearchQuery(query)) | Q(seekerprofile__skills__icontains=query) | Q(seekerprofile__rate__icontains=query) ) context = {"query": query, "job_seeker_results": job_seeker_results, "form": form} … -
OneToOneField, unique and inheritance in Django
I would like to have a relationship with the User model and one of some different (but related) models, but this must be with only one of the available models e.g. different kinds of subscriptions but a User can only have one related. I know I can solve this with a lot of custom checks but I want to know if there is a recommended or simple solution. If I use inheritance and define a base model, let's put "BaseModel" with a OneToOneField to User, and from this model, they will inherit several: ModelA and ModelB, class ModelBase(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="model_base") class Meta: abstract = True class ModelA(ModelBase): pass class ModelB(ModelBase): pass Django shows this error Reverse accessor 'User.model_base' for 'models.ModelA.user' clashes with reverse accessor for 'models.ModelB.user'. I understand that defining a different related_name in submodels solves this, but this does not maintain the "unique" condition. What would be the best solution for this problem? Could I avoid using GenericForeignKeys? Thank you! -
ImproperlyConfigured at /admin/login/ Can't login to django admin after creating a super user with a custom user model
I'am trying to logging into the django admin panel with a superuser I have successfully created but evrytimes it gives me the ImproperlyConfigured at /admin/login/ saying that settings.DATABASES is improperly configured but I have check everything and nothing seems wrong the thing is that I'am also using multiple database with postgresql so the supersuer created is my user_account app, only this is the code of : the models.py of my user_account app: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.core.validators import validate_email from django.utils.translation import gettext_lazy as _ from django.core.exceptions import ValidationError # Create your models here. class UserAccountManager(BaseUserManager): def email_validator(self,email): try: validate_email(email) except ValidationError: raise ValueError(_("please enter a valid email address")) def create_user(self, email, name, phone_number, password=None): if email: email=self.normalize_email(email) self.email_validator(email) else: raise ValueError(_("an email address is required")) if not name: raise ValueError(_("first name is required")) if not phone_number: raise ValueError(_("phone number is required")) user = self.model(email=email, name=name, phone_number=phone_number) user.set_password(password) user.save(using=self._db) return user def create_member(self, email, name, phone_number, password=None): user = self.create_user(email, name, phone_number,password) user.is_member = True user.is_staff = True user.is_superuser = False user.save(using=self._db) return user def create_superuser(self, email, name, phone_number, password=None): user = self.create_user(email, name, phone_number, password) user.is_member = True user.is_staff = True user.is_superuser … -
Maintaining Conversation Context in Django API View with OpenAI GPT for Chat Application
I am building a chat application using Django that integrates with OpenAI's GPT to generate responses based on the conversation history. I've set up an APIView in Django to handle the chat interactions but am struggling with maintaining and sending the previous conversation context to the OpenAI API for generating contextually relevant responses. Current Implementation: Here's the simplified version of my ChatGptApiView: class ChatGptApiView(APIView): # permission_classes =[IsAuthenticated] def get(self, request): return render(request, 'gpt/gpt.html') def post(self, request): if request.method == 'POST': data = request.data conversation_history = [] user_prompt = data.get('user_prompt') # assistant_prompt = data.get('assistant_prompt') profile_id = data.get('profile_id') user_id = request.user.id regenerate = data.get('regenerate', False) try: profile_data = Profile.objects.get(id=profile_id) except Profile.DoesNotExist: return error_response(error_message="Profile not found", status=status.HTTP_400_BAD_REQUEST) user_input = None if user_prompt is not None: user_input = {"role": "user", "content": user_prompt} conversation_history.append(user_input) save_chat_to_mongodb(profile_data, user_input, user_id, regenerate) recent_chats = get_recent_chats(int(profile_id)) # print("recent_chats",recent_chats,"::::") old_chats = recent_chats.get('chat', []) if 'chat' in recent_chats else [] old_chats = [{k: v for k, v in item.items() if k != 'created_at'} for item in old_chats] if len(old_chats) > 0: conversation_history.extend(old_chats) print(conversation_history, "================================================================") # Define a generator function to stream the response def generate_response(context, message, profile_name): print(conversation_history,"::::::::") if profile_name is not None: context.append({ 'role': 'user', 'content':f"You will follow the current conversation …