Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: allauth needs to be added to INSTALLED_APPS
I've been following this tutorial on the django for apis book by William Vincent. I need to use django-allauth. I've installed it in my venv, added it to installed apps and done all the necessary things according to the installation instructions on the Documentation. On running python manage.py migrate , the error comes back as ImportError: allauth needs to be added to INSTALLED_APPS. This is my settings.py in the relevant areas INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.sites", # 3rd party libraries "rest_framework", "corsheaders", "rest_framework.authtoken", "allauth", "allauth.account", "allauth.socialaccount", "dj_rest_auth", "dj_rest_auth.registration", # Local "accounts", "posts", ] ...... TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "django.template.context_processors.request", ], }, }, ] .... AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ] I appreciate the help in advance. I tried checking the documentation, checked all the commas were put in the appropriate place. Looked for similar situations on reddit and stackoverflow but coudln't find anything along that line. -
Selected categories not showing in django
I'm learning how to make Django websites, simple for now. It is necessary that the category of each account is displayed through the p tag, and all through the rest a. Following the results of all categories are links How it should look As a result is displayed tags.py register = template.Library() @register.simple_tag def get_category(filter=None): if not filter: return Category.objects.all() else: return Category.objects.filter(slug_fields=filter) @register.simple_tag(name="hypixel_accaunts") def get_accaunt(): return hypixel.objects.all() @register.inclusion_tag('product/hyp_cats.html') def show_category(sort=None, cat_selected=0): if not sort: category = Category.objects.all() else: category = Category.objects.order_by(sort) return {'category': category, 'cat_selected' : cat_selected} From hyp_cats.html {% for c in category %} {% if c.slug_fields == cat_selected %} <p>{{ c.name }}</p> {% else %} <a href="{{ c.get_absolute_url }}">{{ c.name }} </a> {% endif %} {% endfor %} From main templates {% get_category as get_cats %} {% if cat_selected == 0 %} <p>All accaunts</p> {% else %} <a href="{% url 'hype' %}">All accaunts</a> {% endif %} {% show_category '-name' cat_selected %} <br> {% block content %} {% endblock %} From views.py def show_acc(request, acc_id): accaunt = get_object_or_404(hypixel, nickname=acc_id) contex = { 'accaunt': accaunt, 'cat_selected' : accaunt.cat, } return render(request,'product/hype_accaunt.html', context=contex) From models.py class Category(models.Model): name = models.CharField(max_length=50, db_index=True) slug_fields = models.SlugField(max_length=255,unique=True, db_index=True, verbose_name="URL") def __str__(self): return self.name … -
how to solve Veem payment gateway 'createpayment' error:50000000
i am using veem payemnt gatway for online payments. when i hit the endpoint i am gettting error {"code":50000000,"message":"Value is unexpected: NZ","timestamp":"2023-08-24T12:05:10.825","fileName":"VeemResponseHandler.java","lineNumber":89} import requests import uuid url = "https://sandbox-api.veem.com/veem/v1.1/payments" payload = { "amount": { "currency": "USD", "number": 12345 }, "payee": { "countryCode": "US", "type": "Incomplete", "businessName": "aaaa", "email": "jawadkhan31849@gmail.com", "firstName": "JAWAD", "lastName": "KHAN", "phone": "+9266364644" }, "approveAutomatically": True, "attachments": [ { "type": "ExternalInvoice", "name": "test.txt", "referenceId": "123456" } ] } headers = { "accept": "application/json", "content-type": "application/json", "authorization": "Bearer e340f2cc-5124-44c7-b1f5-0737bcd9df35", "X-REQUEST-ID": str(uuid.uuid4()) } response = requests.post(url, json=payload, headers=headers) print(response.text) -
Django smart-select ChainedModelChoiceField not working properly
I need to have a dependent dropdown box using smart-select where I filter by Country, State, City and finally Area. These are the relevant models: class Country(models.Model): tenant = models.ForeignKey(Tenant, on_delete=models.PROTECT) country_name=models.CharField(max_length=50) is_active=models.BooleanField(default=True) class State(models.Model): country=models.ForeignKey(Country, on_delete=models.CASCADE) state_name=models.CharField(max_length=50) is_active=models.BooleanField(default=True) class City(models.Model): state=models.ForeignKey(State, on_delete=models.CASCADE) city_name=models.CharField(max_length=50) is_active=models.BooleanField(default=True) class Area(models.Model): city=models.ForeignKey(City, on_delete=models.CASCADE) area_name=models.CharField(max_length=50) is_active=models.BooleanField(default=True) And this is what I have tried in Forms: class CountryFormChoiceField(ModelChoiceField): def label_from_instance(self, obj): return obj.country_name class HomeForm(forms.Form): #some other fields country_name=CountryFormChoiceField(queryset=Country.objects.filter(is_active=True), label='Select Country') state_name=ChainedModelChoiceField('common','State','country_name','country','common','Country','country',show_all=False,auto_choose=False) city_name=ChainedModelChoiceField('common','City','state_name','state','common','State','state',show_all=False,auto_choose=False) area_name=ChainedModelChoiceField('common','Area','city_name','city','common','City','city',show_all=False,auto_choose=False) But in the site, only the country field has values in the dropdown, and even after selecting a country the other fields are not showing any options. This is the template: {% load has_group %} {% block content %} <div class="home"> {% if request.user|has_group:"Organization" %} <h1>Signed in as Organization</h1> {% else %} <h1>Welcome to Gamefront</h1> <form action="" method="post" class="homeform"> {% csrf_token %} <table> {{ form.media.js }} {{ form.as_table }} </table> <input type="submit" value="Submit" class="btn btn-outline-primary"> </form> {% endif %} </div> {% endblock %} What could be the issue? -
CSRF verification failed. Request aborted when i upgraded my django to the latest
I have been developin a quiz app in django 3.8 and it was working rather well but when i updated to the latest django the code is breaking. The code is supposed to calculate the marks of the the student after they submit the answers after which it redirects to view the results.. here is my views.py code for that particular functionality def calculate_marks_view(request): if request.COOKIES.get('course_id') is not None: course_id = request.COOKIES.get('course_id') course=QMODEL.Course.objects.get(id=course_id) total_marks=0 questions=QMODEL.Question.objects.all().filter(course=course) for i in range(len(questions)): selected_ans = request.COOKIES.get(str(i+1)) actual_answer = questions[i].answer if selected_ans == actual_answer: total_marks = total_marks + questions[i].marks student = Student.objects.get(user_id=request.user.id) result = QMODEL.Result() result.marks=total_marks result.exam=course result.student=student result.save() return HttpResponseRedirect('view-result') And this is the django html code to display the options and the questions and the submit answers {% extends 'student/studentbase.html' %} {% block content %} {%load static%} <head> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@300;400;500;600;700&display=swap" rel="stylesheet"> <style type="text/css"> body, p, a, h1, h2, h3, h4, h5, h6 { font-family: 'Quicksand', sans-serif; } </style> </head> <div class="jumbotron my-4"> <form class="form" autocomplete="off" onsubmit="return saveAns()" action="/student/calculate-marks" method="POST"> {% csrf_token %} <h2 style="text-align: center;">Topic: {{course.course_name}}</h2> {% for q in questions%} <h3 class="text-danger">{{ forloop.counter }}. {{q.question}}</h3><h4 style="text-align: right;">[{{q.marks}} Marks]</h4> <input type="hidden" name="csrfmiddlewaretoken" value="C24rUotmdHawVQJL3KrqiWxvti8UffOFYUc8TRbZtLt36AVLdP3jbkzUVe3beRAa"> <div class="form-check … -
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}'