Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can we transfer ERC721 tokens through MetaMask and JavaScript?
We are trying to develop an NFT marketplace in a Django project. At this point we know how to integrate MetaMask with our project and use the JavaScript MetaMask API to send ETH transactions ('eth_sendTransaction') or check the balance of a wallet. But we would also know how to transfer NFT (ERC721) tokens between wallets (allow users to buy their NFTs) with and endpoint of this JavaScript API for MetaMask. If it's possible, we would like to have the transfer of the ERC721 token and the amount of ETH payed in the same transaction. Like it's shown in the image below: Example of SepoliaETH token transfer Is there any endpoint in the link below which can help us solving this issue? MetaMask API Thank you We tried to use scripts but we don't want to have the private keys of the users' wallets in our marketplace server because we don't have the permissions to store this kind of data. -
Django Admin & Cloud Storage - Favicon is not uploaded to bucket and not referenced by website
I wanted to use Cloud Storage for my static and media files. Static files work properly by following this answer: https://stackoverflow.com/a/72216226/20802935 The DEFAULT_FILE_STORAGE has been deprecated since version 4.2 so I used this instead: #settings.py STORAGES = { "default": {"BACKEND": "core.gcs_utils.Media"}, "staticfiles": {"BACKEND": "core.gcs_utils.Static"}, } I'm using Gunicorn and Docker -
Django-Unicorn: django_unicorn.errors.ComponentModuleLoadError: The component module 'views_unicorn' could not be loaded
I have a Django Application where I need a partial refresh and I wanted to implement django-unicorn. It works locally but on the server, I am getting this error. The server runs gunicorn. The setup I tried to follow and based my items on it in the documentation here: https://www.django-unicorn.com/docs/direct-view/#template-requirements Traceback (most recent call last): File "/home/django/.local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/django/.local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.10/dist-packages/sentry_sdk/integrations/django/views.py", line 84, in sentry_wrapped_callback return callback(request, *args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/decorator.py", line 232, in fun return caller(func, *(extras + args), **kw) File "/home/django/.local/lib/python3.10/site-packages/django_unicorn/decorators.py", line 16, in timed return func(*args, **kwargs) File "/home/django/.local/lib/python3.10/site-packages/django_unicorn/views/__init__.py", line 49, in wrapped_view return view_func(*args, **kwargs) File "/home/django/.local/lib/python3.10/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) File "/home/django/.local/lib/python3.10/site-packages/django/utils/decorators.py", line 134, in _wrapper_view response = view_func(request, *args, **kwargs) File "/home/django/.local/lib/python3.10/site-packages/django/views/decorators/http.py", line 43, in inner return func(request, *args, **kwargs) File "/home/django/.local/lib/python3.10/site-packages/django_unicorn/views/__init__.py", line 555, in message json_result = _handle_component_request(request, component_request) File "/home/django/.local/lib/python3.10/site-packages/django_unicorn/views/__init__.py", line 408, in _handle_component_request return _process_component_request(request, component_request) File "/home/django/.local/lib/python3.10/site-packages/django_unicorn/views/__init__.py", line 86, in _process_component_request component = UnicornView.create( File "/usr/local/lib/python3.10/dist-packages/decorator.py", line 232, in fun return caller(func, *(extras + args), **kw) File "/home/django/.local/lib/python3.10/site-packages/django_unicorn/decorators.py", line 16, in timed return func(*args, **kwargs) File "/home/django/.local/lib/python3.10/site-packages/django_unicorn/components/unicorn_view.py", line 927, … -
Can I use AES Encryption in Django + MySQL? If yes, will it affect the use of Django's ORM and other features?
We are migrating our PHP codebase to Django. In the current application, all database columns are encrypted (except ID) using AES_ENCRYPT and AES_DECRYPT. something like this: $sql = " INSERT INTO users SET username = AES_ENCRYPT('".$email."','".$key."') , email = AES_ENCRYPT('".$email."','".$key."') "; $sql = "SELECT id , AES_DECRYPT(username ,'".$key."'), AES_DECRYPT(email,'".$key."')" Can this code be replicated in Django and is it possible to still maintain the cool features of Django like migration and ORM? -
Django redirect to Instagram
I'm creating a simple service in Django that redirects to Instagram social profiles. I have some troubles with Android devices where, even if the Instagram appis installed, the link is opened in the browser. I would like the link to be opened with the app, as already happens for iPhones. Here is the code: urls.py from django.urls import path from . import views urlpatterns = [ path('insta-bio/', views.redirect_to_url, name='redirect-to-url'), ] views.py from django.shortcuts import redirect def redirect_to_url(request): my_url = 'https://www.instagram.com/thesimpsons/' return redirect(my_url) I also tried with RedirectView type CBV, but nothing change... Any advice??? Thank's! -
mozilla-django-oidc doesnt authenticate users
I am using mozilla-django-oidc to authenticate keycloak users but i doesnt work. this is settings.py: AUTHENTICATION_BACKENDS = ( 'mozilla_django_oidc.auth.OIDCAuthenticationBackend', ) OIDC_RP_CLIENT_ID = 'HoubanCrm' OIDC_RP_CLIENT_SECRET = '7n9Kw7FgVYEkr1NKUDUA9KDBlMBiFjMS' OIDC_OP_AUTHORIZATION_ENDPOINT = 'http://localhost:8080/realms/HoubanCrm/protocol/openid-connect/auth' OIDC_OP_TOKEN_ENDPOINT = 'http://localhost:8080/realms/HoubanCrm/protocol/openid-connect/token' OIDC_OP_USER_ENDPOINT = 'http://localhost:8080/realms/HoubanCrm/protocol/openid-connect/userinfo' and when I want to login it redirect corrctly to keycloak but I get this erroe when I try to login: JWS token verification failed. Traceback (most recent call last): File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/django/views/generic/base.py", line 143, in dispatch return handler(request, *args, **kwargs) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/mozilla_django_oidc/views.py", line 124, in get self.user = auth.authenticate(**kwargs) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/django/views/decorators/debug.py", line 73, in sensitive_variables_wrapper return func(*func_args, **func_kwargs) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/django/contrib/auth/__init__.py", line 79, in authenticate user = backend.authenticate(request, **credentials) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/mozilla_django_oidc/auth.py", line 324, in authenticate payload = self.verify_token(id_token, nonce=nonce) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/mozilla_django_oidc/auth.py", line 218, in verify_token payload_data = self.get_payload_data(token, key) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/mozilla_django_oidc/auth.py", line 201, in get_payload_data return self._verify_jws(token, key) File "/home/gmtii/PycharmProjects/djangoProject6/.venv/lib/python3.10/site-packages/mozilla_django_oidc/auth.py", line 157, in _verify_jws raise SuspiciousOperation(msg) django.core.exceptions.SuspiciousOperation: JWS token verification failed. Bad Request: /oidc/callback/ [01/Feb/2024 06:48:28] "GET /oidc/callback/?state=R3r6Dg2XcLCWUIVlEUOOkqra0aU1Ta7t&session_state=068dc2c3-1b4f-447f-b31f-56f14a3adb5c&iss=http%3A%2F%2Flocalhost%3A8080%2Frealms%2FHoubanCrm&code=d65bdaef-0c4b-4231-a341-217e51966c7a.068dc2c3-1b4f-447f-b31f-56f14a3adb5c.e38b37dd-6828-4bb9-a457-babc25eb4e01 HTTP/1.1" 400 126592 I printed the jws token it seems ok -
I'm setting the category as the url in django and i'm getting error that ';' expected.javascript
I'm setting the category as the url in django and i'm getting error that ';' expected.javascript {% for category in all_categories %} <div onclick="location.href='{% url 'category' category.category %}';" style="box-shadow:0 5px 30px 0 rgba(0,0,0,.05);" class="hover:scale-105 hover:transform transition duration-300 cursor-pointer bg-gray-900 rounded-lg h-40 w-full my-4 text-center p-5 grid place-items-center"> <div> <p class='text-4xl my-2'><i class="bi bi-tags text-transparent bg-clip-text bg-gradient-to-r from-cyan-200 to-blue-500"></i> </p> <p class='text-base'>{{ category.category }}</p> </div> </div> {% endfor %} -
Django "Failed to establish a new connection: [Errno 111] Connection refused" error when connecting to django API via python script
I have this basic django api that i can access through the browser at https://127.0.0.1:8000/norm/status/; however, when i use python script to connect to it, i keep getting multiple error. This is the python script: BASE_URL='https://127.0.0.1:8000' ENDPOINT='norm/status/' headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36'} def get_resource(): resp=requests.get(BASE_URL+"/"+ENDPOINT, verify=False, headers=headers) print(resp.status_code) print(resp.json()) get_resource() The errors i see: urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x7f80f8286490>: Failed to establish a new connection: [Errno 111] Connection refused urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='127.0.0.1', port=8000): Max retries exceeded with url: /norm/status/ (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f80f8286490>: Failed to establish a new connection: [Errno 111] Connection refused')) I am running the django server inside a docker container and i am not sure if it has anything to do because of that. I really appreciate if someone can help me debug this. Thanks! I tried using django-cors-headers and also HTTPAdapter libraries but it didn't work. -
"mptt_tags" is not registered tags - Django Erro
I am having error when developing blog website.Can anyone help ? raise TemplateSyntaxError( django.template.exceptions.TemplateSyntaxError: 'mptt_tags' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz I have installed in settigs.py as 'mptt' also and tried rerunning the server also.but couldn't find answer. I need to solve this error -
How to monitor Celery worker and return the task back to the queue if the worker dies or is killed?
**Problem Description:** I have a microservice that uses Celery for executing asynchronous tasks. I need to monitor the state of the Celery worker and return the task back to the queue if the worker dies or is killed (e.g., due to a SIGKILL signal). I also have another instance of Celery running on the main service side. **Question:** Is there a way to monitor the state of the Celery worker and automatically return the task back to the queue if the worker dies or is killed? **Additional Information:** - Using visibility_timeout is not suitable as it would require waiting for a day before the task returns to the queue, while I need it to happen almost instantly. -
Design and architecture of Blood Donation Managment in Django
I have almost completed the famous Django tutorial; Writing your first Django app. To consolidate my concepts I want to do a project in Django. So, I am starting a Blood Donation Management System in Django. It is supposed to serve as a network of blood donors and seekers, both the donors and seekers will be able to register, and search through blood group type, and the search result will show list the list of donors/seeker along with the contact details. This way it going to serve the blood donors/seekers community. What I want here is only a design level guidance; What apps should I create. What should the model (tables and attributes) What views should I code I cannot figure out the project structure or a sketch that I should follow. Initially I want only a sketch of the design to have a roadmap to follow along. Best Regards -
Is it possible to prevent deleting multiple objects at once from leaving <2 objects remaining in the Django admin site?
I have a Highlight class with a ForeignKey relationship to the Organism class. On the admin site, Highlights are an inline of Organism. I want each organism object to have 2-5 highlights. I want it to be impossible to use the Organism admin page to delete highlights from an organism in a way that leaves <2 remaining. In models.py: class Organism(BaseModel): ... class Highlight(BaseModel): organism = models.ForeignKey(Organism, on_delete=models.CASCADE) ... class HighlightAdmin(admin.ModelAdmin): ... In admin.py: class HighlightInline(admin.TabularInline): model = Highlight max_num = 5 extra = 1 min_num = 2 ... line_numbering = 0 def count(self): return self.line_numbering def line_number(self, obj): self.line_numbering += 1 return self.line_numbering def has_delete_permission(self, request, obj=None): messages.add_message(request, messages.ERROR, ( request.POST.dict(), request )) if obj.highlight_set.count() > self.min_num: return True elif obj.highlight_set.count() == self.min_num: return False messages.add_message(request, messages.ERROR, ( "Can't have fewer than 2 highlights" )) return False # return return super().has_delete_permission(request, obj) class OrganismAdmin(admin.ModelAdmin): inlines = [HighlightInline] ... admin.site.register(Organism, OrganismAdmin) admin.site.register(Highlight, HighlightAdmin) The function has_delete_permission counts the number of highlights associated with the organism we are deleting highlights from. When there are 0-2 highlights, there are no Delete checkboxes (which is intended). When there are >2 highlights, there are Delete checkboxes. If I have 3 highlights and delete one … -
Customizing Django Admin filters
I’m running an old Django 1.3 website. We use the admin pages to view the models. One of the fields of the model is the User accounts. Filtering is enabled on the admin page for the User field. The problem is that I want it to list only active users. Or better yet, only to show users that exist in the instances of the model. Later versions of Django has a feature that can easily do this. I.e.: list_filter = [ ("author", admin.RelatedOnlyFieldListFilter), ] Is there a way to do this in 1.3? I hope to avoid doing an update, simply to make this one change. Thanks. -
Django: CSRF Verification always fails
So I have separate frontend and backend servers and when I'm performing any POST action from my frontend I'm passing a "Cookie" header with csrftoken inside, but for some reason it's not working. Then I've tried to pass in the csrftoken alone in the header, but it's still the same error. The strange part is that I can't see it in django request.META or request.headers. I use nginx for a reverse proxy and I use TLS for encryption. This is the strange part, where is the header at? X_CSRFTOKEN and Cookie is being passed from my frontend Django and django-cors config (And yeah I have all the required middlewares and in the right order): NOTE: When http://dev.admin.lt is removed I get another error: (Origin checking failed - http://dev.admin.lt does not match any trusted origins.): /auth/login/ CORS_ALLOWED_ORIGINS = [ "https://127.0.0.1", "https://admin.lt", "https://dev.admin.lt", "https://api.admin.lt", "http://dev.admin.lt", # NOTE, without this we get another error ] CSRF_TRUSTED_ORIGINS = [ "https://127.0.0.1", "https://admin.lt", "https://dev.admin.lt", "https://api.admin.lt", "http://dev.admin.lt" # NOTE, without this we get another error ] CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = True CSRF_COOKIE_SAMESITE = None CSRF_COOKIE_DOMAIN = ".admin.lt" # Is this actually doing anything? SESSION_COOKIE_SECURE = True SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SAMESITE = None SESSION_COOKIE_DOMAIN … -
Django backend can't connect to reddis?
i am asking the question with a questionmark because i don't actually know if this is the problem. For context everything worked fine on my local env. where i use docker-compose with reddis. I have a react frontend that does a websocket connection to the backend. The websocket connects to a azure caching for reddis service. Now i am using SSL for this connection and i am setting the right variables for my CHANNELS_LAYER config. My docker logging gives me this, so i know i am setting the right env's {'default': {'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': {'hosts': [('rediss://name.redis.cache.windows.net', 6380, 'REDDIS_PASS')]}}} My settings.py: redis_host = os.environ.get('REDIS_HOST', 'localhost') redis_port = int(os.environ.get('REDIS_PORT', 6379)) redis_password = os.environ.get('REDIS_PASSWORD', '') use_ssl = os.environ.get('USE_SSL', 'False') == 'True' redis_scheme = 'rediss' if use_ssl else 'redis' redis_url = f"{redis_scheme}://{redis_host}" CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [( redis_url, redis_port, redis_password )], }, }, } Now my frontend does a ws connection like this: const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const wsUrl = `${wsProtocol}//name-api.azurewebsites.net/ws/endpointurl/`; const ws = new WebSocket(wsUrl); ws.onmessage = event => { const message = JSON.parse(event.data); switch (message.type) { case 'send_progress_update': setProgress(message.progress); console.log(newTabIndex); if (message.progress === 100) { if ( (grids.length === 1 … -
Predefined performance evaluation per user
I am trying to make an app for the performance evaluation of workers by their boss. For this, there is a database with information on the workers, from which information such as the ID must be extracted, in such a way that to evaluate a worker, personal information must be passed as a parameter in the url of the form and The evaluation is displayed with some complete fields of personal information and 15 questions to answer and stored in a new table to later report on the data. A worker can have many evaluations, for example one monthly. However, I can't get it to work. At first I tried to do it with 2 models, but when it didn't work, I added a third one that would relate to the previous 2. I think the error is in view.py, can someone help me please? Models.py: from django.db import models # Create your models here. nota= ( ('25','Casi Nunca'), ('50','Algunas Veces'), ('75','Con Frecuencia'), ('100','Siempre'), ) recomienda = ( ('0', 'no'), ('100', 'si') ) class Trabajador(models.Model): nombre = models.TextField(max_length = 50, null=False) codigo = models.TextField(max_length = 8, primary_key=True, null=False, unique=True) rut = models.TextField(max_length = 10, null=False, unique=True) cargo = models.TextField(max_length = … -
Reading data corresponding to a specific ID from the database and passing the data to an API
I am trying to fetch data from a database table named "orders_address" by specifying the required ID in the request body and I expect to receive the row for this specific ID along with an API result in the response. However, I can't get fetch the data for this specific ID from the database. I am using DJANGO. I am applying this request body: { "orders": [1] } and my response results is: {"error": "No orders found for the given order IDs."} Here is my route_optimization.py script which does the function needed: import requests from django.http import JsonResponse from orders.models import Order import configparser import json # Read configuration file config = configparser.ConfigParser() config.read('config.ini') # Get Nextbillion.ai API key from config NB_API_KEY = config['API_KEYS']['NB_API_KEY'] def optimize_route(request): if request.method == 'POST': try: data = json.loads(request.body) order_ids = data.get('orders', []) print("Received order IDs:", order_ids) # Debugging statement # Fetch orders from the database based on order IDs orders = Order.objects.filter(id__in=order_ids) print("Orders:", orders) # Debugging statement # Ensure that orders are retrieved if not orders: return JsonResponse({'error': 'No orders found for the given order IDs.'}) # Construct list of delivery locations for Nextbillion.ai API payload delivery_locations = [ {"latitude": order.address.latitude, "longitude": order.address.longitude} for … -
Case-insensitive filter in Django admin using SimpleListFilter
I have a SimpleListFilter in the Django admin panel that filters values (ingredients) based on their first letters (see the code below). The issue is that ingredients could be saved/updated in the database with either uppercase or lowercase letters. Because of this, the filter starts behaving incorrectly, displaying two fields for the same letter (for example, A(1) and a(70)). I've addressed the problem by overwriting CharField in my models (see the code below). But I'm not satisfied with this solution as it's not universal. Is there a way to make this filter case-insensitive without modifying the values before adding them into the database? I want the filter to work regardless of the letter case. (for example, A(71)). class FirstLetterAlphabetiseFilter(admin.SimpleListFilter): title = _('First letter') parameter_name = 'first_letter' def lookups(self, request, model_admin): ingredients = model_admin.get_queryset(request) for letter in sorted( ''.join(set(ingredient.name[0] for ingredient in ingredients)) ): count = ingredients.filter(name__istartswith=letter).count() if count: yield (letter, f'{letter} ({count})') def queryset(self, request, ingredients): if not self.value(): return ingredients return ingredients.filter( name__istartswith=(self.value())) class NameField(models.CharField): """Converts NameField into lower case while saving in database.""" def __init__(self, *args, **kwargs): super(NameField, self).__init__(*args, **kwargs) def get_prep_value(self, value): return str(value).lower() -
How can i modify the serializer.is_valid() method for existing rows on the database so it passes the validation
**I am trying to insert a list of objects by using serializer.save() but when i try to insert existing data it throws error and doesn't pass the validation how can i modify the is_valid() method or is there any way of skipping the existing objects and inserting the others inside the method ** //Saving data = sanitizer.to_dict() serializer = serializer_class(data=data, many=True) if serializer.is_valid(raise_exception=True): serializer.save() //Serializer from apps.trades.models import Trade from rest_framework import serializers class TradeSerializer(serializers.ModelSerializer): class Meta: model = Trade fields = ['identifier', 'issue_date', 'maturity_date', 'invested_amount', 'interest_rate'] The validation error: [{"identifier":["trade with this identifier already exists."]} -
redirect https non-www to https www for nginx django
I tried many solutions but nothing worked. I am trying to redirect https://example.com to https://www.example.com. If I write https://example.com in the address bar, I get an insecure website prompt. I have ssl certificate installed for www.example.com. Here's the code from nginx server: server { server_name exmaple.com www.exmaple.com; location ~ ^/.well-known { root /home/xyz/xyz-dir; allow all; } location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/xyz/xyz-dir; } location /media/ { root /home/xyz/xyz-dir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/www.exmaple.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/www.exmaple.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.exmaple.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = 'exmaple.com') { return 301 https://www.$host$request_uri; } # managed by Certbot listen 80; server_name exmaple.com www.exmaple.com; return 404; # managed by Certbot } -
How to implementing Razorpay Test Mode Withdrawal in Django Web App
I'm in the process of developing a Django web app where users can initiate withdrawals with the following flow: On the website, users have the option to withdraw a specific amount. Upon clicking the withdraw button, users are directed to the next page. On this page, users are prompted to enter their bank details. After saving the bank details, users can click the "Continue" button. At this point, I want the specified amount to be automatically transferred to the entered bank account, all while operating in Razorpay's test mode. I would greatly appreciate any insights, code examples, or references on how to implement this flow effectively. Your help is invaluable. Thank you! -
Subclassed Django SelectMultiple ignores any attribute set to its options
following what I found in this answer I am trying to add a custom class to each option into the two select the widget produces. I used the FilteredSelectMultiple admin widget, which is made of two list of elements the user can interact with to select one or more elements. My relevant code: from django.contrib.admin.widgets import FilteredSelectMultiple class MySelectMultiple(FilteredSelectMultiple): def create_option(self, name, value, *args, **kwargs): option = super().create_option(name, value, *args, **kwargs) print(option) option.update({'attrs': {'foo':'bar'}}) # set option attribute print(option) return option from django import forms class MyReportForm(forms.Form): filters = forms.ModelMultipleChoiceField( queryset= Item.objects.none(), # fixed below widget=MySelectMultiple("Item", is_stacked=True), required=False ) def __init__(self, *args, **kwargs): from myapp.utils import get_all_enabled_items super(MyReportForm, self).__init__(*args, **kwargs) # this returns a filtered queryset self.fields["filters"].queryset = get_all_enabled_items(lvl0=True) The dictionary gets updated correctly if printed, but the form just ignores the attributes I set and produces the same HTML: <select name="generic_filters" id="my_id_from" multiple="multiple" class="filtered" data-is-stacked="1"> <option value="1" title="myTitle1">myTitle1</option> <option value="2" title="myTitle2">myTitle2</option> <option value="3" title="myTitle3">myTitle3</option> </select> Please note that if I try to change the "value" using the same code (with option.update({'value':'0'}), the value correctly changes (and makes all the options have the same value!) What am I doing wrong? How do I set an attribute for each select option … -
Django mysql database eats too much RAM even though no queries are coming in
I rented a small vps(1core 1gb-ram 15ssd) for my Django project. When I added another endpoint to the project, the database on the server suddenly started crashing from lack of RAM (the process was simply killed by the system). Attempts to restart the database with the systemctl restart command resulted in an error, and I was unable to restart the database until I shut down another process(telegram integration) to free up memory. My queries are optimised. Hoping to ease the load on RAM, I changed the innodb_buffer_pool_size and key_buffer_size configurations within 1-16M, but the situation didn't change much. Having increased the server rate to 2gb of RAM, I found that RAM consumption increased (mysql's VIRT value in htop before the upgrade was ~1200, now it is ~1600). Are these normal values of RAM consumption? Why is the database consuming so many resources while idle? How can I redistribute the load between cpu and ram? Why did adding a feature to django affect the database so much(before even using it)? I would really appreciate a detailed explanation of Django's behavior and its impact on the DB, or any advice -
Django not able to authenticate username and password , although data is present is db and the entered data is checked correctly
view.py def loginverify(request): print("-----------login verification------------") if request.method == "POST": cemail = request.POST.get("cemail") cpassword = request.POST.get('cpassword') print(cemail, cpassword) (able to print the data sent ) User = authenticate(request, email=cemail, password=cpassword) print(User)-->(this shows none) if User is not None: login(request, User) print("no problem") messages.success(request, 'Login successful') return redirect('dashboard') # Redirect to the user's dashboard or landing page else: messages.error(request, 'Invalid email or password') print("problem occurred") template = 'polls/login.html' return render(request, template) # Redirect to login page template = 'polls/CustLandingpage.html' return render(request, template) *well the data is received by this function but the authentication is not working * model.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class Customer(models.Model): name = models.CharField(max_length=20) Email = models.CharField(max_length=50) password = models.CharField(max_length=20) USERNAME_FIELD = 'Email' REQUIRED_FIELDS = ['name'] for authentication email and password is used , I tried most of the things but its not working , kindly help -
How to call a View function from another one on Python Django
I'm creating a project that gets NBA data from an API with Python-django. I got a view that renders the index.html page and created another one that generates the data and save it on a model. I think it's completely wrong but i'm kinda stuck....Basically I want to display the index.html page with all the objects on the model Post (at this time this part works), but I also want to call the view "Pontos" to create the posts automatically if some parameter it's called (example, I would create a IF to see if the datetime was 11 o'clock. If it's true, then call the 'Pontos' view to generate the data that would be displayed on index.html) but I don't know how to call the view on another view. Can someone explain to me what I could do to solve this ? I tried creating and IF on the index view to call the Pontos view, but when the Pontos View it's called, it returns his own index.html without the parameters needed....resulting in a blank page.