Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker can't connect my mysql container with djngo container
I have two separate container. When I am trying to connect MySQL with my Django container I am getting this error: django_farhyn | super().__init__(*args, **kwargs2) django_farhyn | django.db.utils.OperationalError: (2005, "Unknown server host 'mysql' (-2)") This docker compose file for mysql , phpmyadmin and using for others services: version: '3' services: mysql: image: mysql:8 container_name: mysql environment: MYSQL_ROOT_PASSWORD: test MYSQL_USER: test MYSQL_PASSWORD: test MYSQL_DATABASE: testdb ports: - "3306:3306" restart: always phpmyadmin: image: phpmyadmin/phpmyadmin container_name: phpmyadmin environment: PMA_HOST: mysql MYSQL_ROOT_PASSWORD: test ports: - "8080:80" depends_on: - mysql restart: always This docker compose file for only django project version: '3' services: django_farhyn: build: . container_name: django_farhyn command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" # Django application port mapping here my db settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config('MYSQL_DATABASE', default=''), 'USER': config('MYSQL_USER', default=''), 'PASSWORD': config('MYSQL_PASSWORD', default=''), 'HOST': 'mysql', 'PORT': '3306', } } I don't know where I am doing mistake and struggling from few hours for connect mysql container with my django docker container. -
How to customize the message for inactive user in Djoser?
I am working on a Django project and I am using Djoser as my auth library. However, when a user is trying to create a jwt token it returns { "detail": "No active account found with the given credentials" } for when there is no user with the credentials and when there is a user but is inactive. After some research, I found the piece of code below which was used to override the TokenObtain in the simplejwt library which djoser was written on top of but I don't know how to actually go about it. I am fairly new to Djoser. from rest_framework import status, exceptions from django.utils.translation import gettext_lazy as _ from rest_framework_simplejwt.serializers import TokenObtainPairSerializer, TokenObtainSerializer class CustomTokenObtainPairSerializer(TokenObtainPairSerializer, TokenObtainSerializer): # Overiding validate function in the TokenObtainSerializer def validate(self, attrs): authenticate_kwargs = { self.username_field: attrs[self.username_field], 'password': attrs['password'], } try: authenticate_kwargs['request'] = self.context['request'] except KeyError: pass # print(f"\nthis is the user of authenticate_kwargs {authenticate_kwargs['email']}\n") ''' Checking if the user exists by getting the email(username field) from authentication_kwargs. If the user exists we check if the user account is active. If the user account is not active we raise the exception and pass the message. Thus stopping the user from getting … -
In VS code facing issue with RUN AND DEBUG for DJANGO
I am running RUN AND DEBUG with django. if i click the run and debug button, it starts and ends in 2 secs. Not showing any error, just stops. Not sure why. adding the launch.json for reference { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python Debugger: Django", "type": "debugpy", "request": "launch", "args": [ "runserver" ], "django": true, "autoStartBrowser": false, "program": "${workspaceFolder}\\manage.py" } ] } I tried changing the values of each key, no use. I am beginner for django. Please help me out -
Django REST Framework ValueError: Cannot query "John Smith": Must be "User" instance
I am working on a Django project with Django REST Framework, and I'm encountering a ValueError when trying to filter orders by customer ID. Here is the error traceback: Internal Server Error: /orders/ Traceback (most recent call last): File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/rest_framework/viewsets.py", line 124, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/rest_framework/mixins.py", line 38, in list queryset = self.filter_queryset(self.get_queryset()) ^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/econ/AdnexumActio/views.py", line 264, in get_queryset return Order.objects.filter(customer_id=customer_id) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/db/models/query.py", line 1476, in filter return self._filter_or_exclude(False, args, kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/db/models/query.py", line 1494, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/db/models/query.py", line 1501, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/db/models/sql/query.py", line 1613, in add_q clause, _ = self._add_q(q_object, self.used_aliases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/mango/Desktop/blessings/env/lib/python3.11/site-packages/django/db/models/sql/query.py", line 1645, in _add_q child_clause, needed_inner = self.build_filter( ^^^^^^^^^^^^^^^^^^ … -
Remove products from the shopping cart
When removing the product from the shopping cart, the removing button does not work my view: class CartDeleteView(View): def get(self, request, id): cart = Cart(request) cart.delete(id) return redirect('cart:cart_detail') def delete(self, id): if id in self.cart: del self.cart[id] self.save() -
How to fetch dropdown from database in the Django ? (Uncaught TypeError: Cannot read properties of null (reading 'classList'))
I am fetching a dropdown from the the database in the Django, Everything is loading while I am inspecting it, but the dropdown is not opeing up. {% if part_data.part.has_ML_Model %} <div class="btn-group"> <button type="button" class="btn btn-success dropdown-toggle" id="dropdownMenuButton{{ forloop.counter }}" data-bs-toggle="dropdown" aria-expanded="false"> {{ part_data.dropdown.0.dropdown_label }} </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton{{ forloop.counter }}"> {% for dropdown in part_data.dropdown %} <li><a class="dropdown-item" href="#">{{dropdown.dropdown_item_one}}</a></li> <li><a class="dropdown-item" href="#">{{dropdown.dropdown_item_two}}</a></li> <li><a class="dropdown-item" href="#">{{dropdown.dropdown_item_three}}</a></li> {% endfor %} </ul> </div> {% endif %} ** My model : ** class CaseStudy_ML_Model(models.Model): case_study_part = models.ForeignKey(CaseStudy_Parts, on_delete=models.CASCADE, null=True) dropdown_label = models.CharField(max_length=255 ,default="") dropdown_item_one = models.CharField(max_length=255, default="") dropdown_item_two = models.CharField(max_length=255, default="") dropdown_item_three = models.CharField(max_length=255, default="") **My views : ** def casestudy(request, CaseStudy_id ): casestudy_object = get_object_or_404(CaseStudy_List, CaseStudy_id = CaseStudy_id) #for list casestudy_parts_obj = CaseStudy_Parts.objects.filter(case_study=casestudy_object).order_by('CaseStudy_order').distinct() #for accordians parts_data = [] #storing in a singlist to avoid duplicacy for part in casestudy_parts_obj: part_content = CaseStudy_Content.objects.filter(case_study_part = part) part_media = CaseStudy_Media.objects.filter(case_study_part = part) part_button = CaseStudy_Buttons.objects.filter(case_study_part = part) part_dropdown = CaseStudy_ML_Model.objects.filter(case_study_part = part) # # Logic to determine if button required for media # has_button_for_media = False # # You can modify this logic based on your specific criteria # if part_media.exists() and part_button.exists(): # Check for media and buttons # has_button_for_media = True parts_data.append({ … -
google ads not working in django (i have installed google ads ) yet it is not confirming the location
I'm working on a Django project where I need to use the Google Ads API. I've installed the google-ads library using pip install google-ads, but I keep encountering an import error when trying to import GoogleAdsClient. Here are the details of my setup and the steps I've followed: pip install google-ads pip list | findstr google-ads google-ads 24.1.0 from google.ads.googleads.client import GoogleAdsClient thisall of this is not working what to do now -
Python on Hosting, access localhost on client-side
I need your help. I have django application that running on hosting provider, and I have function that do requests to localhost application that running on my own computer. How to do requests to localhost application on my own computer? Because when I do requests to localhost its getting error because requests doing requests on the server side and not on client side. I dont want to install anything on my clientside. I want to get the code to solve my problem -
Implementing PHP into Django project
I have a project done in PHP format and I have to include Python Django to implement my machine learning algorithms such as SVM, random forest, logistic regression, and naive Bayes. Is it possible to do so? Can I use my Django project to include my PHP files? Also, my PHP files are under xampp htdocs while my Django project is under the C: folder Can you help me with the codings so I can put them in my Django project to include my PHP files? -
AssertionError in django project
I am trying to test a API to create a company but it gives me a assertion error, it says that i need to create a custom .create() method but I have already defined that but still getting the error. serializer.py ```python class TaxInformationSerializer(serializers.ModelSerializer): class Meta: model = TaxInformation fields = '__all__' def create(self, validated_data): return TaxInformation.objects.create(**validated_data) class CompanySerializer(serializers.ModelSerializer): tax_information = TaxInformationSerializer() class Meta: model = Company fields = ["brand_name", "legal_name", "mobile", "telephone_no", "fax", "status", "tax_information"] read_only_fields = ['user', 'created_at'] def create(self, validated_data): # Automatically set the user to the request user request = self.context.get('request') if request and hasattr(request, 'user'): validated_data['user'] = request.user return super().create(validated_data) # Create the tax information instance tax_information_data = validated_data.pop('tax_information') # tax_information = TaxInformation.objects.create(**tax_information_data) tax_information_serializer = TaxInformationSerializer(data=tax_information_data) tax_information_serializer.is_valid(raise_exception=True) tax_information = tax_information_serializer.save() # Create the company instance with the tax information instance = Company.objects.create(tax_information=tax_information, **validated_data) return instance and the error is AssertionError at /datamanagement/company The `.create()` method does not support writable nested fields by default. Write an explicit `.create()` method for serializer `datamanagement.serializers.CompanySerializer`, or set `read_only=True` on nested serializer fields. I have already defined a custom create method but still getting the error. -
Why are my django-allauth socialaccount template tags empty?
I am using Django 5.0.6 with django-allauth 0.63.3. I followed the allauth quick start guide to configure my settings.py and used pip install "django-allauth[socialaccount]" , and was able to setup google and github SSO providers through settings.py file. settings.py SOCIALACCOUNT_PROVIDERS = { 'github': {...}, 'google': {...}, } I confirmed they both show up and links work in "/accounts/login" endpoint from allauth. However, when making a custom login form, the template tags are empty allauth template reference. login.html {% load socialaccount %} {% get_providers as socialaccount_providers %} <div>{{socialaccount_providers}}</div> I have also tried configuring the providers through the django admin console, but that did not solve the issue. It just made the login page have conflicting duplicate links. I have also reinstalled the package through pip. -
Switch to backend development
As a full-stack developer experienced with the MERN stack I'm looking to transition to focusing on backend development I'm considering learning Java with frameworks like Spring Boot or exploring Django or sticking with Express js My goal is to choose a technology that can effectively handle small and large projects like fintech applications Any advice on which path would be best suited for this transition? -
Django project structure: should my register, login templates go into an accounts app or in project templates
This is the project structure I have currently: project/ manage.py forum_app/ ecommerce_app/. # tbd accounts/ project/ settings.py urls.py templates/ base.html home.html registration/ login.html signup.html profile.html change_password.html ... Should I instead have something like this: project/ manage.py forum_app/ ecommerce_app/ # tbd accounts/ templates/ accounts/ login.html signup.html profile.html change_password.html project/ settings.py urls.py templates/ base.html home.html My confusion comes with the idea that since authentication is a specific set of tasks it should be a seperate app, so the relevant templates should go in the accounts app. However, the login, signup etc. templates are intended for the website as a whole, so maybe they should go in the root templates folder as in first example. I'd appreciate some guidance on what is the best way to do this? Also, if I were to create a Profile model for forum users (profile icon, bio) mapping to auth User, should that live in the accounts/models.py or forum_app/models.py? -
What is the best way to make sure the "django-timezone" session variable is set based on a user's profile preference each time they log in
Background I read this section in Django's documentation titled "Selecting the current time zone,", and it's clear to me how a user can select their preferred timezone for their session (and then the middleware makes sure it is used throughout their session): developer prepares a dictionary of timezones for users to select from developer makes this list available to user in a form within a template that is served by a GET request to a view called set_timezone user selects timezone using this form and makes a POST request set_timezone view uses a simple one-liner to set session "django-timezone" variable: request.session["django_timezone"] = request.POST["timezone"] Finally, the custom TimezoneMiddleware class referenced in the documentation will then activate the timezone for all view requests in the session from that point on Question If I store a user's timezone preference in a User model or User profile model, what is the best way to make sure the "django-timezone" session variable is always set for all their sessions (each time they log in)? Thoughts/guesses Would I need to modify a built-in Django authentication middleware class of some sort? Would it be best to extend the Django-standard LoginView class from django.contrib.auth.views? Or will the aforementioned LoginView … -
Bad Request and Invalid HTTP_HOST header in deployment NGINX + Gunicorn + Django?
Could you, please, help me with some suggestion where or how to find a resolution of my DisallowedHost exception? I have deployed my Django project to the DigitalOcean Ubuntu server with Nginx + Gunicorn according to instructions from DjangoProject and DigitalOcean as well as answers from related questions from DjangoForum, StackOverflow and others. I believe I tried all the advice I could find but still have 400 BadRequest responses, and Invalid HTTP_HOST header Error. likarnet is my project name, and likarnet.com is my domain. I have connected domain likarnet.com to my public IP and SSL certificate to my domain. Versions python 3.12, django 5.0.6 Please, excuse me if I ask some obvious things. This is my first project. File /etc/nginx/sites-available/likarnet server { listen 80 default_server; listen [::]:80 default_server; server_name likarnet www.likarnet; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/likarnet/website/likarnet; } location /media/ { root /home/likarnet/website/likarnet; } location / { proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Real-IP $remote_addr; proxy_redirect off; proxy_pass http://unix:/run/gunicorn.sock; } } I have just tried to use default include proxy_params; File /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=likarnet Group=sudo WorkingDirectory=/home/likarnet/website/likarnet … -
Django User-roles permission
I’m trying to create a school management webapp using Django. I’m using PostgreSQL for database. The webapp will be used by many schools that’s why am trying django_tenant. Kindly advise on how I should go about the account app that should handle login and signup from main homepage. Users are to be link to their respective schools so as other data for security purposes. I have several users like student, parent, teacher, treasurer, manager, and secretary for each school. I want to end up assigning roles for each user that is different from other users something that I need to be handled by using user_type while signing up. But also I want to have other fields in the signup form specific to the user like parent for student. Kindly advise. I try using AbstractUser but since I also want added fields per user am trying customuserform. The two don’t seem to work well together. -
Passing date value to HTML form in django framework
I am building my first application with Django. I am trying to make a template form to update values in a row in a table in a database. I want to populate all the forms fields with the existing values from the database. I can pass dates in as text just fine: This displays my date: <input type="text" class="form-control" value="{{ table.date }}"> but when I try the same value into a date field, it remains blank with I render This displays a blank date field: <input type="date" class="form-control" value="{{ table.date }}"> I assume this has to do with handling date formatting. Is there an easy way to handle this in the html? or does it require backend work? Any python code I tried to write into the template resulted in a 404. Still learning what the capabilities are. From what I have read I am guessing correct way to do this is with a function in my model, but I was hoping I could write something to convert the date in my template. My view is basic: def update(request, id): table = table.objects.get(pk=id) return render(request, 'app/tempate.html', {'table' : table}) -
DataTable table ordering fails when used in HTMX responsive table
I have played around with a few ways to create responsive tables and I like the htmx approach. The issue I run into is I loose some of the DataTables functions I have relied upon, mainly the ability for the user to sort by clicking on the header. Views.py: class HomePageView(TemplateView): template_name = 'wwdb/home_tabletest.html' class WinchOperatorForm(forms.ModelForm): class Meta: model = WinchOperator exclude = [] def get_winchoperator_list(request): context = {} context['winchoperator'] = WinchOperator.objects.all() return render(request, 'wwdb/winchoperator_list.html', context) def add_winchoperator(request): context = {'form': WinchOperatorForm()} return render(request, 'wwdb/add_winchoperator.html', context) def add_winchoperator_submit(request): context = {} form = WinchOperatorForm(request.POST) context['form'] = form if form.is_valid(): context['winchoperator'] = form.save() else: return render(request, 'wwdb/add_winchoperator.html', context) return render(request, 'wwdb/winchoperator_row.html', context) def add_winchoperator_cancel(request): return HttpResponse() def delete_winchoperator(request, winchoperator_pk): winchoperator = WinchOperator.objects.get(pk=winchoperator_pk) winchoperator.delete() return HttpResponse() def edit_winchoperator(request, winchoperator_pk): winchoperator = WinchOperator.objects.get(pk=winchoperator_pk) context = {} context['winchoperator'] = winchoperator context['form'] = WinchOperatorForm(initial={ 'firstname':winchoperator.firstname, 'lastname': winchoperator.lastname, 'status': winchoperator.status, 'username': winchoperator.username, }) return render(request, 'wwdb/edit_winchoperator.html', context) def edit_winchoperator_submit(request, winchoperator_pk): context = {} winchoperator = WinchOperator.objects.get(pk=winchoperator_pk) context['winchoperator'] = winchoperator if request.method == 'POST': form = WinchOperatorForm(request.POST, instance=winchoperator) if form.is_valid(): form.save() else: return render(request, 'wwdb/edit_winchoperator.html', context) return render(request, 'wwdb/winchoperator_row.html', context) I can post more templates if requested, but the template defining the tables are: <div> <table class="table … -
ModelForm with field depending on user permission?
I have a model Address with a field and a ModelForm. class Address(Model): number = PositiveSmallIntegerField(default=1) class AddressForm(ModelForm): class Meta: model = Address fields = "__all__" How do I add a validator to it, when the form is shown to a user with a specific permission? The form should behave as if the model itself would have a number field like this: number = PositiveSmallIntegerField(default=1, validators=[MaxValueValidator(100)]) By that I mean that the form should only allow values from 0 to 100, and the backend should validate that the value is inbetween 0 and 100. The view could pass whether or not to use the limited field like so: form = AddressForm(enable_limit=True) And I could do something like this: class AddressForm(ModelForm): class Meta: model = Address fields = "__all__" def __init__(self, *args, enable_limit=False, **kwargs): if enable_limit: self.base_fields["number"].widget.attrs["max"] = 100 However, this only updates the widget. The form does complain about values > 100, but that's only the HTML forms client-side validation and by changing the value in the request, I can go around that, which is not what I want. Basically, I want to tell the ModelForm to use the Adresse.number field as the foundation, but with an additional MaxValueValidator(100). How … -
Error when reading excel table for autocomplete database
I'm trying to fill the database in Django project automatically (through migration) by reading excel table. Migration file code: # Generated by Django 5.0.6 on 2024-06-21 15:04 import random import openpyxl from django.db import migrations from users import models DEFAULT_TABLE = 'default_articles_data.xlsx' users = [] def fill_articles(apps, schema_editor): wb = openpyxl.load_workbook(DEFAULT_TABLE, data_only=True) active_sheet = wb['Лист1'] blog_users = apps.get_model('users', 'UserProfile') Article = apps.get_model('articles', 'Article') for user in blog_users.objects.all(): users.append(user) for row in range(1, active_sheet.max_row + 1): article_image_source = active_sheet.cell(row=row, column=1).value print(article_image_source) article_title = active_sheet.cell(row=row, column=2).value print(article_title) article_author = random.choice(users) print(article_author) article_short_description = active_sheet.cell(row=row, column=3).value print(article_short_description) article_content = active_sheet.cell(row=row, column=4).value print(article_content) article = Article(title=article_title, author=article_author, short_description=article_short_description, content=article_content, image=article_image_source) article.save() class Migration(migrations.Migration): dependencies = [ ('articles', '0006_comment_article'), ] operations = [migrations.RunPython(fill_articles)] This is what the Article model itself looks like: class Article(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(unique=True, blank=True, null=True) short_description = models.TextField(max_length=100) content = models.TextField() pub_date = models.DateField(auto_now_add=True) image = models.ImageField() author = models.ForeignKey(users_models.UserProfile, on_delete=models.CASCADE) tags = models.ManyToManyField(Tag, blank=True) def __str__(self): return self.title Here is a sample row from the target table (used only A-D columns): On output I get an error: django.db.utils.IntegrityError: NOT NULL constraint failed: articles_article.title The above exception was the direct cause of the following exception: Traceback (most recent … -
Why does csv.reader with TextIOWrapper include new line characters?
I have two functions, one downloads individual csv files and the other downloads a zip with multiple csv files. The download_and_process_csv function works correctly and seems to replace new line characters with a space. 'Chicken, water, cornmeal, salt, dextrose, sugar, sodium phosphate, sodium erythorbate, sodium nitrite. Produced in a facility where allergens are present such as eggs, milk, soy, wheat, mustard, gluten, oats, dairy.' The download_and_process_zip function seems to include new line characters for some reason (\n\n). I've tried newline='' in io.TextIOWrapper however it just replaces it with \r\n. 'Chicken, water, cornmeal, salt, dextrose, sugar, sodium phosphate, sodium erythorbate, sodium nitrite. \n\nProduced in a facility where allergens are present such as eggs, milk, soy, wheat, mustard, gluten, oats, dairy.' Is there a way to modify download_and_process_zip so that new line characters are excluded/replaced or do I have to iterate over all the rows and manually replace the characters? @request_exceptions def download_and_process_csv(client, url, model_class): with closing(client.get(url, stream=True)) as response: response.raise_for_status() response.encoding = 'utf-8' reader = csv.reader(response.iter_lines(decode_unicode=True)) process_copy_from_csv(model_class, reader) @request_exceptions def download_and_process_zip(client, url): with closing(client.get(url, stream=True)) as response: response.raise_for_status() with io.BytesIO(response.content) as buffer: with zipfile.ZipFile(buffer, 'r') as z: for filename in z.namelist(): base_filename, file_extension = os.path.splitext(filename) model_class = apps.get_model(base_filename) if file_extension == … -
django runserver suddenly gives error "double free detected in tcache 2"
I have a django app which suddenly started giving me this error. I have not made changes to the code in the app, and the app runs fine on other servers. So it must be some configuration on my computer. But I have absolutely no idea how to troubleshoot it, and I cannot find any relevant answers when googling the error. Help? $ python manage.py runserver 127.0.0.1:8000 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). free(): double free detected in tcache 2 I'm running Ubuntu 20.04. Django 4.1.4. -
Append an entry per view to the DEFAULT_FILTER_BACKENDS
In a Django (and DRF) project with a large number of views we have set a list of filter backends in settings.py: REST_FRAMEWORK = { "DEFAULT_FILTER_BACKENDS": [ # filter backend classes ], # other settings } Some of the view classes need additional filter backends. We can specify the attribute filter_backends per view class: FooViewSet(viewsets.ModelViewSet): filter_backends = [DefaultFilterOne, DefaultFilterTwo, DefaultFilterThree, AdditionalFilter] However, this is not DRY. Here in this example three (3) filter backends are default and have to be repeated in the viewset class. If there's a change in settings.py it has to be reflected in the view class. What is best practice to append an additional filter backend per class, while keeping the default filter backends from settings.py? -
How do I fix error "TypeError at / ‘dict’ object is not callable" located in exception.py?
Adding django CMS to an existing Django project, I'm getting the error: "TypeError at / ‘dict’ object is not callable". This is the output: TypeError at / 'dict' object is not callable Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.2.13 Exception Type: TypeError Exception Value: 'dict' object is not callable Exception Location: C:\Users\USER\.virtualenvs\AnalyticsScout_V_1_1-2IRLUV3q\lib\site-packages\django\core\handlers\exception.py, line 55, in inner Python Executable: C:\Users\USER\.virtualenvs\AnalyticsScout_V_1_1-2IRLUV3q\Scripts\python.exe Python Version: 3.9.16 Python Path: ['C:\\Users\\USER\\OneDrive\\Bureau\\AnalyticsScout_V_1_1', 'C:\\Users\\USER\\miniconda3\\python39.zip', 'C:\\Users\\USER\\miniconda3\\DLLs', 'C:\\Users\\USER\\miniconda3\\lib', 'C:\\Users\\USER\\miniconda3', 'C:\\Users\\USER\\.virtualenvs\\AnalyticsScout_V_1_1-2IRLUV3q', 'C:\\Users\\USER\\.virtualenvs\\AnalyticsScout_V_1_1-2IRLUV3q\\lib\\site-packages'] Server time: Fri, 21 Jun 2024 09:26:19 +0000 In my local project I have the ‘exception.py’ file as the one in: Exception.py Whenever I run Django, I’m getting the following output in the terminal : Microsoft Windows [Version 10.0.22000.2538] (c) Microsoft Corporation. All rights reserved. (AnalyticsScout_V_1_1-2IRLUV3q) (base) C:\Users\USER\OneDrive\Bureau\AnalyticsScout_V_1_1>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). June 21, 2024 - 05:26:05 Django version 4.2.13, using settings 'analyticsscout.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: / Traceback (most recent call last): File "C:\Users\USER\.virtualenvs\AnalyticsScout_V_1_1-2IRLUV3q\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) TypeError: 'dict' object is not callable [21/Jun/2024 05:26:20] "GET / HTTP/1.1" 500 74922 [21/Jun/2024 05:26:20] "GET /static/debug_toolbar/css/toolbar.css HTTP/1.1" 304 0 [21/Jun/2024 05:26:20] … -
Django Annotation F() value
I have a question regarding Django Annotations: tickers = { "BCO": 10.0, "AIR": 50.0, } assets = Asset.objects.annotate( price=(tickers[F("fk_security__ticker_symbol")])) I would like to annotate the value from the dictionary to the asset but always getting a key error: F(fk_security__ticker_symbol) What am I doing wrong here? Is it even possible to do this? Thanks a lot in advance! If it helps, here is my model: class Asset(models.Model): fk_security = models.ForeignKey(Security, on_delete=models.CASCADE, blank=False, verbose_name="Security",related_name="security", ) class Security(models.Model): ticker_symbol = models.CharField( max_length=5, verbose_name="Ticker Symbol", default="", )