Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
openssl not connecting to gmail server
I'm using ubuntu 22.04 and openssl 1.1.1 This started when I tried to send an email to myself with Django's send_mail() function. The function executed fine, but the email never arrived. Checking the Postfix log revealed this error: connect to alt2.gmail-smtp-in.l.google.com[2607:f8b0:4023:1::1a]:25: Connection timed out Trying to diagnose this led to me to running command-line experiments with openssl. The following command fails with a timeout: # openssl s_client -connect smtp.google.com:587 -starttls smtp 4047B9AF807F0000:error:10000067:BIO routines:BIO_connect:connect error:../crypto/bio/bio_sock2.c:127: 4047B9AF807F0000:error:8000006E:system library:BIO_connect:Connection timed out:../crypto/bio/bio_sock2.c:125:calling connect() ... (several repeats of the error above) ... 403747797B7F0000:error:10000067:BIO routines:BIO_connect:connect error:../crypto/bio/bio_sock2.c:127: connect:errno=110 (The result was the same using "alt2.gmail-smtp-in.l.google.com", which was the domain from the postfix log) I don't think the problem is just my computer or network because trying with "strawberry.active-ns.com" (a domain used by an online example of openssl) works: $ openssl s_client -starttls smtp -connect strawberry.active-ns.com:587 CONNECTED(00000003) ... I have used send_mail() from my laptop in the past, and it has worked fine. Did Google change something? Any help would be greatly appreciated. -
Django - Forms ccreation and handling issue
I'm writing a Django website and I don't actually know which is the best way to organize my Models/Forms fields... I basicall have the following strtuccture (the names are invented): Model CarCompany: name = CharField .... Model Car: name = CharField .... company_name = ForeignKey .... Model Customer: name = CharField .... surname = CharField .... I need to save my model instances making sure there is an assosciation between the customer and all of his cars (and so also related cars.company_names) in the following way: Model CarDealer: name = CharField .... custoom_field = [a list of all the possible assosciations between Car and Customer. The way I thought it is to have a page that renders with the help of Ajax calls a series of rows and in each row I have three select element in which i can select in order: Customer, CarCompany, and (using AJAX), Car. How can I handle at best this situation using Django Forms? -
Testing django haystack integrated with solr backend
I am using Django Haystack which uses Solr for searching and was trying to write tests for this. views.py class CategorySearchAPIView(generics.GenericAPIView): def get(self, request): query = request.query_params.get('q', '') search_results = SearchQuerySet().filter(text__contains = query) results = [] for result in search_results: # my logic return Response(results, status = status.HTTP_200_OK) test.py class SearchCategoriesTest(APITestCase): def setUp(self): self.category1 = Category.objects.create(name="category1") self.category2 = Category.objects.create(name="category2") self.rebuild_index() def rebuild_index(self): call_command('rebuild_index', verbosity=0, interactive=False) def test_search(self): url = # my url response = client.get(url) The problem i am facing here is that, without running the rebuild_index(), my index won't have my newly created categories i.e category1 and category2 and result will be an empty list. But if I run rebuild_index(), my existing index will be overwritten by these two categories and older data is lost. Is there any tips/way I can fix this ? -
Template behavior depends on actual class of an instance in a class hierarchy
In django I have a model A and 3 derived models D1, D2, D3. I also have a ManyToManyField in another model B that references instances of A that can be instances of D1s, D2s or D3s. In the template, if I loop over the instances of A referenced by the ManyToManyField of B. How can I distinguish the display according to whether the actual model of my As is D1, D2 or D3? And how can I access a field which is in D1, but not in A, D2 or D3 when the actual class of my instance is D1? -
Django Allauth - How to Automatically Link Google OAuth Login to Existing User Account Created with Email?
I'm working on a Django project where I've implemented user registration and login functionality using Django Allauth. Users can sign up with their email and password, and I've also added "Login with Google" using OAuth2. The issue I'm facing is that when a user signs up with their email and later tries to log in using "Login with Google," it creates a new account instead of linking to the existing one associated with their email. Is there a way to automatically link the Google OAuth login to the existing user account if the email matches? I want users to be able to seamlessly switch between email-based login and Google OAuth login without creating duplicate accounts. Any guidance or code examples on how to achieve this integration would be greatly appreciated. Thank you! -
file not found during django collectstatic
In my django project collectstatic raises this exception: ValueError: The file 'my_path/exporting.js.map' could not be found with <django.contrib.staticfiles.storage.ManifestStaticFilesStorage object at 0x7f3ee1a444c0>. I recently update to django 4. How can I fix it? Until yesterday it worked, I don't understand, sorry for the ignorance. -
Get group of user in ReactJS for role based permissions on a sidebar
I am creating a role-based permissions for a sidebar in a Django-React using rest_framework project. I have users that belong to different groups. Each groups have different permissions and should have different sidebar menu. In the frontend, how can I get the group of the user that is currently logged in? -
Django admin filter for inline model rows
I have a parent model (Author) & inline models (Book) class Author(models.Model): age = models.IntegerField() class Book(models.Model): name = models.CharField(max_length=250) price = models.CharField(max_length=250) author = models.ForeignKey(Author, on_delete=models.CASCADE) Book model has 3 rows to convey my issue I'm giving UI results in readable dict format {id:1, name:'book1', price: 50, author_id: 1} {id:2, name:'book2', price: 75, author_id: 1} {id:3, name:'book1', price: 65, author_id: 2} in admin.py, i have AuthorAdmin that has a list filter, list_filter = ['age', 'book__name', 'book__price'] in django admin list view page, if i filter /admin/?book__name=book1&book__price=75 it gives Author(id=1), Author(id=2) as result but it should only return the id:1 row alone. kindly help how to use list_filter in m2m relations (inlines) in django admin. i have used __ to filter the inlines, but the results are not accurate. my understanding is that django is returning the parent if atleast 1 of the inline item matches the query. i want the filters to be chained. -
Django form not saving form entries
I am trying to let users enter their own data to a form, but it is not being saved to my database and I can't figure out why. I can add new form entries from the admin, so I'm not sure if I've written things one level too high or something?test entry from admin page I define my submission sheet in models.py: from django.db import models import datetime class Submission(models.Model): project_name = models.CharField(max_length=240) location = models.CharField(max_length=240) # TODO: night be multiple times, try to get working with one for now time = models.DateTimeField() notes = models.CharField(max_length=1000) collector_name = models.CharField(max_length=240) collector_equipment = models.CharField(max_length=240) sample_id = models.CharField(max_length=240) class Meta: # fields = ('project_name', 'location', 'time', 'weather', 'collector_name', 'sample_id') verbose_name_plural = 'submissions' def __str__(self): return self.sample_id and the form itself in forms.py is from django import forms from django_form_builder.forms import BaseDynamicForm from .models import Submission class SubmissionForm(forms.ModelForm): class Meta: model = Submission fields = ( 'project_name', 'location', 'time', 'notes', 'collector_name', 'collector_equipment', 'sample_id', ) labels = { 'project_name': 'Project Name', 'location': 'Location', 'time': 'Time', 'notes': 'Notes', 'collector_name': 'Collector Name', 'collector_equipment': 'Collector Equipment', 'sample_id': 'Sample ID', } help_texts = { 'project_name': 'The project name', 'location': 'Lat/long or comment', 'time': 'Time (on/off) in UTC', 'notes': 'Notes', … -
Most efficient way of triggering DoesNotExist Exception for pk
I want to see if an id exists in the db without getting the instance from the db. And I want to trigger a DoesNotExist exception if it does not exist. This is what I'm currently doing: MyModel.objects.get(pk=my_model_id) but is there a more efficient but clear alternative? -
Should we use `from __future__ import annotations` in python 3.10+?
I know that this question might have more than one correct answer but I would love to get what y'all think. With the discussion going around PEP 563 and PEP 649 and the deprecation of the future, I'm still confused on what the best practice is. Looking at the two examples below: what would be future proof? What would be more performant? Which one is better supported by tools such as pyupgrade, ruff, or flake8-type-checking? In example 2, which syntax is preferred between queries and queries_2? Example 1: from __future__ import annotations from typing import TYPE_CHECKING from collections.abc import Iterable from django.contrib.auth.models import User if TYPE_CHECKING: from django.db.models import QuerySet users: QuerySet[User] = User.objects.all() queries: Iterable[QuerySet] = ... Example 2: from typing import TYPE_CHECKING from collections.abc import Iterable from django.contrib.auth.models import User if TYPE_CHECKING: from django.db.models import QuerySet users: "QuerySet[User]" = User.objects.all() queries: Iterable["QuerySet"] queries_2: "Iterable[QuerySet]" in the examples above, we can assume Iterable is not in TYPE_CHECKING because it is used elsewhere in the file. -
In Django how to use request to retrieve a selected value in a dropdown and split it into two separate values?
Currently I recover the selected value of the third dropdown (Extract_single_city) like this: city = request.GET.get("extract_single_city") I would like to do the same to recover the values of the second dropdown (Trip), using request, but creating two values (for example create departure to recover Madrid, and create destination to recover Barcelona). I'm using this solution with global, but I don't like it, I would like to use something with request global departure, destination departure = trip.city_departure.name, destination = trip.city_destination.name views.py def trip_selector(request): if "Hx-Request" in request.headers: trips = FullRecord.objects.none() #Dropdown 1: Country if request.headers["Hx-Trigger"] == "id_trip": country_id = request.GET.get("country") #Dropdown 2: Trips if country_id != "": trips = FullRecord.objects.filter(country_id=country_id) return render(request, "trips.html", {"trips": trips}) #Dropdown 3: Single City elif request.headers["Hx-Trigger"] == "id_extract_single_city": selected_trip = request.GET.get("trips") extracted_cities = [] #Extract single city if selected_trip != "": trip = FullRecord.objects.get(id=int(selected_trip)) trip_with_combined_names = trip.departure_destination split_trip = trip_with_combined_names.split("-") extracted_cities = split_trip return render(request, "extract_single_city.html", {"options": extracted_cities}) else: countries = Country.objects.all() return render(request, "form.html", {"countries": countries}) forms.html {% extends 'base.html' %} {% block main-content %} <div class="flex justify-between px-10 gap-5 mt-5"> <div class="flex flex-col w-full"> <!-- First Combobox --> <label for="id_country">Country</label> <select name="country" id="id_country"> <option value="">Please select</option> {% for country in countries %} <option value="{{ … -
Proxy database conection fails in django application running in ECS
I deployed both a django app and a ngnix proxy containers in ECS. The app container is running without errors. I could also connect to the database using a bastion instance and create a superuser. However, the proxy container has given me an error. Currently, it throws: django.db.utils.OperationalError: could not connect to server Should this error happen in the proxy? I'm confused. It looks like the connection to the database is working for Django. Here is the entrypoint bash using in the Django container: set -e python manage.py collectstatic --noinput python manage.py wait_for_db python manage.py migrate uwsgi --socket :9000 --workers 4 --master --enable-threads --module app.wsgi and here are the django container logs: spawned uWSGI worker 1 (pid: 11, cores: 1) spawned uWSGI worker 2 (pid: 12, cores: 1) spawned uWSGI worker 3 (pid: 13, cores: 1) spawned uWSGI worker 4 (pid: 14, cores: 1) WSGI app 0 (mountpoint='') ready in 2 seconds on interpreter 0x7f2e0c0b9980 pid: 10 (default app) | *** uWSGI is running in multiple interpreter mode *** spawned uWSGI master process (pid: 10) mapped 364600 bytes (356 KB) for 4 cores *** Operational MODE: preforking *** Python main interpreter initialized at 0x7f2e0c0b9980 python threads support enabled your server … -
Problem with applying CSP policy for Google fonts file
I'm working on Django site (upgrade from version 2 to version 4), where I have to apply Content Security Policy. In other projects I did it with django-csp using project's settings, but in this case I only add 'csp.middleware.CSPMiddleware', to MIDDLEWARE settings, and all CSP is done by <meta http-equiv="Content-Security-Policy" ... tags. That's the first strange thing. After rendering the code of my home page looks like this: The error is: Refused to load the stylesheet 'https://fonts.googleapis.com/css?family=Roboto:wght@300' because it violates the following Content Security Policy directive: "default-src 'self' 'nonce-d0R7xtS9JR5LNg6UqQ5FCg=='". Note that 'style-src-elem' was not explicitly set, so 'default-src' is used as a fallback. The second strange thing is that I set the style-src-elem, but the error says I didn't. And information from DevTools: Why is it blocked? The fonts are available here I used the hints from the official CSP site on Google fonts here and everything seems to be OK, but the problem still exists. -
do not show the dynamic data in the tag list
[enter image description here](https://i.stack.imgur.com/g5sdk.jpg) in the image Turkish words: Kategori = category , Etiket = Tag I want to dynamically see the categories and tags I marked from the admin panel from the category and tag template, but they do not appear. I do not understand where I dıd wrong. topics html codes html {% extends 'partials/_base.html' %} {% load static %} {% block content %} <div class="all-title-box"> <div class="container text-center"> <h1>Courses</span></h1> </div> </div> <div id="overviews" class="section wb"> <div class="container"> <div class="row"> <div class="col-lg-9 blog-post-single"> <div class="row" style=""> {% for topic in topics %} <div class="col-lg-6 col-md-6 col-12 mb-4"> <div class="course-item"> <div class="image-blog"> <img src="{{topic.image.url}}" alt="" class="img-fluid"> </div> <div class="course-br"> <div class="course-title"> <h2><a href="{% url 'topic_detail' topic.category.slug topic.id %}" title="">{{topic.name}}</a></h2> </div> <div class="course-desc"> <p>{{topic.description | truncatechars:100}}</p> </div> </div> <div class="course-meta-bot"> <ul> <li><i class="fa fa-calendar" aria-hidden="true"></i> {{topic.date|date:"d M Y"}}</li> <li><i class="fa fa-book" aria-hidden="true"></i> {{topic.writer}}</li> </ul> </div> </div> </div><!-- end col --> {% endfor %} </div><!-- end row --> </div><!-- end col --> <div class="col-lg-3 col-12 right-single"> <div class="widget-search"> <div class="site-search-area"> <form method="get" id="site-searchform" action="#"> <div> <input class="input-text form-control" name="search" placeholder="Anahtarkelime ara..." type="text"> <input id="searchsubmit" value="Search" type="submit"> </div> </form> </div> </div> <div class="widget-categories"> <h3 class="widget-title">Kategori</h3> <ul> {% for category in categorys %} … -
Python Django Json Data Serialization
I've got an issue where I want to pass the whole data set of the profile page using data serialization as below, however the issue is that I get the output data with single quotes instead of double and I cannot parse it later on: View: def profile_page(request): if request.method == 'POST': form = WeightLogForm(request.POST) if form.is_valid(): weight_log = form.save(commit=False) weight_log.profile = Profile.objects.get(user=request.user) weight_log.save() return redirect('profile') else: form = WeightLogForm() user_weight_log = WeightRecord.objects.filter(profile__user=request.user).order_by('-entry_date') paginator = Paginator(user_weight_log, 10) page = request.GET.get('page') try: user_weight_log = paginator.page(page) except PageNotAnInteger: user_weight_log = paginator.page(1) except EmptyPage: user_weight_log = paginator.page(paginator.num_pages) serialized_data = [{'weight': str(record.weight), 'entry_date': record.entry_date.strftime('%Y-%m-%d')} for record in user_weight_log] return render(request, 'profile.html', { 'user_weight_log': user_weight_log, 'form': form, 'weight_data': serialized_data }) Html Template: <div id="weight-data" data-weight-data="{{ weight_data|safe }}"></div> Data output: [{'weight': '122.00', 'entry_date': '2023-09-28'}, {'weight': '123.00', 'entry_date': '2023-09-18'}, {'weight': '44.00', 'entry_date': '2023-09-15'}, {'weight': '85.00', 'entry_date': '2023-09-06'}, {'weight': '11.00', 'entry_date': '2023-09-06'}, {'weight': '12.00', 'entry_date': '2023-09-05'}, {'weight': '17.00', 'entry_date': '2023-09-05'}, {'weight': '44.00', 'entry_date': '2023-08-08'}, {'weight': '17.00', 'entry_date': '2023-06-08'}, {'weight': '33.00', 'entry_date': '2023-06-07'}] Javascript: var weightDataElement = document.getElementById('weight-data'); var weightDataJSON = weightDataElement.getAttribute('data-weight-data'); var weightData = JSON.parse(weightDataJSON); The error I get: Uncaught SyntaxError: JSON.parse: expected property name or '}' at line 1 column 3 of the JSON data -
Creating a link in ReactJS that will go to the Django admin site
I am looking for a way to link the Django admin site from ReactJS. Initially the domain of Django admin site is '127.0.0.1/admin' but the domain '127.0.0.1' will eventually change. Is there a way to make a dynamic code for this? -
Using prefix_default_language=False disable javascript translations
I have implemented javascript translations, following exactly the documentation. It works perfectly when I use prefix_default_language=True in my i18n_patterns fonction. But when prefix_default_language is set to False, all of the translations in javascript code are not working : document.write(gettext("this is to be translated")) Is this a know issue? Is there something Im missing? -
DRF Shows incorrect schema
I have a following viewset: class MyViewSet: @action(detail=False) def statuses(self, *args, **kwargs): serializer = self.get_serializer(MyModel.Statuses, many=True) return Response(serializer.data) And serializer for it: class LabelValueSerializer(serializers.Serializer): label = serializers.CharField() value = serializers.CharField() class Meta: fields = ("label", "value") I get the correct API response: [ { "label": "New", "value": "new" }, { "label": "Processing", "value": "processing" }, { "label": "Finished", "value": "finished" } ] But the Swagger API suggest that the model is like this suggesting only 1 object is returned and not the list of them. How can I fix this and get the documentation like: [ { "label": string, "value": string } ] -
Huey Monitor - Error occurred sending signal "executing" - database kills the connection
In a Django 4.1 project I have huey (2.4.5) with django-huey (1.1.1) and django-huey-monitor (0.7.1) set up. Redis broker. 5 queues, including default, and are run in docker containers: PYTHONBUFFERED=1 python manage.py djangohuey --queue queue_name --no-periodic --force-color The monitor is initialised as such in tasks/__init__.py: for queue_name in settings.DJANGO_HUEY["queues"].keys(): signal(queue=queue_name)(store_signals) on_startup(queue=queue_name)(startup_handler) Since adding django-huey-monitor Sentry has started to catch exceptions in @db_task tasks Error occurred sending signal "executing" OperationalError server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. Now, I've experienced something like that in the past (5+ years ago) and usually, it helped to add connection.close() at the end of the task imported from django.db thous @db_task should do it anyway. Now everything was running smoothly, @db_task and all, until I added signal monitoring. I tested one @db_task that should be closing the connection anyway, added the connection.close() - that one seems to go silent but another one started acting up. I'd like to solve it globally and have run out of ideas. Are the signals misconfigured? -
error: SMTP AUTH extension not supported by server
I want to send an email to change the password by using this module: from django.contrib.auth import views as auth_views and these are the detail in setting.py: # google account setting EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'MY EMAIL ADDRESS' EMAIL_PORT = 587 EMAIL_HOST_PASSWORD = 'MY PSSWORD' EMAIL_USER_TLS = True DEFAULT_FROM_EMAIL = 'TEST site' I read that I should change the PORT to 465. When I changed that I got another error: SMTPServerDisconnected at /account/reset/ Connection unexpectedly closed What can I do to fix the problem? -
How to show django-allauth errors in my form
I have overrode django-allauth login page and signup page templates. But how can I show their errors? (errors like "your password is wrong", "passwords doesn't match", etc.) -
python django ,i got error in doing registrion for new account
Manager isn't available; 'auth.User' has been swapped for 'user.CustomUser' Request Method: POST Request URL: http://localhost:8000/auth/register/ Django Version: 4.2.5 Exception Type: AttributeError Exception Value: Manager isn't available; 'auth.User' has been swapped for 'user.CustomUser' Exception Location: /home/greyhack199926/Downloads/django/env/lib/python3.11/site-packages/django/db/models/manager.py, line 196, in __get__ Raised during: user.views.register_view Python Executable: /home/greyhack199926/Downloads/django/env/bin/python Python Version: 3.11.4 Python Path: ['/home/greyhack199926/Downloads/django/Main', '/usr/lib/python311.zip', '/usr/lib/python3.11', '/usr/lib/python3.11/lib-dynload', '/home/greyhack199926/Downloads/django/env/lib/python3.11/site-packages'] Server time: Fri, 08 Sep 2023 08:01:22 +0000 i can not register account -
How to Import data from json to SQL database using django
I am in need of a guidance, any help would be much appreciated. I'm new to django ,and right now I am designing a web application based on django framework, The application uses SQL database, However the data that the application needs is being provided through a json file that's being regenerated every few seconds,now my question is, how can I export the json file into sql database using django.. How can I do it? The web application is a financial application , so the accuracy of the data and the data being updated as soon as being generated is a must. -
Efficiency and Challenges in a Multi-Layered Testing Platform with Microservices Transition
enter image description here First, let me introduce my platform. The platform is divided into three layers, as shown below: Piece Layer: It consists of a single user interaction action (e.g., click, input, keyword entry), followed by waiting for a specific element to load (or waiting for a fixed duration), and finally capturing a screenshot of the element for text validation. This combination is referred to as a "piece." It is the smallest operational unit and cannot be further divided. Process Layer: Multiple pieces are combined to form a process. A dataset can be added to a process, which can generate multiple test cases (referred to as "cases"). Case Layer: This layer manages the execution of test cases and allows viewing of execution results. Result Validation: Text validation is done through direct text comparison, while image validation utilizes AI for image comparison. Technology Stack: Python, Django, Playwright, TensorFlow, Docker, GitLab CI/CD. Questions: I am currently running 200+ test cases using a thread pool with 8 threads, and the execution is quite slow. I am in the process of refactoring the code and transitioning to a microservices architecture. Previously, everything was handled by a single Docker image, but now I want …