Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to install django-filetransfers for python 2.7.18
I am not able to install django-filetransfers for python 2.7.18, I have the same installed in other machine but since I am migrating the project to the new machine I am trying to install it. Please help. pip install django-filetransfers DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality. ERROR: Could not find a version that satisfies the requirement django-filetransfers (from versions: none) ERROR: No matching distribution found for django-filetransfers -
Django delete folder when session ends
I am creating a directory using the session key and uploading files to it. I want to delete this directory once the user ends the session by closing the tab. def upload_pdf(self, request, form): files = form.cleaned_data["file_field"] # Get or Create Directory Path(f'{PDF_PATH}{request.session.session_key}').mkdir(parents=True, exist_ok=True) for f in files: try: pdf_handler = PdfWriter() pdf_handler.append(f) file_path = f'{PDF_PATH}{request.session.session_key}/{f}' pdf_handler.write(file_path) messages.add_message(request, messages.SUCCESS, f'<b>{f}</b> Uploaded <a href="my-file-view/{file_path}/" target="_blank">View</a>') except: messages.add_message(request, messages.WARNING, f"<b>{f}</b> not Uploaded - not a PDF file") return super().form_valid(form) How can I run a command at session close? -
ReactJS and NPM problem due to week Internet connection
I'm from Iran and due to week Internet connection the "NPM" command doesn't work for me. I want to work with Django rest_framework and I need ReactJS. I couldn't use "npm install -g create-react-app" and I go to github and found its repository. I cloned that repo but I'm not sure that's enough or NOT and yet, I don't know how to use this repo in my project :( ..... If anyone already use "React repo", please help me out. Thanks. -
Is it okay to have multiple ingress connecting to a service in K8s?
We have a multi-tenant Django application that has a deployment with 5 replicas. In front of that deployment, we have a service. and we connected almost 2k ingress to that service. so we tried with a single service after a while we witnessed that load balancing between pods its not working properly and one of our pods hit the cpu limit frequently yet others has a medium to low workload. U can see cpu usage of our pods in below: also u can see the metric container_network_receive_bytes_total in this pic: we dont have any sticky session or session affinity or websockets or anything in our application in order to prefer one pod to another. I was wondering if we should have a service for each one of them or if a single service is okay. I should mention that we us traefik as our load balancer. -
django project on Ubuntu running nginx unable to upload files
I keep getting this error while trying to upload a file via the django admin 2023/08/24 10:51:09 [warn] 4147#4147: *1 a client request body is buffered to a temporary file /var/cache/nginx/client_temp/0000000001, client: 172.71.98.67, server: 72.167.132.218, request: "POST /ran-admin/blog/post/add/ HTTP/1.1", host: "redaid-nigeria.org", referrer: "https://redaid-nigeria.org/ran-admin/blog/post/add/" 2023/08/24 10:52:02 [error] 4147#4147: *10 open() "/usr/share/nginx/html/server-status" failed (2: No such file or directory), client: 127.0.0.1, server: localhost, request: "GET /server-status?auto HTTP/1.1", host: "localhost" 2023/08/24 10:52:02 [error] 4147#4147: *11 open() "/usr/share/nginx/html/nginx_status" failed (2: No such file or directory), client: 127.0.0.1, server: localhost, request: "GET /nginx_status HTTP/1.1", host: "localhost" 2023/08/24 10:53:28 [warn] 4147#4147: *18 a client request body is buffered to a temporary file /var/cache/nginx/client_temp/0000000002, client: 172.71.98.159, server: 72.167.132.218, request: "POST /ran-admin/blog/post/add/ HTTP/1.1", host: "redaid-nigeria.org", referrer: "https://redaid-nigeria.org/ran-admin/blog/post/add/" 2023/08/24 10:58:06 [warn] 4147#4147: *25 a client request body is buffered to a temporary file /var/cache/nginx/client_temp/0000000003, client: 172.70.46.67, server: 72.167.132.218, request: "POST /ran-admin/blog/post/add/ HTTP/1.1", host: "redaid-nigeria.org", referrer: "https://redaid-nigeria.org/ran-admin/blog/post/add/" Initially I could upload smaller files and only got this error for large files (> 1MB). Now, the error shows for even files as small as 2KB. Please advice My /etc/nginx/sites-available/domainwww .conf file is server { listen 80; server_name 72.167.132.218 redaid-nigeria.org www.redaid-nigeria.org; location = /favicon.ico { access_log off; log_not_found off; } location /static/ … -
Django Dynamic Admin Form
In my Django project I have the models Product and ClothingProduct. Product has an attribute called category. ClothingProduct inherits from Product. When a Product is created where the category value == 'Clothes' an instance of ClothingProduct should also be created and then the user should be able to enter the attribute values for ClothingProduct ( trough the admin panel). I tried the following save() method, but it doesn't work. class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.category.name == 'Clothes': clothingProd, created = ClothingProduct.objects.get_or_create(product=self) if created: clothingProd.color = 'White' clothingProd.save() def __str__(self): return self.name class ClothingProduct(Product): product = models.OneToOneField(Product, on_delete=models.CASCADE, related_name='clothing_product') color = models.CharField(max_length=10, help_text='eg. White') #This is the admin.py content: @admin.register(Product) class ProductAdmin(admin.ModelAdmin): inlines = [ProductImageAdmin] fields = ('name', 'category') def get_form(self, request, obj=None, **kwargs): if obj and obj.category.name == 'Clothes': form = ClothingProductForm else: form = super().get_form(request, obj, **kwargs) return form class ClothingProductForm(forms.ModelForm): class Meta: model = ClothingProduct exclude = ['product'] admin.site.register(ClothingProduct) -
Django error: {'id_service': [ErrorDetail(string='Invalid pk "2" - object does not exist.', code='does_not_exist')]}
I cant reach what is the problem, can someone helo me: @api_view(['POST']) @require_certificate @transaction.atomic def schedule_scan_info_POST(request): with transaction.atomic(): if request.method == 'POST': logger.info('--------------RECIBING INFO SCHEDULE SCAN--------------') logger.info('CERTIFICADO: %s', request.META.get('SSL_CLIENT_CERT', None)) #GET IP AND URL WHO IS CALLING TO THE API ip=request.META.get('HTTP_X_REAL_IP') or request.META.get('HTTP_X_FORWARDED_FOR') or request.META.get('HTTP_CLIENT_IP') or request.META.get('REMOTE_ADDR', '') try: url = request.get_full_path() except Exception as e: logger.error('Error getting the URL: {}'.format(str(e))) return Response({"error": 'Error in the server'}, status=request_status.HTTP_500_INTERNAL_SERVER_ERROR) #DATETIME NOW fecha=datetime.datetime.now().isoformat() #DATA RECIBED TO SAVE data_request=request.data logger.error(request.data) #EEXTRACTING ALL DATA RECIBED serial_number_cert= data_request.get('certificate_serial_number', None) date_param = data_request.get('date_schedule_scan', None) dict_GATT = data_request.get('dict_GATT', None) programmed_scan = data_request.get('programmed_scan', None) dict_vulns = data_request.get('dict_vulns', None) ble_device_mac = data_request.get('ble_device_mac', None) vulnerabilities_encountered = data_request.get('vulnerabilities_encountered', None) #IF THE URL GET EXITS AND DATE if url!=None: #OBTAIN SCANNER OF SHCEDULE SCAN, WITH THE CERTIFICATE try: logger.info('Obtaining Scanner calling') scanner = Scanner.objects.get(certificate_serial_number=serial_number_cert) except Scanner.DoesNotExist: serializer_api = APICallsSerializer(data={'ip': ip, 'url': url, 'method': 'GET', 'date': fecha, 'status_code': request_status.HTTP_400_BAD_REQUEST, 'error': 5}) try: logger.info('Serializer API CALL') serializer_api.is_valid(raise_exception=True) serializer_api.save() except ValidationError as e: logger.warning('Serializer for API CALL Validation error, error: %s', e) return Response({"error": 'Error in the API CALL data'}, status=request_status.HTTP_400_BAD_REQUEST) except Exception as e: logger.warning('Impossible SAVE of API CALL') return Response({"error": 'Error in the server'}, status=request_status.HTTP_500_INTERNAL_SERVER_ERROR) return Response({"error": "Scanner doesn't exists"}, status=request_status.HTTP_400_BAD_REQUEST) #SAVING THE … -
Deploy Django app (using Celery) to Heroku
I am a beginner in web app development. <(__)> I am developing an app with Celery in Django, and I want to deploy it to Heroku, but it doesn't work. It was working fine in my local environment, but... (sad...) I would appreciate it if you could tell me in detail how to configure the minimum required files ("settings.py", "Procfile", etc.) so that I can deploy without errors! ("REDIS_URL" is obtained by Heroku add-on...) I tried the following after researching on the Internet and watching videos, but after deploying the application, the "task result" in the database did not return any results. ・【settings.py】 Change "CELERY_BROKER_URL" to the URI obtained from the Heroku add-on ・【Procfile】 Add the following 「worker celery worker -A project.celery -l INFO」 ・【celery.py】 As follows import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() ・【tasks.py】 Same as local, with "@shared_task" prefixed to the function -
CRSF cookie not set in iframed Django View for an app in SFMC
I have a Django app that I created for SFMC, hosted on Heroku. I get "Forbidden (csrf cookie not set.)" error when I use it in SFMC but it is ok when I use it standalone. Here my settings.py: X_FRAME_OPTIONS = 'ALLOW-FROM .exacttarget.com' CSRF_TRUSTED_ORIGINS = [ 'https://*.exacttarget.com', 'https://*.herokuapp.com' ] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') CSRF_COOKIE_SECURE = True CSRF_COOKIE_DOMAIN = '.herokuapp.com' CSRF_COOKIE_SAMESITE = 'None' SECURE_SSL_REDIRECT = True CORS_ORIGIN_ALLOW_ALL = True I use {%csrf_token%} in the form correctly and it has the value. Can you help me? [https://stackoverflow.com/questions/53076379/crsf-cookie-not-set-in-iframed-django-view-within-another-site](I have tried the methods here but it did not work.) I have tried many different settings variations but none of them worked. -
django-pivot, ValueError: Column aliases cannot contain whitespace characters, quotation marks, semicolons, or SQL comments
I used django-pivot packages and I have got above error. first it work correcly in jupyter: but when I try to use companyid__company field instead of companyid field I've got this error (Column aliases cannot contain whitespace characters, quotation marks, semicolons, or SQL comments.) Models: class TblCompany(models.Model): companyid = models.AutoField(db_column='CompanyID', primary_key=True) company = models.CharField(db_column='Company', max_length=200) ... class Meta: db_table = 'tbl_Company' class TblCorporation(models.Model): contractcorporationid = models.AutoField(db_column='ContractCorporationID', primary_key=True) contractid = models.ForeignKey(TblContract, related_name="contract_corporation", on_delete=models.CASCADE, db_column='ContractID') companyid = models.ForeignKey(TblCompany, related_name="Company_Corporation", on_delete=models.CASCADE, db_column='CompanyID') e_percent = models.FloatField(db_column='E_Percent') p_percent = models.FloatField(db_column='P_Percent') c_percent = models.FloatField(db_column='C_Percent') class Meta: db_table = 'tbl_Corporation' meanwhile using companyid__company in filtering like following one have no problem: tblCorporation.objects.all().values('companyid__company') -
What is the better way to make consecutive FK relations cosistent in database?
In my django project, I have several models with consecutive relations between them. Let's say class Artist(models.Model): name = models.CharField(max_length=10) class Album(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE) class Song(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE) album = models.ForeignKey(Album, on_delete=models.RESTRICT) At the same time, it is important for me to make the relations consistent, i.e. the album of model Song should have its FR related to the artist field. Should I use come kind of constraint for a database, or it should be done with serialization logic? I tried to find any related examples in django documentation -
Getting AD's _id_token_claims in django middleware
from django.conf import settings from ms_identity_web import IdentityWebPython identity_web = IdentityWebPython(request) print(identity_web) claims = identity_web._id_token_claims How do I get the details from identity_web like when I get them using claims = request.identity_context_data._id_token_claims in my view functions ? claims = identity_web._id_token_claims is throwing 'WSGIRequest' object has no attribute 'identity_context_data' -
How to retrieve object storage image url from django backend to display with Javascript
I am having an issue with displaying images from the database when generating content dynamically using javascript and Fetch API. The images display correctly when accessing them with template tags. I am trying to dynamically load different products based on the selected category. I have a products model, where i have defined an image which is hosted in linode object storage bucket. When accessing the image directly through a template with {{product.image.url}} the image displays correctly, and in the page source i can see an url link to the file in the linode bucket as expected. However, when loading the product data dynamically, the image does not load and in the page source i can see that it is incorrectly rendering a file path. (example app/product/image instead of https://....) I use this code to render the image. fetch(`opensubcategory/${id}`) .then(response => response.json()) .then(data => { var subproducts = JSON.parse(data.products); for (var i = 0;i<subproducts.length;i++){ var subproduct = subproducts[i].fields; let image = document.createElement('img'); console.log(subproduct.image) imageurl = subproduct.image.url image.src = imageurl; image.classList.add("productimage"); imagediv.append(image); console.log(subproduct.image) shows a file path console.log(subproduct.image.url) shows undefined Here is my server side code for this view: def opensubcategory(request,id): subcategory = Subcategory.objects.get(pk=id) subcategory_products = Product.objects.filter(subcategory=subcategory) products_serialized = serialize("json",subcategory_products) return JsonResponse({"products":products_serialized}) … -
I am attempting to deploy a Django app via AWS Elastic Beanstalk. I have run into errors of every kind. Now I'm getting a connection error
I am following the W3 Django tutorial at this site: https://www.w3schools.com/django/django_deploy_provider.php. I'm hoping to get a sample deployment working here. Then, I'll be able to deploy my actual application. As you can see, the environment is setup and the health is ok. Here is the page when you go to it. As you can see, it displays correctly. So at least something is working correctly. When I click on the members link, I get this page after waiting for a while: I've looked in the logs and found the following in the errors section: /var/log/nginx/error.log 023/08/24 07:44:55 [error] 3217#3217: *6 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 64.71.154.2, server: , request: "GET /members/ HTTP/1.1", upstream: "http://127.0.0.1:8000/members/", host: "my-tennis-club-env-new.eba-gysp36xc.us-west-1.elasticbeanstalk.com", referrer: "http://my-tennis-club-env-new.eba-gysp36xc.us-west-1.elasticbeanstalk.com/" I figured that the problem must be the fact that it's making an HTTP GET request to the localhost. I don't know why this would be. In the Django settings file I have ALLOWED_HOSTS = ['my-tennis-club-env-new.eba-gysp36xc.us-west-1.elasticbeanstalk.com']. This should solve that problem but it doesn't. I still get the time outs. Please help me with this issue. This is my first Django project and deployment is much more difficult than I expected. -
Django AttributeError: 'QuerySet' object has no attribute 'items'
I want to reach this format in my output: { "E": [ { "value": 50, "label": "company1" }, { "value": 0, "label": "company2" }, ... ], "P": [ { "value": 50, "label": "company1" }, { "value": 0, "label": "company2" }, ... ], "C": [ { "value": 50, "label": "company1" }, { "value": 0, "label": "company2" }, ... ], } } so I decide to use serializers.DictField (dictionary field) but I have got this error when I run my api ('QuerySet' object has no attribute 'items') after search in net I could not find suitable description for solving this problem. I guess query filter in my model methods cause the issue and queryset does not have items for iterating. on the other hand first I write these model methods in jupyter separately and they worked correctly. Details of my code: Model: `class TblCorporation(models.Model): contractcorporationid = models.AutoField(db_column='ContractCorporationID', primary_key=True) contractid = models.ForeignKey(TblContract, related_name="Contract_Corporation", on_delete=models.CASCADE, db_column='ContractID') companyid = models.ForeignKey(TblCompany, related_name="Company_Corporation", on_delete=models.CASCADE, db_column='CompanyID') e_percent = models.FloatField(db_column='E_Percent') p_percent = models.FloatField(db_column='P_Percent') c_percent = models.FloatField(db_column='C_Percent') def __str__(self) -> str: return '%s: e=%s, p=%s, c=%s' % (self.companyid.company, self.e_percent, self.p_percent, self.c_percent) def E(self): e = TblCorporation.objects.filter(contractid__exact=self.contractid).values( 'companyid__company', 'e_percent').annotate( value = F('e_percent'), label = F('companyid__company')).values( 'value', 'label') return (e) def P(self): … -
What is alternative of deleted Money#decimal_places_display?
I stuck a bit with hiding decimals of Money object. Ex: In [51]: str(Money(123, 'USD')) Out[51]: 'US$123.00' returns with 00 in the end. Before it was resolved by money_obj.decimal_places_display = 0 but it is deleted in the last version on djmoney https://django-money.readthedocs.io/en/latest/changes.html#id3 I have tried to use babel format_currency, but no success. The decimals are there so far: In [54]: from babel.numbers import format_currency ...: format_currency(12345, 'USD', format='¤#') Out[54]: '$12345.00' For now my solution is quite manual, and the question is it possible to make it better? In [55]: from babel.numbers import format_decimal ...: from djmoney.money import Money ...: ...: from utils.constants import CURRENCIES_CHOICES ...: ...: ...: def format_int(money: Money) -> str: ...: amount = format_decimal(round(money.amount), locale='en_GB') ...: currency = format_currency(0, str(money.currency), format='¤') ...: return f'{currency} {amount}' ...: ...: format_int(Money(12345, 'USD')) ...: Out[55]: '$ 12,345' -
gettting django version does't support error while migration [closed]
This version of djongo does not support "schema validation using NOT NULL" fully. Visit https://nesdis.github.io/djongo/support/ This version of djongo does not support "COLUMN DROP DEFAULT " fully. Visit https://nesdis.github.io/djongo/support/ This version of djongo does not support "schema validation using NULL" fully. Visit https://nesdis.github.io/djongo/support/ tried migrating using fake but do't understand it cleatrly -
In Django, problem populating a dropdown, which is empty. I tried printing the values in the console and they are valid
I have three dropdowns and they are all dependent between them. The first two dropdowns work fine, while the third dropdown doesn't work: it's empty with nothing inside. The first dropdown is called trip_selector and it correctly returns for example Spain, England, France. If I select Spain, then the second dropdown called trip it returns correctly Madrid-Bilbao, Seville-Barcelona. PROBLEM: The problem is the third dropdown called seleziona_soggetto in views.py, or in seleziona_soggetto.html. In console i tried to print the items I would like to populate the dropdown (x, y and options), and they print Madrid and Barcelona values correctly, but I can't populate them in the dropdown. WHAT I WANT: I wish that when I select in the second dropdown (called trips) for example Madrid-Barcelona then the third dropdown should be populated in seleziona_soggetto.htmlwith Madrid and Barcelona, one for each item: Madrid Barcelona So I would like to populate seleziona_soggetto.html dropdown with option (i.e. x and y) of the function def seleziona_soggetto. I would like to use split() and loop (for) for educational purposes IMPORTANT: I know I may not use the loop (for) in html page, but for educational purposes I would like to use the loop (for) I … -
Django: "BEGIN" not executed in transaction.atomic(), record not locked
@api_view(['GET', 'POST', 'PUT']) def Test(request): with transaction.atomic(using="<table_name>"): target_user = AdminUser.objects.select_for_update().get(id="test_user") target_user.name = "name" target_user.save() return Response({}, status=status.HTTP_200_OK) Executing this API should execute the following sql command, but it does not BEGIN SELECT **** FOR UPDATE COMMIT is actually executed as SELECT **** FOR UPDATE COMMIT Django 3.2.12 Python 3.6.15 Mysql 5.7.41 from django.db import connection cursor = connection.cursor() cursor.execute("BEGIN") Inserting these codes didn't lock the record. -
How to go to specific page number of the paginator from the view in DRF
i have a path like this: path('comments/', CommentList.as_view(), name='comment-view'), i want that when i fetch that URL with the parameter: ?comment-id=37 for example, then Django should give the page that contains that comment. i use generic view and I'm able to calculate the page number that contains that comment like this: class CommentList(generics.ListCreateAPIView): permission_classes = [permissions.AllowAny] queryset = Comment.objects.all() serializer_class = CommentSerializer def get_queryset(self): if 'comment_id' in self.request.GET: comment_id = self.request.GET.get('comment_id') thread_id = self.request.GET.get('thread') num_preceeding_results = Comment.objects.filter(thread=thread_id,id__lt=comment_id).count() page = num_preceeding_results // page_size + 1 offset = (page - 1) * 10 now all i need is to return the desired page. i tried reverse and reverse lazy but they didn't work. so any suggestion please? i tried: return reverse('comment-view') + f'?thread={thread_id}&offset={offset}' -
msgstr is not a valid Python brace format string due to '�'
I have a Django i18n entry like: #: mycode.py:2323 #, python-brace-format msgid "Linked alias <a href=\"{alias_url}\" target=\"blank\">{alias}</a> to record <a href=\"{record_url}\" target=\"blank\">{record}</a>." msgstr "<a href=\"{alias_url}\" target=\"blank\">エイリアス{エイリアス}</a>を会社<a href=\"{record_url}\" target=\"blank\">{会社}に</a>リンクしました。" Yet when I run django-admin compilemessages I get the error: Execution of msgfmt failed: /path/to/django.po:222: 'msgstr' is not a valid Python brace format string, unlike 'msgid'. Reason: In the directive number 1, '�' cannot start a field name. Why is it complaining about the non-existent character '�' in my msgstr? -
How do I pull the current user onto the page for this practice project? I am struggling with the backend Django Rest Framework
I cant seem to pull any data whatsoever onto my page from the backend. Any guidance or resources would be helpful. Right now, im just trying to display whoever is logged in. I can add users to the backend through a table called customuser, but I dont know how to retrieve any data such as the current logged in user from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework import serializers from .models import * from django.shortcuts import render from django.http import HttpResponse, JsonResponse import requests import json class CustomUserSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True ) username = serializers.CharField() password = serializers.CharField(min_length=8, write_only=True) class Meta: model = CustomUser fields = ('email', 'password', 'first_name', 'last_name', 'username') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' import React, { useState, useEffect } from 'react'; import { useGlobalState } from '../context/GlobalState'; import authService from '../services/auth.service'; import jwtDecode from 'jwt-decode'; import Link from 'next/link'; import axios from 'axios'; import Layout from './layout'; import { useRouter } from 'next/router'; const ProfilePage = () => { const router = useRouter(); const [postData, setPostData] = useState({ … -
Django Group migrations don't persist on db even when using --reuse-db
My Django app creates some Groups via migrations. I'm having issues with pytest not finding the Groups when using the --reuse-db flag. My understanding was: migrations get applied before pytest runs, and although the tests get executed in a transaction to roll back any database changes, the db gets cached and those migrations persist (if using the --reuse-db flag). But that's not happening here. To repro my problem: if I run a test with the --create-db flag, it has no problem with any Group it needs to access if I switch to --reuse-db flag, and run the test twice, the second time fails with a Group.DoesNotExist error: ====================================================================================== short test summary info ====================================================================================== FAILED /test/something.py::test_defaults - django.contrib.auth.models.Group.DoesNotExist: Group matching query does not exist. FAILED /test/something.py::test_create - django.contrib.auth.models.Group.DoesNotExist: Group matching query does not exist. FAILED /test/something.py::test_get - django.contrib.auth.models.Group.DoesNotExist: Group matching query does not exist. ============================================================================= 3 failed, 1 passed, 116 warnings in 2.57s =================================================================== -
Add element to user attribute with foreign key
Each user has a groups-attribute as a list of groups. These are foreign keys of a groups table. Now I want to programmatically add some groups to a users groups attribute. I tried: user.groups = [] getting me Direct assignment to the forward side of a many-to-many set is prohibited. Use emails_for_help.set() instead How do I do this instead? And how do I set the groups which is a default feature of django? How do I know the id's. Thanks! -
In Django i can't populate a dropdown, it appears empty. Values are valid if i try to print them in the console
In Django I can't populate a dropdown. I have three dropdowns and they are all dependent. The first two dropdowns work fine, while the third dropdown doesn't work: it's empty with nothing inside. The first dropdown is called trip_selector and it correctly returns for example Spain. If I select Spain, then the second dropdown called trip it returns correctly Madrid-Bilbao, Seville-Barcelona. PROBLEM: The problem is the third dropdown called trip_selector in views.py. I wish that when I select in the second dropdown (called trips) for example Madrid-Barcelona then the third dropdown should be populated with Madrid and Barcelona. I tried to print x and y and print the Madrid and Barcelona values correctly, but I can't populate them in the dropdown. What am I doing wrong? Am I doing something wrong in views.py, something in the html page or something in HTMX? P.S: I know I could use options = [trip.team_home, trip.team_away] directly, but I need to create two separate variables like x and y seleziona_soggetto.html <select name="seleziona_soggetto" id="id_seleziona_soggetto" style="width:200px;" hx-get="{% url 'seleziona_soggetto' %}" hx-indicator=".htmx-indicator" hx-trigger="change" hx-swap="none"> <option value="">Please select</option> {% for i in options %} <option value="{{ i }}">{{ i }}</option> {% endfor %} </select> views.py #FIRST DROPDOWN (WORKS …