Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to grab the active tabs URL from an opend browser(64-bit Linux system) using python
i trying to make an desktop monitoring system for linux based OS. When I work with this code I get the currently opend applications in my system and browser tabs and its title also. But I want the urls too. If any one know about this please help. Here is my views.py file from django.http import JsonResponse import subprocess import re import threading import time from urllib.parse import urlparse opened_applications = [] def get_domain_name(url): parsed_url = urlparse(url) domain = parsed_url.netloc if domain.startswith("www."): domain = domain[4:] # Remove 'www.' if present return domain def extract_search_query(title): # Common patterns indicating a search query in browser titles search_patterns = ["Google Search", "Google", "Bing", "Yahoo", "DuckDuckGo"] # Check if any of the search patterns are present in the title for pattern in search_patterns: if pattern.lower() in title.lower(): # Extract the search query using string manipulation query_start_index = title.lower().find(pattern.lower()) + len(pattern) search_query = title[query_start_index:].strip() return search_query return "Search Query Placeholder" def monitor_opened_applications(): global opened_applications try: while True: # Get a list of window titles using wmctrl output = subprocess.check_output(["wmctrl", "-lx"]).decode("utf-8") # Extract application names from window titles new_opened_applications = [] for line in output.split("\n"): # print("++++++++++", line) if line: match = re.match(r"^(\w+\s+\S+)\s+(\S+)\s+(.+)$", line) if match: … -
message from channels not gettion to reciver the right
when i send a message from a user not getting to the recipient or recevier.but only getting the message who sended as revceived message and it was to in sended messages. # consumer.py import json from channels.consumer import AsyncConsumer from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer from channels.db import database_sync_to_async from rest_framework.authtoken.models import Token from rest_framework_simplejwt.tokens import RefreshToken,AccessToken from asgiref.sync import async_to_sync from api.models import UserModel as User,Message,Rooms from django.db.models import Q import uuid class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): token=(self.scope['url_route']['kwargs']['token']) receiver_id=self.scope['url_route']['kwargs']['receiver_id'] receiver= await self.get_user_by_id(receiver_id) sender=await self.get_user_object(token=token) gname=await self.get_room(sender,receiver) self.roomGroupName = gname await self.channel_layer.group_add( self.roomGroupName, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.roomGroupName, self.channel_layer ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] username = text_data_json["username"] print(self.roomGroupName, self.channel_name) user= await self.get_user_object(token=(self.scope['url_route']['kwargs']['token'])) await self.channel_layer.group_send( self.roomGroupName, { "type": "sendMessage", "message": message, "username": username, }) async def sendMessage(self, event): message = event["message"] user_id = self.scope['url_route']['kwargs']['receiver_id'] print(user_id,'fdsfsdfsdfsdfwerrrrrreee') receiver= await self.get_user_by_id(user_id) token=self.scope['url_route']['kwargs']['token'] print(token) user = await self.get_user_object(token) print(user) await self.create_message(sender=user,message=message,room_name=self.roomGroupName,receiver=receiver) await self.send(text_data=json.dumps({"message": message, "username": user.username,'to':'ihsan'})) @database_sync_to_async def get_user_by_id(self,id): return User.objects.filter(id=id).first() @database_sync_to_async def get_user_object(self, token): token=AccessToken(token=token) return User.objects.get(id=token.payload['user_id']) @database_sync_to_async def create_message(self,sender,receiver,message,room_name): messageObj=Message.objects.create(sender=sender,receiver=receiver,message=message) room=Rooms.objects.get(groupName=room_name) messageObj.save() room.messages.add(messageObj) room.save() return messageObj @database_sync_to_async def get_room(self,user1,user2): print(user1.id,user2.id) room=Rooms.objects.filter(Q(users__id=user1.id)&Q(users__id=user2.id)).first() if room: return room.groupName else: room=Rooms(groupName=str(uuid.uuid1())) room.save() room.users.add(user1) room.users.add(user2) return room.groupName … -
Django form problem on Model object and redirect
I'm facing 2 problems when creating Form in Django: Problem on redirect after submitting Form Model object is not iterable Specifically, I'm creating feedback form and all my code is as below. There are 4 files and using crispy_form to show the form in html file. Everything works fine except after I click on submit button. It cannot return to the same feedback form with blank fields, and it shows the error 'BugTypes' object is not iterable Please check and help. Thank you! # models.py from django.db import models # Create your models here. class BugTypes(models.Model): bugType = models.CharField(max_length=100) def __str__(self): return self.bugType class UserFeedback(models.Model): username = models.CharField(max_length=100) problem = models.CharField(max_length=255) bugType = models.ManyToManyField("BugTypes", related_name='userFeedBack') feedback = models.TextField() def __str__(self): return self. Problem # forms.py from django import forms from survey.models import UserFeedback, BugTypes class FeedbackForm(forms.ModelForm): username = forms.CharField( widget = forms.TextInput( attrs={'class': 'form-control'} ) ) problem = forms.CharField( widget = forms.TextInput( attrs = {'class': 'form-control'} ) ) bugType = forms.ModelChoiceField( queryset = BugTypes.objects.all(), widget = forms.Select( attrs={'class': 'form-control'} )) feedback = forms.CharField( widget = forms.Textarea( attrs = {'class': 'form-control'} )) class Meta: model = UserFeedback fields = "__all__" # views.py from django.shortcuts import render from django.urls import reverse from … -
'int' object has no attribute 'username'
iam try to loop through a following users list,and i got this error say "'int' object has no attribute 'username'" def Home(request): profile = Profile.objects.get(user=request.user) posts = Post_Upload.objects.all() #show only the user posts you following user_following_list = FollowersCount.objects.filter(user=request.user).values_list('follower', flat=True) print(user_following_list) feed_lists = Post_Upload.objects.filter(user__in=user_following_list) #user suggestion all_users = User.objects.all() all_following_users = [] for users in user_following_list: user_list = User.objects.get(username=users.username) all_following_users.append(user_list) new_suggestion = [ X for x in list(all_users) if (x not in list(all_following_users))] current_user = User.objects.filter(username=request.user.username) final_suggestion = [X for x in list(new_suggestion) if (x not in list(current_user))] random.shuffle(final_suggestion) user_profile = [] user_profile_list = [] for users in final_suggestion: user_profile.append((users.id)) for ids in user_profile: profiles = Profile.objects.filter(id=ids) user_profile_list.append(profiles) suggestion_user_profile_list = list(chain(*user_profile_list)) context = {"posts":feed_lists,"profile":profile,"suggestion_user_profile_list":suggestion_user_profile_list[:4]} return render(request,'index.html',context) i try to change the users.username into users then i am getting this error say "User matching query does not exist." the problem are showing here user_list = User.objects.get(username=users.username) -
KeyError at / 118 in django deployment
I have created a workflow for my repository and everything even the deployment is going fine and i have created the model in same environment as in the docker and workflow is running but still i am getting this: Environment: Request Method: GET Request URL: http://mysite-olvdmbamqa-el.a.run.app/ Django Version: 4.0.2 Python Version: 3.11.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'welcome_deck', 'movie_recommender', 'irisapp'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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'] Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 167, in _get_response callback, callback_args, callback_kwargs = self.resolve_request(request) File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 290, in resolve_request resolver_match = resolver.resolve(request.path_info) File "/usr/local/lib/python3.11/site-packages/django/urls/resolvers.py", line 592, in resolve for pattern in self.url_patterns: File "/usr/local/lib/python3.11/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.11/site-packages/django/urls/resolvers.py", line 634, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.11/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.11/site-packages/django/urls/resolvers.py", line 627, in urlconf_module return import_module(self.urlconf_name) File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1204, in _gcd_import <source code not available> File "<frozen importlib._bootstrap>", line 1176, in _find_and_load <source code not available> File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked <source code not available> … -
Annotate django queryset based on related field attributes
Suppose you have this models structure in a django project from django.db import models class Object(models.Model): name = models.CharField(max_length=100) class ObjectEvent(models.Model): class EventTypes(models.IntegerChoices): CREATED = 1, "Created" SCHEDULED = 2, "Scheduled" COMPLETED = 3, "Completed" CANCELED = 4, "Canceled" event_type = models.IntegerField(choices=EventTypes.choices) object = models.ForeignKey(Object, on_delete=models.CASCADE, related_name="events") I now want to access the derived property ended which is defined as every object that have an event of type COMPLETED or CANCELED. I already did that with the @property decorator, but as I want to be able to filter using ended attribute. So I'm trying to implement this through the annotate queryset method. class ObjectManager(models.Manager): def get_queryset(self): qs = super().get_queryset() qs = qs.annotate( ended=models.Case( models.When( events__event_type__in=( ObjectEvent.EventTypes.COMPLETED, ObjectEvent.EventTypes.CANCELED, ), then=models.Value(True), ), default=models.Value(False), output_field=models.BooleanField( verbose_name="Object ended", ), ) ) return qs class Object(models.Model): objects = ObjectManager() name = models.CharField(max_length=100) fake_data.json [ { "model": "main.object", "pk": 1, "fields": { "name": "task1" } }, { "model": "main.object", "pk": 2, "fields": { "name": "task2" } }, { "model": "main.object", "pk": 3, "fields": { "name": "task3" } }, { "model": "main.object", "pk": 4, "fields": { "name": "task4" } }, { "model": "main.objectevent", "pk": 1, "fields": { "event_type": 1, "object": 1 } }, { "model": "main.objectevent", "pk": … -
Sending a notification to single user using web socket in django
In my drf project, I have added the functionality where notifications are being broadcasted to all web socket users. What I want is to send notification to single user. I hope I will get a solution to my problem. I am using django-channels and web sockets. -
Why not just set Django's ALLOWED_HOSTS to ["*"]?
I understand why validation of the host header is important but I do not understand why this would be the responsibility of Django. The docs for the settings mysteriously mention which are possible even under many seemingly-safe web server configurations. and the docs for the host header validation mention something similar: Because even seemingly-secure web server configurations are susceptible to fake Host headers and Previous versions of this document recommended configuring your web server to ensure it validates incoming HTTP Host headers. While this is still recommended, in many common web servers a configuration that seems to validate the Host header may not in fact do so. For instance, even if Apache [..] In 2024, is there still any reason to fear these "many" (undocumented) "seemingly-safe server configurations" or can I just use a sane proxy server and let that do the validation instead? Setting ALLOWED_HOSTS to ["*"] removes one more thing to think about while deploying. -
How to add a custom check in `validate_constaints` function considering the instance yet to be committed?
I'd like to use this constraint on my Django model: models.UniqueConstraint( fields=["edificio", "studio"], condition=models.Q(attiva=True), name="unique_attiva_per_edificio_studio", violation_error_message=_( "cannot have two active configurations for the same studio", ), ) But since I'm on MariaDB (and I cannot change it) conditional constraints/indexes aren't supported yet. So I'm extending the validate_constraints function in my EdificioConfigurazione model to check it. def validate_constraints(self, exclude=None): super().validate_constraints(exclude) # TODO: this will be removed once MySQL/MariaDB supports conditional constraints manager = EdificioConfigurazione.objects multiple_attiva_per_edificio = ( manager.values("edificio", "studio") .annotate( rcount=models.Count("id", filter=models.F("attiva")), ) .filter(rcount__gt=1) ) if multiple_attiva_per_edificio.exists(): violation_error_message = _( "cannot have two active configurations for the same studio", ) raise ValidationError(violation_error_message) Assuming this is the right approach to do this (I'm open to suggestions), I cannot enforce this check since the instance to be added/modified (which is self) is not committed to the DB yet. How can I use the instance? My idea would be looking at the self.pk field and: if self.pk is None: I add the instance to the queryset before the checks else: the instance is already in the DB (I'm modifying it for example) so I need to update the queryset to use it instead of the one committed. Once again, I don't know if extending … -
use dynamic string for model key in django
For exampkle I have tabel like this, class FormSelector(models.Model): prefs = models.JSONField(default=dict,null=True, blank=True) items = models.JSONField(default=dict,null=True, blank=True) then in views, I want to do like this, json = {"prefs":[1,2],"items":[2,3,4]} mo = FormSelector.objects.last() for key in json: // key is string "prefs","items" mo.{key} = di[key] // I want to do the equivalent to mo.prefs , mo.items Is there any good method to do this? -
Does React have XSS attack protection?
The object from Django Rest Framework is: Object { id: 3, user: {…}, photos: (1) […], caption: '<script>console.log("Hacked lol")</script>'} and my React component is: function Post({post}) { return ( <div id="post" className="post w-full max-w-xl p-2 mt-4 rounded-2xl bg-main-box"> <div id="post-caption"> {post.caption} </div> </div> ) Will it prevent this XSS attack on caption or will it put the caption as it is? -
Why does using logging in django corrupt log files?
When I was using logging in my django project, I found that after 2-3 requests for an excuse, the log file got corrupted. Why in settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': '%(asctime)s %(levelname)-8s [%(pathname)s:%(lineno)d] [%(funcName)s] [%(message)s]' } }, 'handlers': { 'console_handler': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'standard', }, 'info_handler': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'formatter': 'standard', 'filename': os.path.join(INFO_LOG_DIR, 'info.log'), 'when': 'midnight', 'backupCount': 30, 'encoding': 'UTF-8', }, 'error_handler': { 'level': 'ERROR', 'class': 'logging.handlers.TimedRotatingFileHandler', 'formatter': 'standard', 'filename': os.path.join(ERROR_LOG_DIR, 'error.log'), 'when': 'midnight', 'backupCount': 30, 'encoding': 'UTF-8', }, 'homework': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'formatter': 'standard', 'filename': os.path.join(HOMEWORK_LOG_DIR, 'homework.log'), 'maxBytes': 1024 * 1024 * 10, 'backupCount': 100, 'encoding': 'UTF-8', } }, 'loggers': { 'data_analysis': { 'handlers': ['console_handler', 'info_handler', 'error_handler'], 'level': 'DEBUG', 'propagate': True, }, 'homework': { 'handlers': ['homework', 'console_handler'], 'level': 'DEBUG', 'propagate': True, } }, } in other py file: log = logging.getLogger("data_analysis") But after sending a few requests, the log file looks like this python version: 3.6.8 django version: 3.2.3 Part of my project uses multithreading, but when I was testing, I commented out the multithreaded code I want to be able to log properly -
NameError in Choices= LACTATION STAGES in meta class in models. py
It is just saying that in ... lactation_stage = models.Instegerfield(editable=False, choices= LACTATION_STAGES,) there is a nameError in name'LACTATION_STAGES, is not defined Just expecting some one to help me i am a beginner -
ModuleNotFound error in migration of new model
This is my model: class Company(models.Model): class LTRCharField(models.CharField): def formfield(self, **kwargs): defaults = {'widget': TextInput(attrs={'dir': 'ltr'})} defaults.update(kwargs) return super().formfield(**defaults) title = models.CharField(_('company title'), max_length=255) logo = FileBrowseField( _('company logo'), max_length=255, directory='company/', extensions=['.png'] ) address = models.TextField(_('company address')) phone = LTRCharField(_('company phone'), max_length=20) class Meta: verbose_name = _('company') verbose_name_plural = _('company') def __str__(self): return self.title The migrate management command gives me this error: ModuleNotFoundError: No module named 'company.models.Company'; 'company.models' is not a package When I look at the migration file I see this line has error: import company.models.Company I can't figure out what is the issue here? -
Django - Adding more options to AdminTimeWidget
I tried to add more time choices to AdminTimeWidget by overriding DateTimeShortcuts refering to this post also another similar posts on SO. My problems is I am getting Uncaught ReferenceError: DateTimeShortcuts is not defined and jQuery.Deferred exception: DateTimeShortcuts is not defined ReferenceError: DateTimeShortcuts is not defined at HTMLDocument error on console. I am newbie to django, I did not understant why I am getting this error. Here is how I implemented it: (function($) { $(document).ready(function() { DateTimeShortcuts.clockHours.default_ = [ ['16:30', 16.5], ['17:30', 17.5], ['18:00', 18], ['19:00', 19], ['20:00', 20], ]; DateTimeShortcuts.handleClockQuicklink = function (num, val) { let d; if (val == -1) { d = DateTimeShortcuts.now(); } else { const h = val | 0; const m = (val - h) * 60; d = new Date(1970, 1, 1, h, m, 0, 0); } DateTimeShortcuts.clockInputs[num].value = d.strftime(get_format('TIME_INPUT_FORMATS')[0]); DateTimeShortcuts.clockInputs[num].focus(); DateTimeShortcuts.dismissClock(num); }; }); })(jQuery); and in my ModelAdmin I included this JS file in Media class as below: @admin.register(models.MyModel) class MyAdminModel(): // other stuff list_filter = [("created", custom_titled_datetime_range_filter("By created"))] class Media: js = ("admin/js/DateTimeShortcuts.js",) Also I have a custom datetime range filter implemented as: def custom_titled_datetime_range_filter(title): class CustomDateTimeRangeFilter(DateTimeRangeFilter): def __init__(self, field, request, params, model, model_admin, field_path): super().__init__(field, request, params, model, model_admin, field_path) … -
'error: subprocess-exited-with-error' while installing my requirements/local.txt file after cloning the repo [duplicate]
Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... error error: subprocess-exited-with-error × Preparing metadata (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [8 lines of output] running dist_info creating C:\Users\Dell\AppData\Local\Temp\pip-modern-metadata-o75tij8k\psycopg_c.egg-info writing C:\Users\Dell\AppData\Local\Temp\pip-modern-metadata-o75tij8k\psycopg_c.egg-info\PKG-INFO writing dependency_links to C:\Users\Dell\AppData\Local\Temp\pip-modern-metadata-o75tij8k\psycopg_c.egg-info\dependency_links.txt writing top-level names to C:\Users\Dell\AppData\Local\Temp\pip-modern-metadata-o75tij8k\psycopg_c.egg-info\top_level.txt writing manifest file 'C:\Users\Dell\AppData\Local\Temp\pip-modern-metadata-o75tij8k\psycopg_c.egg-info\SOURCES.txt' couldn't run 'pg_config' --includedir: [WinError 2] The system cannot find the file specified error: [WinError 2] The system cannot find the file specified [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. I'm encountering this error while installing requirements/local.txt after cloning repo, what could be the reason and a solution for this? I was expecting all the dependencies to be installed but encountered this error -
Manager isn't available in django
My Register view is like below. class UserRegisterView( FormView ): template_name = 'register.html' form_class = UserCreationForm redirect_authenticated_user = True success_url = reverse_lazy('dashboard') # name of URL def form_valid( self, form ): user = form.save() if user is not None: login( self.request, user ) return super( UserRegisterView, self ).form_valid( form ) def get( self, *args, **kwargs ): if self.request.user.is_authenticated: return redirect('register') return super( UserRegisterView, self ).get( *args, **kwargs ) My model is like below. from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ) USER_TYPE = ( ('S', 'Super Admin'), ('A', 'Admin'), ('P', 'Patient'), ('D', 'Doctor'), ('U', 'User'), ) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) date_of_birth = models.DateField(null=True, blank=True ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) user_type = models.CharField(max_length=1, choices=USER_TYPE) username = models.EmailField(unique=True) email = models.EmailField(unique=True) phone = models.CharField(max_length=15, blank=True, null=True) address = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) REQUIRED_FIELDS = [] def __str__(self): return f"{self.first_name} {self.last_name}" I am getting error Manager isn't available; 'auth.User' has been swapped for 'hospital.User' -
Django - Disconnect signal with multiple receivers
I use pre_save and post_save signals in my app with many receivers on them. For example : @receiver(post_save, sender=SrdRevisionDocument) @receiver(post_save, sender=SrdRevisionWording) @receiver(post_save, sender=SrdRevisionAcronym) @receiver(post_save, sender=SrdRevisionRevision) @receiver(post_save, sender=SrdRevisionTableRequest) @receiver(post_save, sender=SrdRevisionTable) def handle_added_or_edited_element(sender, instance, **kwargs): ... content of the signal However, in some case, I need to disconnect the signal to have only the usual behavior of the save() method. I tried the simple method in Django documentation Signal.disconnect(receiver=None, sender=None, dispatch_uid=None) but it doesn't works with multiple receivers. Also, I've tried some solutions from StackOverflow, like Context Manager but none seems to work with multiple receivers (i.e., Disconnect signals for models and reconnect in django). I know I'm not the only one facing this issue, but I didn't found a solution. -
Django - Adding a favicon through urls.py
I'm trying to get my favicon to appear in the browser tab. The favicon.ico is correctly placed in the static files directory, and I can access it directly via http://localhost:8000/static/favicon.ico. I am trying to get it to work without adjusting the html header. The favicon.ico is located inside of project/core/static my urls.py is located inside of project/core I have this code inside of my settings.py INSTALLED_APPS = [ 'django.contrib.staticfiles', ] STATIC_URL = '/static/' I have this code inside of my urls.py from django.conf import settings from django.views.generic.base import RedirectView from django.contrib.staticfiles.storage import staticfiles_storage if settings.DEBUG: urlpatterns += [ path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('favicon.ico'))), ] Django version - 5.0.1 Verified that I can access the favicon directly via http://localhost:8000/static/favicon.ico. The expected behaviour is the favicon displayed on the browser tab. -
Integrating Google Gemini python sdk on Django app returns html, not the expected prompt answer, how do I successfully integrate Gemini sdk?
#views.py from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST import google.generativeai as genai import logging logger = logging.getLogger(__name__) genai.configure(api_key='mykey') @csrf_exempt @require_POST def get_gemini_response(request): try: company_name = request.POST.get('company_Name') if not company_name: return JsonResponse({'error': 'Missing company name'}, status=400) # Formulate the prompt for Gemini AI prompt = f"Provide insights and analysis about the company '{company_name}', focusing on its financial health, market position, recent news, and potential future trends." # Use the Gemini Pro model model = genai.GenerativeModel(model="models/gemini-pro") response = model.generate_text( prompt=prompt, temperature=0.7, max_output_tokens=512 ) # Extract the generated text from the response generated_text = response.result['candidates'][0]['content']['parts'][0]['text'] # Return the generated text wrapped in HTML return JsonResponse({'response': generated_text}) except genai.GenerativeAIError as e: logger.error(f"Gemini API Error: {e}") return JsonResponse({'error': f"Gemini API Error: {e.message}"}, status=500) except Exception as e: logger.exception(f"Error processing request: {e}") return JsonResponse({'error': 'Internal server error'}, status=500) #company_filing.html <div class="row justify-content-center"> <button class="btn btn-md col" data-toggle="modal" data-target="#aiInsights">AI Insights</button> </div> <script> $(document).ready(function() { $('#aiInsights').on('show.bs.modal', function (event) { var companyName = "{{ company_name | safe }}"; var csrftoken = $('input[name="csrfmiddlewaretoken"]').val(); // Show loading spinner $('#geminiResponseContainer').html('<div class="text-center"><span class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></span></div>'); // Logging the data sent in the AJAX request console.log('Preparing AJAX request with data:', { company_Name: companyName, csrfmiddlewaretoken: csrftoken }); $.ajax({ url: … -
Django Rest Framework - Apply filter and aggregation and then create all inside view
Any help on this issue would be highly appreciated please! Basically I have a model which handles transactions and is linked to the user model. I would like to all transactions made today, per user, and then I want to aggregate their sales by summing the transactions per user, and then based on this sum, I would want to calculate 10% of it and create a new transaction (basically today's interest earned) I have tried to make it work inside inside serializers.py class UserTransactionFilterSerializer(serializers.Serializer): username = serializers.CharField(read_only = True) id = serializers.IntegerField(read_only = True) agg_amt_btc = serializers.SerializerMethodField(read_only=True) trans = serializers.SerializerMethodField(read_only = True) # Gets transaction data using UserTransactionSerializer def get_trans(self, obj): user = obj print(user) today = timezone.now().date() my_trans_qs = user.transaction_set.filter(trans_date__date=today) return TransactionUserInlineSerializer(my_trans_qs, many=True, context = self.context).data # Aggregates the trans amount (sum and avg) def get_agg_amt_btc(self, obj): user = obj print(user) today = timezone.now().date() my_trans_qs = user.transaction_set.filter(trans_date__date=today) return my_trans_qs.aggregate(sum_btc = Sum('trans_amt_btc'), avg_btc = Avg('trans_amt_btc')) def create(self,obj): today = timezone.now().date() for user in User.objects.filter(transaction__trans_date__date=today).distinct(): total_transactions = user.transaction_set.aggregate(sum_btc = Sum('trans_amt_btc'))['sum_btc'] print(user) transaction_amount = total_transactions * Decimal('0.1') print(transaction_amount) with transaction.atomic(): Transaction.objects.create(owner=user, trans_amt_btc=transaction_amount) return user which works! but it bypasses all validations when I do: Transaction.objects.create(owner=user, trans_amt_btc=transaction_amount) because based on my model, some … -
How Do I Make and Send Nested JSON Outputs in Django Server for iOS Client?
I'm currently learning Django to build the server for my iOS app, which I developed first without a server at all, but I've been stuck on how to replicate the data models inside the client Swift code I made when I came up with the app. The models are nested in nature, which, of course, require creating nested JSON outputs, and that's exactly why I'm struggling so much developing the server side. The models from the client look like that under: // CodingKeys will be added once the server is finished. struct Sections: Codable { let sections: [Section] } struct Section: Codable, Hashable { let title: String let articles: [Article] } struct Article: Codable, Hashable { let title: String let articleViews: Int let thumbnailURL: String let articleURL: String let articleMetadata: ArticleMetadata let articleAuxiliaryData: ArticleAuxiliaryData } struct ArticleMetadata: Codable, Hashable { let timeToRead: Int let date: String } struct ArticleAuxiliaryData: Codable, Hashable { let countOfLoved: Int let countOfShared: Int } On the server side, I've so far tried using Serializers from rest_framework to form JSON outputs accordingly, but I guess I can't seem to grasp the idea of how to use it or how to "link" subsidized data to their parent … -
Teradata connection issue within django
I am able to connect to teradata from django app in home network. But not able to do so from office network. I am working for a banking company and there are network restrictions. One resolution was to update routetable using powershell commands with admin access. But doing so is not allowing to run the app still. How can this issue be resolved? Tried updating routetable manually using powershell commands. But that is not helping. Can anyone suggest how to resolve the issue? -
Django Channels, Set different WebSocket routing patterns for different paths
I am trying to implement a Django Projects with multiple Apps, with multiple Consumers with different WebSocket routing patterns for each paths. Below is my working code, the code works, but is obviously is not correct, I have tried with different methods as the Django Chennels Documents Django Channels - Routing states but never got it to work, #asgi.py from api.middleware import TokenAuthMiddleWare from api.routing import websocket_urlpatterns from live_tracker.routing import live_websocket_urlpatterns application = ProtocolTypeRouter( { 'http': get_asgi_application(), 'websocket': TokenAuthMiddleWare(AuthMiddlewareStack(URLRouter(websocket_urlpatterns))), } ) application = ProtocolTypeRouter( { 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack(URLRouter(live_websocket_urlpatterns)), } ) From the 2 apps I have, in first app I have made it so that a token is needed to access the websocket_urlpatterns while in the second app I only need default django authentication: live_websocket_urlpatterns. I went through StackOverflows this question How to use multiple websocket connections using Django Channels? the question is handling AuthMiddlewareStack only,to which I have 2, a custom TokenAuthMiddleWare and django's default AuthMiddlewareStack is there a way I can merge the 2 applictaion to 1 applications? -
How do I generate pdf using pupetter in django. Got signal only works in main thread of the main interpreter
#urls.py path('pdf/', views.generate_pdf), #views.py async def main(): browser = await launch() page = await browser.newPage() await page.goto("https://python.org") await page.waitFor(1000) await page.pdf({"path": "python.pdf"}) await browser.close() async def generate_pdf(request): print("Starting...") await main() print("PDF has been taken") return HttpResponse("PDF has been generated") got error signal only works in main thread of the main interpreter It works nicely while running in standalone python file but not inside django got runtime error This event loop is already running while using async def generate_training_pdf(request): asyncio.get_event_loop().run_until_complete(main())