Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ORA-02019 Error When Executing Queries on Remote Oracle DB in Django Application
I'm currently working on a Django application that interacts with an Oracle database. My application needs to execute SQL queries on a remote Oracle database, which is configured in the settings.py file. The SQL queries I'm trying to execute have a syntax similar to: SELECT * FROM table@source Here, source is a different database than the one currently executing the query. Both the source and target databases are Oracle databases. Despite the remote database being configured in settings.py, I encounter the following error when executing the first query: ORA-02019: connection description for remote database not found I'm looking for guidance on how to resolve this error. Here's some additional information that might be helpful: I've confirmed that the remote database is accessible outside of the Django environment. The user credentials used in settings.py have the necessary privileges. The application works fine with local database queries. Has anyone encountered a similar issue or can provide insights into what might be going wrong? Any advice on configuring Django to work seamlessly with remote Oracle databases using database links would be greatly appreciated. Thank you in advance for your help! -
In Django how to compare two texts and print a message about correctness?
I'm new to Django. In Django i would like to compare two texts and receive a message if they are the same or different. In reality these two texts are two short HTML codes. The page can reload easily, I'm only interested in the logic behind comparing the two texts (and not the use of Ajax, jQuery, JS). A text will be inserted in the front-end by the user, who will write in a div (no textarea) with contenteditable="true" which is already present in my code. I have already prepared an example text in the black panel, so I would like to compare the entire block of text (from up to ). While the other text will be contained in the backend (in a variable or something similar). Then I will click on the button and in the gray rectangle i would like to print CORRECT: the two texts are the same or ERROR: the two texts are different. Important is that i don't want to use textarea, but as already said I want to use the div with contenteditable="true" that I already have in my code. HTML {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta … -
DoesNotExist at /.../pk/
So I created a simple CRUD simple, like a tweet, where you have Username, Title and Message/Description It was working well and I was following a tutorial, then it happened I don't know what going on because my models seems to be ok class Topic(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) #participants = updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Room, on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] It also doesn't seem to be an error in my views def room(requests,pk): room = Room.objects.get(id=pk) message = Message.objects.get(id=pk) context = {'room':room, 'message':message} return render(requests,'base/buy.html',context) def createRoom(request): form = RoomForm() if request.method == 'POST': form = RoomForm(request.POST) if form.is_valid(): form.save() return redirect('home') context = {'form':form} return render(request, 'base/room_form.html', context) But then I noticed this error in my shell Traceback (most recent call last): File "c:\Users\adrya\thegreatsite\base\views.py", line 2, in <module> from .models import Room, Message ImportError: attempted relative import with no known parent package these are the models I imported from django.shortcuts import render, … -
How to hide Graphql Apis from everyone on internet
I have a website built using Python Django framework and backend APIs are designed using GraphQL api. The graphql url is like below, http://0.0.0.0:8000/graphql/ All my apis are currently accessible by everyone on the internet. I need to hide those behind some authentication (login / password). Please suggest some ways to fix this. -
Django is very slow in the browser when I'm coding my Django app
I want some helps. I'm working on a ecommerce website. I code my side in localhost side. However, when I launch my site on the browser like chrome, it takes a long Time to reload and it's slow. Some éléments don't appear and I can easily work. I want your help plaise. Sorry for my Bad english, I'm from french speaker country. I don't know how to résolve this issue.. -
Differences when running HTML script with "python manage.py" or Visual Studio Code's Live Server
I'm building a website and I've been experiencing some issues when debugging. I'm using Visual Studio Code and the framework Django. I'm really new to this so I could be making some silly mistake. The problem I have is this: I'm trying to insert a date-time picker to an HTML (particularly, a flatpickr date-time picker). I want it to be included in a particular div section, and I've followed the corresponding instructions to do this. Nevertheless, when I run the code using the "python manage.py runserver", the calendar appears in a top-left position instead of at the bottom, where the div is. This is how it looks running the "python manage.py runserver" command: (https://i.stack.imgur.com/t96x2.png). And this is how it looks when I use the "Open with Live Server" option in Visual Studio Code: (https://i.stack.imgur.com/HH1Pv.png) When using the "Open with Live Server" option, of course, the css isn't applied, so it just shows the HTML. But there the calendar appears where it should. I send also the HTML code of the page. I paste the code of the webpage here {% load static %} <html> <head> <title>Atención dental Dalla Vecchia</title> <link rel="stylesheet" href="{% static 'C:/Users/CgLenovo/Documents/Programas/Sitio_web_dental_3/Dental_website/static/home/css/style.css' %}"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" … -
How to display the value instead of the ID in the form in Django
I need to display the time, but the form outputs the ID models.py class Ticket(models.Model): concert = models.ForeignKey('Concert', related_name='concert_name', on_delete=models.PROTECT) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) place = models.ForeignKey('Place', on_delete=models.PROTECT) date_time = models.ForeignKey('Time', on_delete=models.PROTECT) price = models.IntegerField(blank=True, null=True) def __str__(self): return f"{self.first_name}, {self.last_name}, {self.date_time}" class Concert(models.Model): name_concert = models.CharField(max_length=50) description = models.TextField(max_length=500) length = models.TimeField() type = models.ForeignKey('Type', on_delete=models.PROTECT) janr = models.ForeignKey('Janr', blank=True, null=True, on_delete=models.PROTECT) regisser = models.ForeignKey('Regisser', blank=True, null=True, on_delete=models.PROTECT) date_time = models.ForeignKey('Time', on_delete=models.PROTECT) img = models.ImageField(upload_to='photo/', blank=True, null=True) price = models.IntegerField(blank=True, null=True) def __str__(self): return self.name_concert class Time(models.Model): date_time = models.DateTimeField() def __str__(self): return format(self.date_time, "%d.%m.%y %H:%M") forms.py class ticketForm(forms.ModelForm): class Meta: model = Ticket fields = ['first_name', 'last_name', 'concert', 'date_time', 'price', 'place'] widgets = { "first_name": TextInput(attrs={ 'class': 'input-style', 'placeholder': 'Имя' }), "last_name": TextInput(attrs={ 'class': 'input-style', 'placeholder': 'Фамилия' }), "concert": TextInput(attrs={ 'class': 'input-style', 'placeholder': '', 'value': 'ticket.concert_name', 'readonly': 'readonly' }), "date_time": TextInput(attrs={ 'class': 'input-style', 'placeholder': '', 'value': 'ticket.date_time', 'readonly': 'readonly' }), "price": TextInput(attrs={ 'class': 'input-style', 'placeholder': '', 'value': 'ticket.price', 'readonly': 'readonly' }), "place": TextInput(attrs={ 'class': 'input-style', 'placeholder': '', 'value': '', 'readonly': 'readonly' }) } views.py def ticketsSite(request, concert_id): ticket = get_object_or_404(Concert, id=concert_id) form = ticketForm(initial={'concert': ticket.name_concert, 'price': ticket.price, 'date_time': ticket.date_time}) context = { 'ticket': ticket, 'form': form … -
Authenticate method in django returns None
It is the first time I do a project in Django. As a first step, I am creating methods to sign-up and sign-in users. The sign-up works well. However, after registering an user, I try to sign-in without success. My models.py file is: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): def create_user(self, username, email, password=None, **extra_fields): user = self.model(username=username, email=email, **extra_fields) # set_password will handle the password before saving it in the database # It hash the password before saving it user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(username, email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=20, unique=True) email = models.EmailField(unique=True) password = models.CharField(max_length=256) fname = models.CharField(max_length=100) lname = models.CharField(max_length=100) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return self.username class Meta: managed = True db_table = "users" and the sign-in method in views.py is the following one: def signin(request): if request.method == "POST": username = request.POST.get("username") password = request.POST.get("password") # Authenticate the user user = authenticate(request, username=username, password=password) # If it is not None - user exists and right credentials if user: login(request, user) fname = … -
Implementing Autocomplete for M2M Fields in Wagtail CustomUser Model
I have added two additional fields to my CustomUser model in my Wagtail project. These two fields are many-to-many (m2m) fields, and in the form, I want these fields to be represented as an Autocomplete feature. How can I achieve this? models.py class User(AbstractUser): journal = models.ManyToManyField("journal.Journal", verbose_name=_("Journal"), blank=True) collection = models.ManyToManyField("collection.Collection", verbose_name=_("Collection"), blank=True) forms.py class CustomUserEditForm(UserEditForm): journal = forms.ModelMultipleChoiceField(queryset=Journal.objects.all(), required=False, label=_("Journal")) collection = forms.ModelMultipleChoiceField(queryset=Collection.objects.filter(is_active=True), required=True, label=_("Collection")) class CustomUserCreationForm(UserCreationForm): journal = forms.ModelMultipleChoiceField(queryset=Journal.objects.all(), required=False, label=_("Journal")) collection = forms.ModelMultipleChoiceField(queryset=Collection.objects.filter(is_active=True), required=True, label=_("Collection")) -
Python - remove commas and leave decimal points from string as number
As of title, I need to remove commas from string number and leave decimal point, but the problem is input can be with . or ,. This input will be saved for Django model's DecimalField For example: Input: 250,000,50 250,000 250000.00 25,000 Output: 250000.50 250000.00 250000.00 25000.00 What I have tried: def _normalize_amount(self, value -> str): normalized_amount = value[:-3].replace(",", "") + value[-3:] return Decimal(normalized_amount) Problem is that this function can not handle the cases where user enters , as decimal point. How to solve this case ? -
Website wont load! How do i get my website files online via Hostinger?
Im starting up a website company that compares dentists' prices and lets you book online. Ive had a freelancer develop a python coded website using Django creating the back end and the front end. Think he used ubuntu. He showed me a loom recording of the website working and then sent me the files. I just cant get the website to load/work Ive set up my domain in godaddy - www.toothpik.co.uk I have hosting on hostinger, got a VPS server at their instruction to allow python code. Ive uploaded the files to the shared web server, then i also configured the SFTP via WinSCP and i can see the files that the Dev send me from an expanded zip file. I have linked my VPS IP to keys generated in puTTY for SSH which is enabled on my hostinger using a public key into hostinger Sorted all my DNS out so it points from godaddy to hostinger (i want to do cloud flare in future, god help me on that) getting Hello World message when visiting the website URL to Hostinger. Im not very techy, but im learning Ive read about Git, PuTTY etc. Ive been talking with the hostinger … -
Display unique records in a django table
I have three models: class Member(models.Model): person_id = models.CharField(max_length=100, null=True) first_name = models.CharField(max_length=100, null=True) last_name = models.CharField(max_length=100, null=True) minit = models.CharField(max_length=1, null=True) dob = models.DateField(null=True) class Project(models.Model): project_name = models.CharField(max_length=100) project_description = models.CharField(max_length=100) project_owner = models.CharField(max_length=100) dos_from = models.DateField() dos_to = models.DateField() class Review(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name='review_rel') project = models.ForeignKey(Project, on_delete=models.CASCADE) dos= models.DateField() review_type= models.CharField(max_length=25) Some members will have no reviews at all, some will have multiple reviews even within the same project. I would like to create a table with one row per member and project for the members who are assigned a review. When I start with the Review model, I get multiple rows for the same member (if the member has more than one review within the same project) I don’t know how to dedup it. import django_tables2 as tables class Reviews_Table(tables.Table): class Meta: model = Review fields = ( "project__project_name", "member__person_id", "member__first_name", "member__last_name", "member__minit", "member__dob", ) I also tried starting with the Member Model, but I can’t figure out how to go backwards and link to the Review model. I have been stuck on this for a while. I would truly appreciate help. Thank you -
Managing ALLOWED_HOSTS in Django for Kubernetes health check
I have a Django application running on Kubernetes, using an API for health checks. The issue I'm facing is that every time the IP associated with Django in Kubernetes changes, I have to manually update ALLOWED_HOSTS. django code: class HealthViewSet(ViewSet): @action(methods=['GET'], detail=False) def health(self, request): try: return Response('OK', status=status.HTTP_200_OK) except Exception as e: print(e) return Response({'response': 'Internal server error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) deployment code : livenessProbe: httpGet: path: /health/ port: 8000 initialDelaySeconds: 15 timeoutSeconds: 5 Error: Invalid HTTP_HOST header: '192.168.186.79:8000'. You may need to add '192.168.186.79' to ALLOWED_HOSTS. Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/utils/deprecation.py", line 135, in __call__ response = self.process_request(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/middleware/common.py", line 48, in process_request host = request.get_host() ^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/http/request.py", line 148, in get_host raise DisallowedHost(msg) django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: '192.168.186.79:8000'. You may need to add '192.168.186.79' to ALLOWED_HOSTS. Bad Request: /health/ Is there a way to dynamically use ALLOWED_HOSTS and avoid manual updates? (Every deployment IP changed.) ALLOWED_HOSTS ALLOWED_HOSTS = [localhost', '127.0.0.1'] Any guidance or suggestions for the best solution in this regard would be appreciated. -
Adding several object on the same djangoform
There is this code to register devices in a database. You fill the form with some data, like MAC, and save it. I want to implement a function where you split up several MACs with ,(comma) and for each MAC a new device is added to DB(this table has an autoincrement sequence). Basically my code is: for i in listmac.split(","): form2 = form.save(commit=False) #next_id = Net.objects.order_by('-id_seq').first().id_seq+1 #form2.id_seq=next_id form2.mac = i form2.save() The problem:\ Let's say my next id is 150.\ With the code like that, if I put 3 MACs, the code tries to add 3 devices with the seq=150, therefore only the last one is saved.\ If i uncomment those two lines, it adds correctly 150, 151 and 152, but it does not save the sequence in the autoincrement field. So if I try to insert another register directly through the database for example, it tries to insert 151 and it gives me an error. -
Adding attributes to functions outside function scope
Does this add new attributes to the view function in the View Class of python? This is the definition of as_view() function in View class of view.generic.base module. @classonlymethod def as_view(cls, **initkwargs): """Main entry point for a request-response process.""" for key in initkwargs: if key in cls.http_method_names: raise TypeError( "The method name %s is not accepted as a keyword argument " "to %s()." % (key, cls.__name__) ) if not hasattr(cls, key): raise TypeError( "%s() received an invalid keyword %r. as_view " "only accepts arguments that are already " "attributes of the class." % (cls.__name__, key) ) def view(request, *args, **kwargs): self = cls(**initkwargs) self.setup(request, *args, **kwargs) if not hasattr(self, "request"): raise AttributeError( "%s instance has no 'request' attribute. Did you override " "setup() and forget to call super()?" % cls.__name__ ) return self.dispatch(request, *args, **kwargs) view.view_class = cls view.view_initkwargs = initkwargs # __name__ and __qualname__ are intentionally left unchanged as # view_class should be used to robustly determine the name of the view # instead. view.__doc__ = cls.__doc__ view.__module__ = cls.__module__ view.__annotations__ = cls.dispatch.__annotations__ # Copy possible attributes set by decorators, e.g. @csrf_exempt, from # the dispatch method. view.__dict__.update(cls.dispatch.__dict__) # Mark the callback if the view class is async. if … -
SimpleListFilter does nothing - but neither does any other list_filter
when applying a SimpleListFilter in Django 5 admin, I get the same queryset no matter the value. After some testing I realized, the matter is not only with the SimpleListFilter, but all fields of list_filter. class Monitor(models.Model): serial = models.CharField("serial", max_length=9, primary_key=True) status = models.PositiveSmallIntegerField("status", default=0) class StatusFilter(admin.SimpleListFilter): title = "status" parameter_name = "status" def lookups(self, request, model_admin): return [(0, "off"), (1, "busy"), (2, "on")] def queryset(self, request, queryset): print("value:", self.value(), type(self.value())) if self.value() == 0: qs = queryset.filter(status=0) print("queryset count", qs.count()) return qs elif self.value() == 1: qs = queryset.filter(status=1) print("queryset count", qs.count()) return qs elif self.value() == 2: qs = queryset.filter(status=2) print("queryset count", qs.count()) return qs print("no filter") return queryset The example of the SimpleListFilter shows the correct amount tough: The numbers in this screenshots are correct (29, 0, 6) When pressing once (!) on a filter, for example "on" I get multiple prints returned, which is many more than I would expect: value: 2 <class 'str'> no filter value: 0 <class 'int'> queryset count 29 value: 1 <class 'int'> queryset count 0 value: 2 <class 'int'> queryset count 6 value: 2 <class 'str'> no filter value: 2 <class 'str'> no filter value: 2 <class 'str'> no filter … -
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS DJANGO_SETTINGS_MODULE
Does anyone know if there are any import or project organization problems? I have mainly seen views and models to see if there was a problem there but I have no solution enter image description here I have tried everything, sorry, I'm just starting with django on my own. enter image description here -
expected str, bytes or os.PathLike object, not NoneType for subprocess of ffmpeg
I dont know much about ffmpeg, subprocess and its functions, im trying to take a screenshot form a video and save it at my other field of my model. this is my model: class SubSong(models.Model): song = models.ForeignKey(SongPage, on_delete=models.CASCADE, related_name='related_song') create = jmodels.jDateField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='related_user') video = models.FileField(upload_to='sub_video/',) like = models.ManyToManyField(User, blank=True, ) total_like = models.PositiveIntegerField(default=0) is_allowed = models.BooleanField(default=False) image_sub = ThumbImage(upload_to='sub_songs/', default='1.jpg') def __str__(self): return self.song.title and views.py if request.method == 'POST': authen(request) form = MyTryForm(request.POST, request.FILES) if form.is_valid(): data = form.cleaned_data x = SubSong.objects.create(song_id=id, user_id=request.user.id, video=data['video'], ) path = x.video.name out = path.replace('sub_video/', '').replace('mp4', 'jpg') z=subprocess.check_output( ffmpeg.input('media/' + path, ss='00:00:50').filter( 'thumbnail').output('media/sub_songs/' + out, vframes=1).run(), text=True) x.image_sub=z x.save() messages.success(request, 'ویدیوی شما با موفقیت ارسال شد ، پس از بررسی منتشر خواهد شد') return redirect(request.META.get('HTTP_REFERER')) else: messages.error(request, 'ویدیوی شما بارگداری نشد') return redirect(request.META.get('HTTP_REFERER')) it can save the video and also default picture 1.jpg at image_sub. also it can save scrrenshot at the media/sub_song/.but my problem is that it gives me error: expected str, bytes or os.PathLike object, not NoneType how i should return the screen from subprocess to save it as my image_sub field? and why do this error raise? i dont want to see this error … -
Django log out problems
I am developing a tweet application and while I can log in during the authentication process, my logout function does not work. I leave my source codes to explanation. I'm waiting for your help The error I get is as follows: (http://127.0.0.1:8000/logout/?next=/) and i get This site cannot be reached error! More precisely, I cannot access the page I want. When I click on logout, I have to log out of the account. I should also mention that I am using Python 3.12.0 and Django. my urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("",include('tweetapp.urls')), path("",include('django.contrib.auth.urls')),] my views.py from django.shortcuts import render, redirect from . import models from django.urls import reverse from tweetapp.forms import AddTweetForm, AddTweetModelForm def listtweet(request): all_tweets = models.Tweet.objects.all() tweet_dict = {"tweets":all_tweets} return render(request,'tweetapp/listtweet.html',context=tweet_dict) def addtweet(request): if request.POST: nickname = request.POST["nickname"] message = request.POST["message"] models.Tweet.objects.create(nickname=nickname, message=message) return redirect(reverse('tweetapp:listtweet')) else: return render(request,'tweetapp/addtweet.html') def addtweetbyform(request): if request.method == "POST": form = AddTweetForm(request.POST) if form.is_valid(): nickname = form.cleaned_data["nickname_input"] message = form.cleaned_data["message_input"] models.Tweet.objects.create(nickname=nickname, message=message ) return redirect(reverse('tweetapp:listtweet')) else: print("error in form") return render(request,'tweetapp/addtweetbyform.html', context={"form":form}) else: form = AddTweetForm() return render(request,'tweetapp/addtweetbyform.html', context={"form":form}) def addtweetbymodelform(request): if request.method == "POST": form = AddTweetModelForm(request.POST) if form.is_valid(): print(form.cleaned_data) return redirect(reverse('tweetapp:listtweet')) … -
How to edit list_editable only to be available before 30 days pass Django_Admin
So I've got some transactions and every transaction has some editable fields from list editable, now this way they are editable all the time, but what I want to do is make them be editable only if they are not older then 30 days, when they get older then 30 days list_editable is just empty "list_editable = []". class Transaction(BaseModel): date = models.DateField( blank=False, null=False, db_index=True, default=datetime.now) user = models.ForeignKey(User, blank=False, null=False, on_delete=models.PROTECT) amount = models.IntegerField(blank=False, null=False) description = models.CharField(max_length=500, blank=True, null=True) ... class TransactionAdmin (ExportActionMixin, BulkModelAdmin): list_editable = ['date', 'user', 'amount', 'description'] **Now I tried to put this in an if statement that if the transaction dates + 30 days are older then the date now list editable should be the normal list editable with the fields else it should be empty, thats just what the latest thing I tried was. I tried it in every possible variation **( that I could think of ) but I always end up with the same result It either gives me all the list **editable fields for all transactions or none list editable fields. Now my question is what am i doing wrong, am I going about it the wrong way or … -
How to get the average of a specific value in Django queryset
I have two models 'Teams' and 'Members'. One of the fields in Members is 'favorite_team' and a field in Teams is 'favorite_avg' I am trying to get an average of the favorite_team field by entering in a value. I am trying to find a better/faster way to do this: all_members = Members.objects.all().count() giants_fans = Members.objects.filter(favorite_team='New York Giants').count() team = Teams.objects.get(name='New York Giants') team.favorite_avg = giants_fans/all_members team.save() -
Django Rest Framework best way to delete an object
So I"M Trying to make this delete method in my drf project. i setuped the @api_view(['DELETE']) to the views function and setuped a form method to delete the object. but it didn't worked well. so i have to make the @api_view to post method and set the form method to post to delete the object. is there any way i can make this using delete method?. this is my view @api_view(['POST']) @permission_classes([IsAuthenticated]) def delete(request,article_id): if request.method == 'POST': article = get_object_or_404(Article, pk=article_id) if article.author == request.user: article.delete() return redirect('/') return Response(status=status.HTTP_400_BAD_REQUEST) this is my form method <form action="{% url 'news:delete' article.id %}" method="post"> {% csrf_token %} <input type="submit" value="delete"> </form> -
Django migrations on celery not stoping after .save()
I have a django application and celery, and one of the tasks is to create a tenant in '/admin' @app.task def create_tenant_account(form_data): ... tenant = Company(...) tenant.save() ... After tenant.save() all of the migrations start applying, but suddenly the celery crashes because the code dont stoped after tenant.save() (after the save, I have some tenants setup that needs to run after) This only happens on celery, locally it stops and runs normally. Is there a way to prevent the code from runing? My solution was to create another function to run after the tenant.save(), but for now, I need the setup to run in the same function. -
How to implement subquery in Django ORM?
I have a Postgres sql query that looks like below SELECT Date_trunc('hour', batch_time) + Date_part('minute', batch_time) :: INT / 10 * interval '10 min', Round(Avg(min_metric) :: NUMERIC, 2), metric_notify FROM (SELECT batch_time, Min("uptime") AS min_metric, Coalesce(CASE WHEN notify LIKE '%HIGH%' THEN 'HIGH' ELSE '' END, '') AS metric_notify FROM lt_store WHERE batch_time >= '2024-01-14 09:01:26.656059' AND batch_time <= '2024-01-15 09:01:26.656055' GROUP BY 1, 3 ORDER BY 1 ASC) AS subq GROUP BY 1, 3 As you can see, there are two queries. In the inner query, I do min aggregation on the metric with a group by on time and in the outer query, I do avg aggregation on the metric with a 10 min time interval truncation. Now I plan to replicate the same in django query and this is what I do result1 = LtStore.objects.filter(batch_time__gte='2024-01-14 09:01:26.656059', batch_time__lte='2024-01-15 09:01:26.656055' ).values ('batch_time').annotate(min_metric=Round(Min('uptime')), metric_notify=Coalesce(Max( Case( When(notify__contains='HIGH', then=Value('HIGH')), default=Value(''), )), Value('') ), ).order_by("batch_time") trunc_query = "date_trunc('hour', LtStore.batch_time) + date_part('minute', LtStore.batch_time)::int / 10 * interval '10 min'" result2 = LtStore.objects.annotate( min_metric=Subquery(result1.values('min_metric')[:1]), metric_notify=Subquery(result1.values('metric_notify')[:1]) ).extra({"trunc": trunc_query}).values( 'trunc', 'metric_notify' ).annotate( avg_metric=Avg('min_metric') ).order_by("trunc") The above django query works but I get a different result as compared to the one with sql query. What am I doing wrong? -
Safari Takes Excessive Time to Load and Render Server-Sent Events (SSE) in Django Application
Here's a brief overview of our implementation: Backend (Django): Sends SSEs using django-eventstream. Events are sent to a URL like https://devbackend.marshallgoldsmith.ai/events/{session_id}, where {session_id} is a unique identifier. Frontend: Uses fetchEventSource to listen to the events from the above URL. We handle various event scenarios such as onmessage, onerror, and onclose. The event stream opens fine in Chrome and even displays correctly when the URL is opened directly in a Chrome browser tab. Issue with Safari: When accessing the event stream URL in Safari, it keeps loading indefinitely and does not display any events, unlike in Chrome. There are no apparent error messages in the Safari console. we checked cross-origin issues and other compatibility issues and searched. But no luck. So if anyone face this kind of issue, please let us know. that will be more helpful. Thanks