Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to stop a celery task if user unloads?
My website allows users to translate files. I want to add a failsafe in case a user decides to unload the webpage(whether by reloading, navigating away or closing the tab). My backend is django plus celery[redis]. Currently, after a user begins the translation task my frontend polls the backend every 5 seconds to see if the task is still running. Here is the corresponding JS for reference: function pollTaskStatus(taskId) { currentTaskId = taskId; console.log(currentTaskId) pollInterval = setInterval(() => { const xhr = new XMLHttpRequest(); xhr.onload = function() { if (xhr.status == 200) { const response = JSON.parse(xhr.responseText); if (response.status === 'completed') { console.log('sent'); showTranslationComplete(response); clearInterval(pollInterval); // Stop polling once completed isTranslating = false; // Set to false when translation is complete } } else { showError('An error occurred.'); clearInterval(pollInterval); // Stop polling on error isTranslating = false; // Set to false on errors } }; xhr.onerror = function() { showError('Connection error. Please check your network connection and try again.'); clearInterval(pollInterval); // Stop polling on network error isTranslating = false; // Set to false on network error }; xhr.open('GET', `/translate/poll_task_status/${taskId}/`, true); xhr.send(); }, 5000); // Poll every 5 seconds } I know it is unreliable to run functions during/after an unload … -
Pass multiple type of data in AJAX request with Django
I have this Ajax call : var serializedData = $(this).serialize(); $.ajax({ type:"POST", url: "/my_url_view/", data: serializedData , var_id_sales_document:$("#id_id_sales_documents").val() , success: function(data){ $("#result").text(data["result"]); } }); What I'm trying to do is to pass serializedData to save the form but I also need to get var_id_sales_document to re-use it in my view like this : var_id_sales_document = request.POST.get('var_id_sales_document') Normally I used to pass data in my ajax like this $.ajaxSetup( { data: {item1: $('#item').val(), csrfmiddlewaretoken: '{{ csrf_token }}' }, }); But like this I don't know how to pass serialized data ... I tried many things on the forum but I didn't find how to cumulate those kind of datas. -
ManytoMany fields generating "no such table:<tablename>" error where <tablename> is related to no model in models.py
I'm sorry if question title is confusing or not clear but i didn't have a better way of writting it. I have a django app root, in models.py i created a model Post containing 3 manytomany fields ; File, Video and Picture and some other fields and while trying to populate the model i get this error message django.db.utils.OperationalError: no such table: root_post_Picture. I already ran python manage.py sqlmigrate root 0001_initial and saw no table with such name and it's not surprising since root_post_Picture corresponds to none of my models . I think it is related to the manaytomanyfields i created since the name root_post_Picture seems to be a combination of the tables root_post and root_picture from my database. views.py def postcreation(request): Videoarray=[] Picturearray=[] Filearray=[] form=AbsolutePostForm(request.GET) file = Fileform(request.FILES) pic = PictureForm(request.FILES) vid = VideoForm(request.FILES) if request.method=="POST": file = Fileform(request.FILES) if "File" in request.POST: if file.is_valid(): File=Files(Post_type="posts",Post_id=get_id_generation("postids.txt"),File=request.FILES["File"]) File.save() Filearray.append(File) print("file") return HttpResponse("file") pic = PictureForm(request.FILES) if "Picture" in request.FILES: if pic.is_valid(): Picture = Pictures(Post_type="posts", Post_id=get_id_generation("postids.txt"),Picture=request.FILES["Picture"]) Picture.save() Picturearray.append(Picture) print("pic") return HttpResponse("picture") vid = VideoForm(request.FILES) if "Video" in request.FILES: if vid.is_valid(): Video = Videos(Post_type="posts", Post_id=get_id_generation("postids.txt"),Video=request.FILES["Video"]) Video.save() print("vid") Videoarray.append(Video) if "Postcoment" in request.POST: form = AbsolutePostForm(request.POST) if form.is_valid(): post=form.cleaned_data["Postcoment"] Main=Post(post=post) Main.save() for obj … -
How to delete images when removing post in Summernote?
Using Summernote on the Django project to add/remove posts via the Admin interface, I can find no solution for removing images from the Media Root. None of the similar responses found on SO work. Works fine on images outside of Summernote - installed django-cleanup What's the best way to delete image(s) when removing a post via Admin? -
connect to the hikvision camera with python
i want to get sream video from hikvision camera and show it on the webpage using django . i did it but it has delay for 2 or 3 seconds . i try with both rtsp and http protocol . http with port 80 is better than rtsp in delay . is there another way to connect to the camera with no delay ? i change camera configuration many times . if frame rate is higher than 4 the delay is increasing but with under 4 frame rate its delay is about 2 seconds .do you have suggestion?also i use substream config to use protocol http. self.Capture = cv2.VideoCapture("http://user:pass@ip:port/ISAPI/Streaming/channels/102/httpPreview") -
Django 1.8 and MSSQL 2022
Is there a way to connect a project in Django 1.8 to MSSQL 2022, using django_pyodbc_azure librery allows me connect to MSSQL 2016, is there another librery that allows me do this? -
video call working in localhost using webrtc in reactjs and python django channels for websocket.... but not working in staging?
I had to implement a video call application using webrtc in React JS and used Python django channels in the backend for the web socket connection. The video call is working fine on localhost but not in staging. How do you think I could solve this problem? peer connection, send an offer, send an answer, and ice candidates everything is fine. but in staging, video calls are not working. -
Issues running Django server in MacOS
I am having troubles trying to run a Django server in my Macbook M3 Pro with MacOS Sonoma 14.6.1. When running the command python manage.py runserver the server doesn't start neither shows error. I just receive in terminal the messages: Watching for file changes with StatReloader Performing system checks... System check identified some issues: WARNINGS: general_hydrocarbons.HProject.alliance: (fields.W340) null has no effect on ManyToManyField. tracking_event.TrackingManagement.user: (fields.W340) null has no effect on ManyToManyField. System check identified 2 issues (1 silenced). No errors are shown in the terminal. I have also tried the command python manage.py check, this executes correctly with no errors. I tried running the python manage.py migrate and python manage.py makemigrations commands too. Both are returning the same error: zsh: segmentation fault python manage.py migrate zsh: segmentation fault python manage.py makemigrations I have been working on this project the last 4 months with no problems of this type. Today I changed from anaconda to miniforge and this issue appeared. I also tested running other project built over FastAPI and in this case the project is running correctly. The packages installed in the project are: APScheduler==3.10.4 asgiref==3.6.0 beautifulsoup4==4.12.3 bs4==0.0.2 certifi==2024.7.4 charset-normalizer==3.3.2 crispy-bootstrap5==0.7 Django==4.0 django-ckeditor==6.5.1 django-crispy-forms==2.0 django-filter==23.5 django-js-asset==2.0.0 django-recaptcha==3.0.0 et-xmlfile==1.1.0 idna==3.8 lxml==5.3.0 … -
Operational Error in my Django Project as I can't find out why it is happening
I've been working on one of my projects while learning Django, and it's my first project based on follow-up tutorials. Now, I've almost completed my entire project, but there's one problem that keeps occurring, and I can't figure out why. There's a debug mode enabled, and it claims this is an operational error. So, this problem occurs as I am developing an online commerce shop and have created a conversation app that allows users to talk with the Admin about the items. However, when the user enters the text message and presses the submit button, an error message such as "operational error" appears. Even I can't see the message from the Django admin because it also displays the debug error message there. Clicking up on Contact sellerstatic.net/JdPW4V2C.png) Error Message -
Could Rails implement a django style ORM (with fields and migrations defined from the model?)
I love Rails, except I love the field definition and auto-generated migrations in the the Django ORM. Django model example: class Person(models.Model): name = models.CharField(max_length=200) So the field is defined on the model, and then the migrations are generated from it (with ability to modify them before running). Some other frameworks do this as well. There's lots of benefits, from consistent validation to auto-generated admin/forms, factories, and API. Has anyone seen any packages that do something similar in Rails/Ruby? Are there any reasons this wouldn't work? -
How can I resolve the issue where Django migrations are not applying changes to the database?
I have a Django app and I'm using PostgreSQL for the database. I've added some new properties to my models, and after making these changes, I ran the following commands: python manage.py migrate python manage.py makemigrations A new migration file, 0001_initial.py, was generated with the new properties, such as "hdd_list_remark". However, when I check the database, it seems the migrations are not applied. One of the models with the added properties is: hdd_list_remark = models.TextField( max_length=500, blank=True, verbose_name="HDD lijst opmerking") name = models.CharField(max_length=100, verbose_name="Naam") sort = models.CharField(max_length=100, default='', verbose_name="Soort(Latijn)") slug = models.SlugField(max_length=100, editable=False) cites = models.CharField(max_length=5, choices=CitesChoices.choices, default=CitesChoices.EMPTY, verbose_name="Cites") uis = models.BooleanField(default=False, verbose_name="UIS") pet_list = models.CharField(max_length=3, choices=HDDChoices.choices, default=HDDChoices.EMPTY, verbose_name=" HDD lijst") bird_directive_list = models.CharField(max_length=13, blank=True, choices=BirdDirectiveChoices.choices, default=BirdDirectiveChoices.EMPTY, verbose_name=" Vogelrichtlijnen") Habitat_directive_list = models.CharField(max_length=13, blank=True, choices=HabitatDirectiveChoices.choices, default=HabitatDirectiveChoices.EMPTY, verbose_name=" Habitatrichtlijnen") description = models.TextField( max_length=5000, blank=True, null=True, verbose_name="Beschrijving") feeding = models.TextField( max_length=2000, blank=True, null=True, verbose_name="Voeding") housing = models.TextField( max_length=2000, blank=True, null=True, verbose_name="Huisvesting") care = models.TextField(max_length=1000, blank=True, null=True, verbose_name="Verzorging") literature = models.TextField( max_length=10000, blank=True, null=True, verbose_name="Literatuur") images = models.ImageField( upload_to="media/photos/animals", blank=False, null=False, verbose_name="Foto") category = models.ForeignKey( Category, related_name='animals', on_delete=models.CASCADE, verbose_name="Familie") date_create = models.DateTimeField( auto_now_add=True, verbose_name="Datum aangemaakt") date_update = models.DateTimeField( auto_now=True, verbose_name="Datum aangepast") animal_images = models.ManyToManyField( AnimalImage, related_name='related_animals', blank=True) files = models.ManyToManyField( AnimalFile, related_name='related_animals_files', blank=True) The … -
The sub-items of the 'Products' item in the 'Menu' dropdown are not displayed when clicked
The sub-items of the 'Products' item in the 'Menu' dropdown are not displayed when clicked، he 'فهرست' button works correctly when clicked and opens the dropdown, but when I click on the 'محصولات' item, the dropdown closes. I want the sub-items of 'محصولات' to be displayed when I click on it. he 'فهرست' button works correctly when clicked and opens the dropdown, but when I click on the 'محصولات' item, the dropdown closes. I want the sub-items of 'محصولات' to be displayed when I click on it. -
Model's ForeignKey field rises not-null constraint event with `default=` set
My model : def Maker(models.Model): name = models.CharField() def get_default_maker(): default_brand, created = Maker.objects.get_or_create(name="noname") return default_brand.pk class Item(models.Model): maker = models.ForeignKey( Maker, verbose_name="Maker", on_delete=models.SET(get_default_brand), default=get_default_maker ) I have a Maker instance-plug "noname". I would like to assign it on Item creation if maker field not set (in form). But whenever I try to create an Item without setting maker field I get psycopg2.errors.NotNullViolation: null value in column "maker_id" of relation "stock_management_item" violates not-null constraint. Ofcourse, I can manage that in view/form but I would like to understand why default value won't work. -
Access geonode api via client
I'm encountering an issue with authentication in GeoNode and could use some help. I've enabled it by setting: LOCKDOWN_GEONODE=True However, I need to access the API (.../api/v2/...) through a client, both for frontend clients in Django templates and in pure code. When I activate the lockdown, any API call is redirected to the login page, regardless of the authentication method I use. I've tried BasicAuth and token authentication (by adding REST_FRAMEWORK TokenAuthentication), but nothing seems to work. The only workaround I've found is to add the API urls to AUTH_EXEMPT_URLS, and create my own middleware to intercept requests. But that doesn't seem like the correct approach. -
Pointing a Django Project to my Purchased Domain in Google Cloud
I bought domain from GoDaddy and am hosting it in a bucket(which has the same name as my domain) in a project on Google cloud. In the bucket, under 'edit website configuration' I added a simple html page in the field called ' Index (main) page suffix'. That html comes up correctly when I go to my domain on the browser. So everthing works as expectd. The problem is that I want to deploy a Django project(with several apps in it) to my domain instead of the simple html. There are many tutorials that show how to deploy a Django project on Google Cloud but they all end up giving you a domain that they(or Google Cloud) assigns. I don't want Google Cloud generated domain but want the project deployed on my purchased domain. How do I make that work? It seems like it shouldn't be hard so I'm guessing there is a simple 'trick' that I haven't been able to find. I went through several tutorials on Django deployment on Google Cloud. I even deployed one of the small examples from one tutorial. But it has a Google Cloud generated domain name which is not what I want. -
Pass data to django framework using javascript (no jquery)
I have a dropdown list that I got from an uploaded CSV file from Django that I want to pass back to a different Django view with javascript when selected. I keep getting a 404 error (index.js:9 POST http://127.0.0.1:8000/gui_app/%7B%%20url%20%22get_selection%22%20%%7D 404 (Not Found) (anonymous) @ index.js:9 ) when I click on the select button after I choose a value from the dropdown. From what I understand reading the error message, the issue seems to be coming from javascript not being able to render the url the correct way. What's the correct way to pass the url in javascript so that javascript recognizes it and passes the data to the view? Here's my code below index.js let signalSelectButton = document.getElementById("signalSelectButton") const url = loacation.href('/get_selection/') signalSelectButton.addEventListener("click", function() { console.log("clicked") const selectedValue = document.getElementById("signalSelect").value console.log(selectedValue) fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' }, body: JSON.stringify({selected_value: selectedValue}) }) .then(response => { if (!response.ok) { throw new Error('Network response was not ok') } return response.json() }) .then(data => { console.log(data) document.getElementById('response-message').innerText = data.message }) .catch(error => {console.error('Error:', error)}) }) views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.conf import settings from django.core.files.storage import FileSystemStorage from .forms … -
can't login to my django website on phone browser but i can login to accounts created on a phone after deployment on railway
i can login into accounts created on pc using a pc but not a phone and i can login into accounts created on the phone using a phone but not a pc i dont know what settings are involved to fix this im not using a custom user model just the User model of django -
Django, how to get annotated field of related model
For example, the Invoice model has a project field that points a ForeignKey to the Project model, Project has a custom ProjectManager that has get_queryset defined, in get_queryset I do: super().annotate(display=...) and when I want to get this annotated field through Invoice: Invoice.objects.filter(project__display__iregex=...) then an error occurs that project does not have a display field, how can I make it so that the related models take fields from some queryset, this is get_queryset() for us Django 4.2.4 Python 3.10 To take annotated fields I use Subquery: Subquery(models.Project.objects.filter(id=OuterRef("project_id")).values_list("display")) but because of this the request is executed very slowly. -
django dynamic content not appearing [closed]
I have been tyring to create a dynamic carousel that displays title and detail of projects. but the content is not appearing besides the fact that it loads in the inspection tools. <div id="carouselExampleCaptions" class="carousel slide" > <div class="carousel-indicators"> {% for p in projects %} <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="{{ forloop.counter0 }}" {% if forloop.first %}class="active" aria-current="true"{% endif %} aria-label="Slide {{ p }}"></button> {% endfor %} </div> <div class="carousel-inner"> {% for p in projects %} <div class="carousel-item {% if forloop.first %}active{% endif %}"> <img src="..." class="d-block w-100" alt="..."> <div class="carousel-caption"> <h5 class="title" style="color: #ffffff;">{{ p.title }}</h5> <p>{{ p.detail }}</p> </div> </div> {% endfor %} </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev"> <span class="carousel-control-prev-icon" ></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next"> <span class="carousel-control-next-icon" ></span> <span class="visually-hidden">Next</span> </button> </div> I have been trying to resolve this for a day. image -
Django queryset count with zero
I have this Django Model : class Survey(models.Model): call = models.OneToOneField(Call, null=True, related_name='survey', on_delete=models.CASCADE) service = models.ForeignKey(Service, related_name='survey', null=True, on_delete=models.CASCADE) when_start = models.DateTimeField() when_end = models.DateTimeField() I would like to obtain the number of calls per service over a time slot I tried this : start = datetime.datetime(2024, 6, 17, 0, 0) end = datetime.datetime(2024, 6, 17, 23, 59, 59) services = <QuerySet [<Service: S1>, <Service: S2>, <Service: S3>]> Sondage.objects.filter(service__in=services, when_start__range=(start, end)).values('service__name').annotate(nb=Count('call')) result : <QuerySet [{'service__name': 'S1', 'nb': 50}, {'service__name': 'S2', 'nb': 119}]> But I would like to have this (0 for "S3" service): <QuerySet [{'service__name': 'S1', 'nb': 50}, {'service__name': 'S2', 'nb': 119}, {'service__name': 'S3', 'nb': 0}]]> I read several notes that referred to "Coalesce" but I can't seem to use it correctly -
Django, how to create ForeignKey field when .annotate?
I wanted to create a ForeignKey field in Django using .annotate, but I couldn't find any option for it, maybe it doesn't exist. I just want to LEFT JOIN a specific model with a specific condition. But now I have to do it like this: queyrset = Invoice.objects.annotate(provided_amount=Subquery(InvoicePayment.objects.filter(invoice_id=OuterRef("id"), date=timezone.now().date())) queryset.first().provided_amount But I want it like this: queryset = Invoice.objects.annotate(invoice_payment=...) queryset.first().invoice_payment.provided_amount I could do it using property, but I don't want to do it like that, I would like to do everything in one query. Maybe there is a library for this? Django - 4.2.4 Python - 3.10 I tried creating a SQL VIEW and binding it to the model with managed = False, but it's not very convenient to do that every time. -
What is the replacement of RelatedFilter in newer versions of django_filters?
we have a Django project version 2.0.4, now i am trying to upgrade it to 3.1 the project use djangorestframework-filters, but now this package hasn’t been actively maintained. the problem is one of our FilterSet use RelatedFilter, and i can't find any good replacement for it. the relationship to another FilterSet is essential for the corresponding api. the small part of FilterSet: class SchoolFilter(filters.FilterSet): students__student__registrations__examination = RelatedFilter( ExaminationFilter, queryset=examination_queryset, ) the ExaminationFilterSet has so many filters. -
Input fields are not being updated after editing them in a crud program in django
//edit.html <form action="/update/{{ rec.id }}" method="POST"> {% csrf_token %} Name: <label> <input type="text" name="title" value="{{ rec.name }}" /> </label> <br/> Marks1: <label> <input type="number" name="mark1" value="{{ rec.mark1 }}" /> </label> <br/> Marks2: <label> <input type="number" name="mark2" value="{{ rec.mark1 }}" /> </label> <br/> Marks3: <label> <input type="number" name="mark3" value="{{ rec.mark1 }}" /> </label> <br/> Marks4: <label> <input type="number" name="mark4" value="{{ rec.mark1 }}" /> </label> <br/> <input type="submit" value="Post" /> </form> //show.html <td><a href="/edit/{{ data.id }}">Edit</a></td> //views.py def edit(request, id): ob = Student.objects.get(id=id) return render(request, 'edit.html', {'rec': ob}) def update(request, id): ob = Student.objects.get(id=id) ob.name = request.POST.get('name') ob.marks1 = request.POST.get('marks1') ob.marks2 = request.POST.get('marks2') ob.marks3 = request.POST.get('marks3') ob.marks4 = request.POST.get('marks4') ob.save() return redirect("/show") //urls.py path('edit/<int:id>', views.edit), path('update/<int:id>', views.update), Whenever I hit the edit button and enter the new details, the name field becomes blank and the marks field get initialized to 0; -
Django application deployed on Ubuntu server redirects to login page after successful login
I have deployed django on ubuntu 22 server with nginx as the application server, but when I login in to the system and on each request I get redirected back to the login.` if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") logger.debug(f"Attempting to authenticate user {username}.") user = authenticate(username=username, password=password) if user is not None: logger.debug(f"Authenticated user {username}.") login(request, user) if user.role == 'STAFF': return redirect("sales:sales_list") elif user.role in ["MANAGER", "SUPERVISOR",]: return redirect("authentication:manager_dashboard") elif user.role in ["ADMIN", "GENERAL", "CEO"]: return redirect('master:index') this is how I did the authentication` class SalesListView(ListView): """ View for displaying sales transactions. Requires user to be logged in and have specific roles (STAFF, MANAGER, ADMIN, SUPERVISOR, CEO). Displays sales data based on user role and branch. """ template_name = "manager/purchase/sales.html" model = Sale context_object_name = "sales" def dispatch(self, request, *args, **kwargs): """ Custom dispatch method to handle role-based template selection. Sets different template names based on the user's role. """ user = request.user if not user.is_authenticated: # If not authenticated, redirect to login page messages.error(request, 'You need to log in first!', extra_tags="danger") return redirect('authentication:login') self.branch = user.branch.id self.user_role = user.role print(f"User branch {self.branch} : user role {self.user_role}") if self.user_role == 'STAFF': self.template_name = 'team_member/sales/sales.html' # Set … -
sass.CompileError: File to import not found or readable
I am working on a django project and i decide to use django-simple-bulma but anytime run Python manage.py collectstatic i keep getting sass.compilererror Traceback (most recent call last): File "C:\Users\DIAWHIZ\desktop\themiraclemovement\manage.py", line 22, in <module> main() File "C:\Users\DIAWHIZ\desktop\themiraclemovement\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\django\core\management\base.py", line 459, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 209, in handle collected = self.collect() ^^^^^^^^^^^^^^ File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 126, in collect for path, storage in finder.list(self.ignore_patterns): File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\django_simple_bulma\finders.py", line 216, in list files.extend(self._get_custom_css()) ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\django_simple_bulma\finders.py", line 187, in _get_custom_css css_string = sass.compile(string=scss_string, output_style=self.output_style) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\DIAWHIZ\desktop\themiraclemovement\tmmenv\Lib\site-packages\sass.py", line 725, in compile raise CompileError(v) sass.CompileError: Error: File to import not found or unreadable: []. on line 1:1 of stdin >> @import "[]";