Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Optimizing Django QuerySet with Nested Aggregations
I’m working on optimizing a complex Django query where I need to perform nested aggregations and conditional annotations across multiple related models. I want to fetch the top 5 most active users based on their interactions with posts, while also calculating different types of engagement metrics (like views, comments, and likes). My models: class User(models.Model): name = models.CharField(max_length=100) class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255) created_at = models.DateTimeField() class Engagement(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) type = models.CharField(max_length=50) # 'view', 'like', 'comment' created_at = models.DateTimeField() Here is what my code looks like: from django.db.models import Count, Q some_date = ... top_users = ( User.objects.annotate( view_count=Count('engagement__id', filter=Q(engagement__type='view', engagement__created_at__gte=some_date)), like_count=Count('engagement__id', filter=Q(engagement__type='like', engagement__created_at__gte=some_date)), comment_count=Count('engagement__id', filter=Q(engagement__type='comment', engagement__created_at__gte=some_date)), total_engagements=Count('engagement__id', filter=Q(engagement__created_at__gte=some_date)) ) .order_by('-total_engagements')[:5] ) It works, however the query performance is not ideal. With large datasets, this approach leads to slow query execution times and I wonder whether using multiple Count annotations with filter conditions is efficient. Is there a more optimized way to write this query, or any best practices I should consider for improving performance, especially when dealing with large amounts of data? Any insights or suggestions would be really helpful! -
Django dynamically adding integer fields to forms
Hi I have a very simple application that I am making in order to learn Django. I have a SQLite table that has two columns, the first is the 'id' generated by Django, the second is a charfield containing the name of a product_name. The way I am trying to get the program to work is as follows: Get value list of values in the table. This query_set gets assigned to bases Loop through the each tuple in the bases list and use these values to create form fields. So the product_name will be the Label and the id will be the id of the field. I will later use Jquery on these fields to get the values. I have the following code: from django import forms from django.db import models from django.core.exceptions import ValidationError from .models import Department, Test_list, Products, Current_tests class Batch(forms.Form): bases = Products.objects.all().values_list('product_name','id') for i in bases: for j in [0,1]: bn = i[0] bnid = i[1] name = forms.IntegerField(label=f"{bn}",widget=forms.NumberInput(attrs={"id":bnid})) The code actually works but instead of getting a number of text inputs equal to the rows in my database, it only shows the last row. I believe this is because while in the loop, I … -
Django + jQuery: No Image Provided Error with 400 31 Response When Uploading Image via AJAX
I'm working on a Django project where I'm uploading an image to be processed by a machine learning model. The frontend uses jQuery to send the image via an AJAX request. However, the server keeps returning the error: {"error": "No image provided."} and Accuracy: NaN%. Additionally, I receive the response 400 31 in the browser console. Frontend (AJAX and HTML Code): <script> $(document).ready(() => { $("input[id='image']").on('change', function (event) { let input = this; var reader = new FileReader(); reader.onload = function (e) { $('#banner').css('width', '350px') $('#banner').addClass('img-thumbnail') $('#banner').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); }) $('#process').click(() => { $('.buttons').hide() $('.loader').show() $('#title').html("Processing...") let image = $('#image').prop('files')[0] var data = image['name']; console.log(data) $.ajax({ url: "http://127.0.0.1:8000/api/", type: "POST", dataType: 'json', data: { image: data, csrfmiddlewaretoken: '{{ csrf_token }}' }, headers: { 'Authorization': 'z*qm$(e9k0wa--t!^ux(xn15vk$)h7c$%3%vflo^@_++bg&uw(', // CSRF token 'Content-Type': 'application/json' // JSON }, success: function (xhr) { alert("Error while processing") }, error: function (xhr) { $('#title').html("Result") let result = (xhr.responseText).split("-"); let disease = result[0]; let accuracy = result[1]; $('.loader').hide() $('#disease').html("Result: " + disease) $('#accuracy').html("Accuracy: " + parseInt(accuracy).toFixed(2) + "%") $('#graph').attr('src', '{% static "graph.png" %}') $('.result').show() } }); }); }); </script> Django Views.py: from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse, JsonResponse from diab_retina_app import process … -
Rendering MultiValueField including help_text and label for each subfield
I am using a JSONField to represent a config that is used in multiple forms. Instead of the default Textarea widget, I want to render multiple fields each with their own label and help_text. I am able to achieve this by implementing a Form just for the config but it seems it should also be possible (and cleaner) to represent the config as a MultiValueField. Unfortunately I cannot for the life of me figure out how to render the label and the help_text when following this approach as that information seems no longer available when the widget is rendered. What am I missing? class ConfigWidget(forms.MultiWidget): template_name = 'config_widget.html' def __init__(self, attrs=None): widgets = [ forms.TextInput(attrs=attrs), forms.TextInput(attrs=attrs), ] super().__init__(widgets, attrs) def decompress(self, value): if isinstance(value, dict): return [value['foo'], value['bar']] return [None, None] class ConfigField(forms.MultiValueField): widget = ConfigWidget def __init__(self, *args, **kwargs): fields = ( forms.CharField(label='Foo', help_text='Foo help.'), forms.CharField(label='Bar', help_text='Bar help.'), ) super().__init__(fields=fields, *args, **kwargs) def compress(self, data_list): if data_list: return { 'foo': data_list[0], 'bar': data_list[1], } -
Django test client redirects logged users to login page
I know this questions has already been asked, but none of the answers works for me. Whenever I try to use the client login in Django tests, it basically gets ignored and I get a redirect to the login page. After a few test I noticed that it logs me in correctly, but kicks me out when I use it. Here is a stripped down version of my code that still reproduces this. from django.auth import get_user() class MapListViewTest(TestCase): @classmethod def setUpTestData(cls): # Create a user cls.user = get_user_model().objects.create(username="testuser") cls.user.set_password("password") cls.user.save() # [...] def setUp(self): self.client.login( username=self.user.get_username(), password=self.user.password ) def test_map_list_view_renders(self): """Test that the MapListView renders successfully and includes a list of maps.""" logger.info(get_user(self.client)) # <-- <django.contrib.auth.models.AnonymousUser object at 0x7377d5589540> self.client.login( username=self.user.get_username(), password=self.user.password ) logger.info(get_user(self.client)) # <-- <Profile: testuser> response = self.client.get(reverse("map_list"), follow=True) logger.info(get_user(self.client)) # <-- <django.contrib.auth.models.AnonymousUser object at 0x7377d5589540> self.assertEqual(response.status_code, 200) # <-- OK self.assertTemplateUsed(response, "map_list.html") # <-- lands on 'account/login.html' (I put it twice here in the snippet, but it is only in the setUp in the real code) I don't know if this is of any relevance, but the redirection changes the address from http://localhost/... to http://testserver/..., and I am working in a docker container. Also, the … -
Save number of total search query count on models in Django
Below is my Django code to save user searches on database. How can I implement a function that when a same user searches same keywords for multiple time I need to record count of that keywords on database if its logged in user or session user def get_queryset(self): query = self.request.GET.get('q') if query: if self.request.user.is_authenticated: if not search_keywords.objects.filter(user=self.request.user, search_word=query).exists(): search_keywords.objects.create( user = self.request.user, search_word = query, session_id = session_id ) else: if not search_keywords.objects.filter(session_id=session_id, search_word=query).exists(): search_keywords.objects.get_or_create( session_id=session_id, search_word = query, ) search_vector = ( SearchVector('title', weight='A') + SearchVector('description', weight='B') + ) search_query = SearchQuery(query) return items.objects.annotate( rank=SearchRank(search_vector, search_query) ).filter(rank__gt=0.1).order_by('-rank') return items.objects.none() -
Token authentication not working in Django Rest Framework after passing the token
Session authentication is working correctly as I am getting "You are authenticated!" if I login from the Django admin, but token authentication isn't functioning and I am getting error "Authentication credentials were not provided." pip freeze Django==5.1.2 django-filter==24.3 djangorestframework==3.15.2 djangorestframework-simplejwt==5.3.1 Following are the project files views.py from django.shortcuts import render from rest_framework import generics, permissions from .models import Artist from .serializers import ArtistSerializer from rest_framework.authentication import TokenAuthentication class ArtistListCreateView(generics.ListCreateAPIView): queryset = Artist.objects.all() serializer_class = ArtistSerializer permission_classes = [permissions.IsAuthenticated] authentication_classes = [TokenAuthentication] def perform_create(self, serializer): serializer.save(user=self.request.user) class ArtistDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Artist.objects.all() serializer_class = ArtistSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): print("Authenticated user:", self.request.user) return Artist.objects.filter(user=self.request.user) serializers.py from rest_framework import serializers from .models import Artist class ArtistSerializer(serializers.ModelSerializer): class Meta: model = Artist fields = ['id', 'user', 'phone_country_code', 'phone', 'location', 'created_at', 'updated_at'] read_only_fields = ['id', 'user','created_at', 'updated_at'] models.py from django.contrib.auth import get_user_model from django.db import models User = get_user_model() class Artist(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='artist_profile') phone_country_code = models.CharField(max_length=10) phone = models.CharField(max_length=15) location = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username urls.py from django.urls import path from .views import ArtistListCreateView, ArtistDetailView urlpatterns = [ path('artists/', ArtistListCreateView.as_view(), name='artist-list-create'), path('artists/<int:pk>/', ArtistDetailView.as_view(), name='artist-detail'), ] I have tried updating the settings.py with following details … -
SSL is required, but the server does not support it (Django)
I was working on a test project as a practice and when I tried migrating it to the database (MariaDB PhpMyAdmin), I get this error "django.db.utils.OperationalError: (2026, 'TLS/SSL error: SSL is required, but the server does not support it')" This is how I wrote it in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'schooldb', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3307', # 'OPTIONS': {'init_command': "SET SQL_MODE='STRICT_TRANS_TABLES'"}, } } I already have mysqlclient installed. -
Python requests Session not passing cookies?
I have followed the documentation as far as I can tell, but it seems that the requests library Session object is not retaining cookies. Here is my simple code: with requests.Session() as s: url = '%s://'%http+serverStr+'/login/' s.get(url) payload = {'username': 'sfprod', 'password': <password>, 'csrfmiddlewaretoken': s.cookies['csrftoken'], 'next': '/'} login_resp = s.post(url, data=payload, headers=(dict(Referer=url))) This is connecting to a Django server. When I run the first s.get() call I see these cookies returned: <RequestsCookieJar[Cookie(version=0, name='csrftoken', value='Iw2k4RF5QIy6oNOA71681oq4kGVBxjzTmQCULicbWdr5ZfH1Kunrn30DNupQtFhF', port=None, port_specified=False, domain='gancho.local', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=True, expires=1761043315, discard=False, comment=None, comment_url=None, rest={'SameSite': 'Lax'}, rfc2109=False)]> However when the second call happens, no cookies are passed to the server. The COOKIES member of the request object received is empty and the server returns 403 Forbidden. I stepped through the csrftoken code in the debugger and it is rejecting the request because the cookie is not present (to be precise, because there is no CSRF_COOKIE value in the META member of the request, but I assume this is because the cookie is not present). I can log in with a browser, and in this case I see the cookie in the request, so I think it is not a setup problem with the server. Is there something I … -
Is it safe and ok to divide mp3 file like that?
I have an mp3 file and want to divide it into several files ("chunks"). I came up with this code (I stole the idea from django): from pathlib import Path class FileWrapper: def __init__(self, file) -> None: self.file = file def chunks(self, chunk_size): chunk_size = chunk_size try: self.file.seek(0) except (AttributeError, Exception): pass while True: data = self.file.read(chunk_size) if not data: break yield data with open("./test2.mp3", "rb+") as src: wrapper_file = FileWrapper(src) for chunk_ind, chunk in enumerate(wrapper_file.chunks(chunk_size=100 * 1024)): out_file_path = Path("./", f"test2_{chunk_ind}.mp3") with open(out_file_path, "wb+") as destination: destination.write(chunk) And, you know, it's working okay, but I'm scary and in doubt, that this approach can sometimes work, but sometimes it maybe can "brake" resulted "chunks". So, is this way - okay? Or I need to dive deeper into how mp3 files made? -
"GET /static/assets/css/plugins/something.css.map HTTP/1.1" 404
I am getting this error every time I reload my website. And for this error it's taking so much time to reload the website. but my stylings from .css and .js are working. I am getting this errors in my terminal - [22/Oct/2024 03:51:18] "GET /static/assets/css/demos/demo-6.css HTTP/1.1" 304 0 [22/Oct/2024 03:51:18] "GET /static/assets/css/custom-old.css HTTP/1.1" 304 0 **[22/Oct/2024 03:51:20] "GET /static/assets/css/plugins/jquery.countdown.css.map HTTP/1.1" 404 1989 [22/Oct/2024 03:51:20] "GET /static/assets/css/plugins/magnific-popup/magnific-popup.css.map HTTP/1.1" 404 2028 [22/Oct/2024 03:51:20] "GET /static/assets/css/style.css.map HTTP/1.1" 404 1932 [22/Oct/2024 03:51:20] "GET /static/assets/css/plugins/owl-carousel/owl.carousel.css.map HTTP/1.1" 404 2016 [22/Oct/2024 03:51:20] "GET /static/assets/css/demos/demo-6.css.map HTTP/1.1" 404 1953 [22/Oct/2024 03:51:20] "GET /static/assets/css/skins/skin-demo-6.css.map HTTP/1.1" 404 1968 [22/Oct/2024 03:51:20] "GET /static/assets/css/bootstrap.min.css.map HTTP/1.1" 404 1956 [22/Oct/2024 03:51:20] "GET /static/assets/js/bootstrap.bundle.min.js.map HTTP/1.1" 404 1971 [22/Oct/2024 03:51:20] "GET /static/assets/js/jquery.plugin.min.map HTTP/1.1" 404 1953 [22/Oct/2024 03:51:20] "GET /static/assets/js/jquery.countdown.min.map HTTP/1.1" 404 1962** I am using soome jquery plugins. Here's i am linking the files in my base.html CSS - <link rel="stylesheet" href="{% static 'assets/css/style.css'%}"> <link rel="stylesheet" href="{% static 'assets/css/skins/skin-demo-6.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/demos/demo-6.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css"> <link rel="stylesheet" href="http://dodsoftware.com/sotests/fancy/jquery.fancybox-1.3.4.css" type="text/css" media="screen" /> <link rel="stylesheet" href="{% static 'assets/css/custom-old.css'%}"> <link rel="stylesheet" href="{% static 'assets/css/custom.css'%}"> JAVASCRIPTS - <script src="{% static 'assets/js/jquery.elevateZoom.min.js' %}"></script> <script src="{% static 'assets/js/jquery.magnific-popup.min.js' %}"></script> <script src="{% static 'assets/js/jquery.plugin.min.js' %}"></script> <script src="{% static 'assets/js/jquery.countdown.min.js' … -
mysqlclient not found even after installed in Django on MacOS
I use pyenv to create a virtual-env, and install mysqlclient in it successfully. But when I python manage.py runserver, it shows 'Did you install mysqlclient?'. How to resoleve it? I try it both in terminal and PyCharm, all did not work. I also looked up a lot of technical forums and basically said that the virtual environment mismatch is the reason, and no one is in the same situation as me. -
How do I avoid a SuspiciousFileOperation when uploading a Django photo?
from django_resized import ResizedImageField class UserProfilePhoto(Model): photo = ResizedImageField(size=[128, 128], upload_to=MEDIA_ROOT) photo_hash = BigIntegerField( blank=True, null=True, help_text=_("an integer representation of the hexdigest hash of the photo"), ) def __str__(self): return f"{self.photo.name} ({self.photo_hash})" I used to have a save() operation in the model, which would do the resizing but now I'm using Django-resized because after all that figuring out how to resize the photo and generate a hash value it turns out there is a module to do it already. I'm adding a picture to the userprofilephoto in the admin. SuspiciousFileOperation at /admin/userprofile/userprofilephoto/add/ Detected path traversal attempt in '/app/mine/media/mendlebrot-lawn.jpeg' How do you turn off the error or the validation? To answer some questions in advance: No. I'm not going to go back to ImageField() It gave me the same problem with lots more code. -
how to fix my register view that generates a token and assigns it to a cookie? django error
Hello I am having trouble building a register view for my django homework assignment. I'm a beginner and trying to work on my register functionality and the views file is where I am having trouble. It's supposed to add a new user to user table in the database, and create a session key string and assign it to the cookie so the user can stay signed in. Whenever I submit a new user it redirects and gives me this error ValueError: Field 'id' expected a number but got 'pjtjtksydunpdysgxcxtmpazfyawvqzg' (my generated string) Here's my register view def register(request: HttpRequest): if request.method == 'POST': params = request.POST user = User( name = params.get("name"), email = params.get("email"), password_hash = params.get("password") ) hasher = hashlib.sha256() hasher.update(bytes(user.password_hash, "UTF-8")) user.password_hash = hasher.hexdigest() user.save() token = "" letters = string.ascii_lowercase for _ in range(32): token = "".join(random.choice(letters) for _ in range(32)) session_token = Session.objects.create(user=user, token=token) response = redirect("/") response.set_cookie('token', token) return response return render(request, "destination/register.html") here are my models in case if needed class User(models.Model): id = models.BigAutoField(primary_key=True) name = models.TextField() email = models.EmailField(unique=True) password_hash = models.TextField() class Session(models.Model): id = models.BigAutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) token = models.TextField() register.html <!DOCTYPE html> <html lang="en"> <head> <meta … -
Excel File Corrupted When Downloaded from Django Backend via Axios in Vue.js
I'm trying to download an Excel file from my Django backend to the frontend using Axios and FileSaver.js (also tried without this). The file is generated successfully on the backend, but when I download it through the frontend, the file becomes corrupted and cannot be opened by Excel. I am using pandas to create the Excel file in-memory and then return it as a response. Backend code - buffer = BytesIO() with pd.ExcelWriter(buffer, engine='xlsxwriter') as writer: for item in data_list: attributes = item['attributes'] attributes['ID'] = item['id'] df = pd.DataFrame([attributes]) sheet_name = f"Sheet_{item['id']}" df.to_excel(writer, sheet_name=sheet_name, index=False) buffer.seek(0) response = HttpResponse(buffer, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename="data_export.xlsx"' return response Frontend code - async function downloadFile() { try { const response = await axios.get('/api/export-excel', { responseType: 'blob', }); saveAs(new Blob([response.data]), 'data_export.xlsx'); } catch (error) { console.error('Error downloading file:', error); } } I know there are similar questions already asked and I have already tried those things (using arraybuffer, type - ms-excel, also tried using openpyxl) but none seems to work. What could be causing the file corruption during download via the frontend? How can I ensure that the file downloads correctly and opens in Excel without corruption? Any advice or suggestions would be greatly … -
Django problem cannot connect to PostgreSQL server in Docker container
I have this logs 2024-10-21 23:55:07 django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: Connection refused 2024-10-21 23:55:07 Is the server running on that host and accepting TCP/IP connections? 2024-10-21 23:55:07 connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused 2024-10-21 23:55:07 Is the server running on that host and accepting TCP/IP connections? but my PostgreSQL server is working proprely there are my postgres logs 2024-10-21 23:50:15 2024-10-21 18:50:15.916 UTC [29] LOG: database system was shut down at 2024-10-21 18:50:14 UTC 2024-10-21 23:50:15 2024-10-21 18:50:15.918 UTC [1] LOG: database system is ready to accept connections database setting inside django DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'pgdb', 'USER': 'postgres', 'PASSWORD': 'admin', 'HOST': 'localhost', 'PORT': '5432', } } compose file version: '3.8' services: web: build: . command: bash -c "python /app/manage.py migrate && python /app/manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 depends_on: - postgres volumes: - .:/app postgres: image: postgres:latest environment: POSTGRES_DB: pgdb POSTGRES_USER: postgres POSTGRES_PASSWORD: admin ports: - "5433:5432" dockerfile FROM python:3.11 WORKDIR /app COPY . /app RUN pip install -r requirements.txt && pip install psycopg2-binary COPY . . I want just run django server on docker, I have tried to run my friend's completed project … -
django-react basic system architecture required
I am trying to understand how a django react project operates? If someone can give me a rough system architecture it would be really helpful. I am creating a music room based on spotify API using django react as my pillars of the project. Help me create a system architecture for it -
gradual migration of django monolith to async
I have huge django2 app (without django ORM) and I want to make it asynchronous. Right now i've come up with two strategies: upgrade to django 3/4 and migrate to async view by view add separate app (fastapi), migrate each view to the new app, and while migration is in progress split traffic between apps on load balancer level. the problem with first approach is that django will switch between sync and async mode and I will not see any improvements before migrating most of the views. the problem with second approach is that it is somewhat complicated and will require more code migrations and infra tinkering. any suggestions? -
Django Environment Identifying the DEBUG as False while it is set to True
I get and error CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False Below are the edits I attempted seeing at stackoverflow's suggestion from various (queries)[https://stackoverflow.com/questions/66923320/why-it-doesnt-set-debug-true] around 5 of them were relevant and tried to edit accordingly. ... I also checked for views and urls for any filename mistyping and typo errors. Yet I am getting CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False. I closed the session and changed the open .py file default from vscode and then with python. Yet this error is persistent PLEASE HELP My settings.py has DEBUG = TRUE ALLOWED_HOSTS = [] I have also tried ALLOWED_HOSTS = ['*'] then ALLOWED_HOSTS = ['localhost'] then ALLOWED_HOSTS = ['127.0.0.1'] then ALLOWED_HOSTS = ['localhost', '127.0.0.1'] once with DEBUG = FALSE and then with DEBUG = TRUE Alternately I Tried this TEMPLATE_DEBUG = DEBUG if not DEBUG: ALLOWED_HOST = ['0.0.0.0', '127.0.0.1','localhost','*'] ALLOWED_HOSTS = []``` The issue still persists despite Changing VS code settings .py extension change from VSCODE to Python interpreter and vice versa. -
Django circular import (models-views(-forms))
Watched all the previous related topics devoted to this problem, but haven't found a proper solution, so decided to create my own question. I'm creating a forum project (as a part of the site project). Views are made via class-based views: SubForumListView leads to a main forum page, where its main sections ("subforums") are listed. TopicListView, in its turn, leads to the pages of certain subforums with the list of active topics created within the subforum. ShowTopic view leads to a certain topic page with a list of comments. The problem manifests itself because of: Models.py: Method get_absolute_url in the model Subforum, which in its return section's reverse function takes a view as the 1st argument; I've tried to avoid a direct import of the view, but the program doesn't accept other variants; Views.py: most of the views have imported models either in instance arguments (model = Subforum), or in methods using querysets (like in get_context_data: topics = Topic.objects.all()); I can't surely say whether the change of instance argument model = Subforum to model = 'Subforum' really helps, as it's impossible to do with queryset methods and thus can't be proved; Forms.py: my form classes were created via forms.ModelForm and … -
Django: How to add objects to ManyToManyFields of multiple objects in a fast way?
We have models.py file : class Car(models.Model): brand = models.CharField(max_length=50 , null=True , blank=True) sub_brand = models.CharField(max_length=50 , null=True , blank=True) code = models.CharField(max_length=20 , unique=True) class Skill(models.Model): car = models.ForeignKey(Car , on_delete=models.CASCADE, null=True , blank=True) skill = models.CharField(max_length=50 , null=True , blank=True) class Provider(models.Model): name = models.CharField(max_length=100) skills = models.ManyToManyField(Skill , blank=True) and we want to add some skills based on cars to the provider model so I use views.py like this: def skills_add(request , id): provider = get_object_or_404(Provider , id=id) if request.method == 'POST': form = AddSkill(request.POST) if form.is_valid(): data = form.cleaned_data cars = Car.objects.filter(brand=data['brand']) for i in cars: for x in data['skills']: skill = Skill.objects.get(car=i , skill=x) provider.skills.add(skill) provider.save() else: return redirect("managers:dashboard_manager") return redirect(request.META.get('HTTP_REFERER')) the data["brand"] is a string of one brand of car and data["skills"] is a list of strings that each one of them are name of one skill that we have in out database. you send the data to form and then it's start to filter cars with that brand . after that , We start to loop over those cars and loop over the skills that sended . We add each one of them to skills field of the provider. But the problem … -
How can I handle multiple separate models in a single AJAX request using Django REST Framework?
In my Django project (version 5.1.2), I need to handle data from multiple models in a single AJAX request from the front end. For example, I have a form that collects user information and shipping addresses at the same time. I want to submit this data in a single request and have it saved in separate models in the database. I’m using Django REST Framework to manage the API, but I’m unsure how to properly validate and save multiple models at once in one request. Currently, I am using one ViewSet per model, but I don’t know how to combine them in a single AJAX request and ensure that if there’s an error in one of the models, none of the data is saved (i.e., I want proper transaction handling). Is there a recommended solution for this in Django 5.1.2? What is the best way to handle multiple models in a single AJAX request in Django REST Framework? Details: I'm using Django 5.1.2. Both user and address information need to be saved transactionally. What I Tried: I created two separate ViewSets for the user information and shipping address models. Then, I tried to send the form data via a single … -
Encoding problem when migrating postgresql database tables to models.py django
When performing table migration python manage.py inspectdb > example/models.py all Cyrillic strings are transposed as a set of unknown characters: 'id_шёїюф ∙хую' Encoding of the database server as well as python script is UTF-8. Is there any way to solve this problem? I tried show server_encoding; and got UTF8, tried set PYTHONIOENCODING=UTF-8 Also, I added 'OPTIONS': { 'client_encoding': 'UTF8', } into settings.py. All aforementioned methods didn't help and problem is still existing. I use psycopg package. -
swagger select a defintion for django
so, I've been working on my Django project Apis and i'm using drf-spectacular for the swagger view this is in my settings.py: SPECTACULAR_SETTINGS = { 'TITLE': 'Your Project API', 'DESCRIPTION': 'Resume Swagger API', 'VERSION': '1.0.0', 'SERVE_INCLUDE_SCHEMA': False, } and ofc this in my main urls.py: urlpatterns = [ # Swagger Url path('api/schema/', SpectacularAPIView.as_view(), name='schema'), # Optional UI: path('', SpectacularSwaggerView.as_view(), name='swagger-ui'), ] it has no drop down in order to select a definition, I mean i don't know if such thing exist for django: this is how my swagger looks like: enter image description here but i've seen this for as far as i know for an ASP.NET project that has such drop down to navigate between different api endpoints as below: enter image description here is this achievable in django? I've searched alot through docs and everything but i guess there is no such a guide to do this i hope someone comes up with a solution? -
bin/bash logs screw up after running django query create - ÄDEBUGÅ instead [DEBUG]
When running this django command: MyObjectBase.objects.create( ..., report_pdf=open(f"{REPORT_PATH}/{file_name}.pdf", "rb").read(), ... ) My log output in the bin/bash console of VS Code in WSL2 on Win11 gets screwed. Instead before the command: [2024-10-21 13:40:52 +0200] [923356] [DEBUG] this is a debug message I am getting logs like: Ä21/Oct/2024:11:47:18 +0000Å ÄDEBUGÅ Backticks turn into 'é'. It looks like that during the create-command the binaries of the file are printed to the log like (just thousands of chars longer than this sample) ÖxecoÖxc6Öxd2ÖxffÖxd6ÖxffKÖx00xyÖxchÖxfaÖxe66Öx7fÖx98Ö This does not happen for every report, using different base data does not cause this effect. Unfortunately it is impossible for me to detect differences. I can say that the base data only contains strings and doubles and so on but no nested blobs or strings like code, but special chars like # are possible. I tried another terminal. tmux was available by default. It does not face this problems, logs stay fine. But not using (one of) the most default terminals is not a valid solution for me. So I am looking after the cause and hope to get it solved somehow. As an alternative I could imagine to suppress the binaries from the log when running django create. …