Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Websocket connection through nginx returns 400 - Hixie76 protocol not supported
I have a (fairly complex) django app hosted on AWS via Elastic Beanstalk, and am trying to implement websockets on it, using django-channels Here is the docker-compose.yml file sent to elastic beanstalk: version: "3.8" services: migration: build: . env_file: - .env command: python manage.py migrate api: build: . env_file: - .env command: daphne myapp.asgi:application --port 8000 --bind 0.0.0.0 deploy: restart_policy: condition: on-failure delay: 5s max_attempts: 3 window: 120s expose: - 8000 depends_on: - migration nginx: image: nginx:1.21.0-alpine env_file: - .env volumes: - ./nginx/templates:/etc/nginx/templates - ./nginx/certs:/etc/nginx/certs ports: - 80:80 - 443:443 depends_on: - api deploy: restart_policy: condition: on-failure delay: 5s max_attempts: 3 window: 120s Here is the nginx config file: server { listen 80; listen [::]:80; location /health/ { proxy_pass http://api:8000/health/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location / { return 301 https://$host$request_uri; } } server { listen 443 ssl; listen [::]:443 ssl; root /usr/share/nginx/html/; index index.html; ssl_certificate /etc/nginx/certs/public.crt; ssl_certificate_key /etc/nginx/certs/myapp.pem; location / { proxy_pass http://api:8000/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_read_timeout 300s; } client_max_body_size 5M; } When running on my local machine, everything runs smooth. … -
Django - Return remaining throttle calls available
I am trying to retrieve the remaining calls available with no luck, the use case is sending that data in the response or headers to the frontend, so that the end user can check the credit of API calls available settings.py REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.ScopedRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'my_view': '10/day', } } views.py class MyView(APIView): throttle_classes = [ScopedRateThrottle] throttle_scope = 'my_view' -
Somebody help please [closed]
Command Prompt-python manage.py runnerver C:\Users\jeanl\lecture3>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Jeanl\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\uris\resolvers.py", line 717, in url patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\jeanl\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1838, in bootstrap_inner self.run() File "C:\Users\jeanl\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self. target("self._args, **self. wargs) File "C:\Users\jean1\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, *args) File "C:\Users\jean1\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner run self.check(display_num_errors=True) File "C: Misers\jean1 VApplata\Local\Programs\Python\Python311\Lib\site-packages\django\core\nanagement\base.py all issues checks.run checks( ", line 485, in check File "C:\Users\JeanlopData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\registry.py", line 88, in run checks new_errors= check(app_configs-app_configs, databases-databases) File "C:\Users\Jean1VppData\Local\Programs\Python\Python311\lib\site-packages\django\core\checks \urls.py", line 42, in check_url_namespaces_unique all namespaces load all nanespaces(resolver) File "C:\Users\Jean1VppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 72, in _load_all_namespaces namespaces.extend(_load_all_namespaces (pattern, current)) File "C:\Users\Jeanl\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 61, in load_all_namespaces url patterns getattr(resolver, "url patterns", []) File "C:\Users\Jean1\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\functional.py", line 57, in get_ res instance._dict [self.nase] self.func(Instance) File "C:\Users\Jean]\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\urls\resolvers.py", line 725, in url patterns raise ImproperlyConfigured (msg.format(name-self.urlconf_name)) from e django.core.exceptions. ImproperlyConfigured: The included URL cont module "hello.urls' from 'C:\Users\Jean]\lecture3\hello\urls.py's does not appear to have any patterns in it. If you see the 'urlpatterns variable with valid patterns in the file then the issue … -
Django allauth - SocialTokens table empty after Google Login
Python: 3.8.10 Django: 4.1.7 django-allauth: 0.54.0 I'm working on a webpage which I have to connect to the Company Google Workspace. I correctly managed the login, with no issues. Now, I have to connect to the Gmail of the authenticated user. For connecting to Google Apps I need a Token that, as I understood, should be in the Database in the table SocialTokens (automatically filled-in after the login phase). I populated Sites and Social Application manually, and rightly (I guess) based on fact that login works. The authentication works properly, but after the login the model SocialToken (table "Social application tokens") is still empty. But I cannot figure out why the table SocialTokens is not populated after the correct Google login. Here my settings.py SITE_ID = 1 INSTALLED_APPS = [ 'django.contrib.admin', ..., 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] SOCIALACCOUNT_PROVIDERS = { 'google':{ 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': {'access_type':'offline'}, } } SOCIALACCOUNT_STORE_TOKEN = True SOCIALACCOUNT_AUTO_SIGNUP = True I tried what below: update django-allauth (0.4 --> 0.54) SOCIALACCOUNT_STORE_TOKEN = True --> set False, True and unset(commented and deleted) SOCIALACCOUNT_AUTO_SIGNUP = True --> set False, True and unset(commented and deleted) two lines above in all their combinations (es. SOCIALACCOUNT_STORE_TOKEN = True and SOCIALACCOUNT_AUTO_SIGNUP … -
Crontab inside a Bash file
I want to start my django project and execute every 10 min a BaseCommand. I wrote bash file it doesn't seem to work. I have some cronjob code but I don't know if this is enough... */10 * * * * python3 manage.py read_create_earning_reports ...or activating the virtual environment for the crontab is neccessary. */10 * * * * cd /Users/andreysaykin/Documents/project_distrokid/project_dk && source ../bin/activate && python3 manage.py myBaseCommand Afterwards I start my server. cd /my/django/project/path source ../bin/activate python3 manage.py runserver What my current Problem is that I am getting this Error: /Users/username/Documents/bash/myScript.sh: line 2: */10: No such file or directory -
Fail dockerizing Django+ PostgreSQL project due to problem with installing psycopg2
I created a Django project which uses PostgreSQL as database. I already have PostgreSQL container and was trying to create an image of my project when I faced the following errors: Preparing metadata (setup.py): started #8 46.75 Preparing metadata (setup.py): finished with status 'error' #8 46.75 error: subprocess-exited-with-error #8 46.75 #8 46.75 × python setup.py egg_info did not run successfully. #8 46.75 │ exit code: 1 #8 46.75 ╰─> [25 lines of output] #8 46.75 /usr/local/lib/python3.12/site-packages/setuptools/config/setupcfg.py:508: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead. #8 46.75 warnings.warn(msg, warning_class) #8 46.75 running egg_info #8 46.75 creating /tmp/pip-pip-egg-info-h_1_kknf/psycopg2.egg-info #8 46.75 writing /tmp/pip-pip-egg-info-h_1_kknf/psycopg2.egg-info/PKG-INFO #8 46.75 writing dependency_links to /tmp/pip-pip-egg-info-h_1_kknf/psycopg2.egg-info/dependency_links.txt #8 46.75 writing top-level names to /tmp/pip-pip-egg-info-h_1_kknf/psycopg2.egg-info/top_level.txt #8 46.75 writing manifest file '/tmp/pip-pip-egg-info-h_1_kknf/psycopg2.egg-info/SOURCES.txt' #8 46.75 #8 46.75 Error: pg_config executable not found. #8 46.75 #8 46.75 pg_config is required to build psycopg2 from source. Please add the directory #8 46.75 containing pg_config to the $PATH or specify the full executable path with the #8 46.75 option: #8 46.75 #8 46.75 python setup.py build_ext --pg-config /path/to/pg_config build ... #8 46.75 #8 46.75 or with the pg_config option in 'setup.cfg'. #8 46.75 #8 46.75 If you prefer to avoid building psycopg2 from source, please install … -
Django admin autocomplete_fields saving everything in queryset
I am using Django Admin autocomplete_fields to save a bunch of zipcodes. I want to be able to save all the zipcodes in the queryset. Is that possible? I tried overwriting a bunch of methods but nothing has helped so far. -
Django mail error SMTPServerDisconnected: Connection unexpectedly closed even after setting all the correct details (including DEFAULT_FROM_EMAIL)
I am facing various problems (errors) while trying to send mail through django. I have checked other stackoverflow questions but none helped me Django version - 4.2 Django email specific settings- EMAIL_HOST = "county.herosite.pro" EMAIL_PORT = 465 # EMAIL_USE_SSL = True EMAIL_USE_TLS = True EMAIL_HOST_USER = "noreply@bulltrek.com" DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_HOST_PASWORD = "myPassword" Commands ran in django shell In [1]: from django.core.mail import send_mail In [2]: sender_email = "noreply@bulltrek.com" In [3]: send_mail("Hola","Gola",sender_email,[sender_email]) Error I got --------------------------------------------------------------------------- SMTPServerDisconnected Traceback (most recent call last) Cell In[4], line 1 ----> 1 send_mail("Hola","Gola",sender_email,[sender_email]) File ~/snadeepAlgoTradingPlatform/env/lib/python3.11/site-packages/django/core/mail/__init__.py:87, in send_mail(subject, message, from_email, recipient_list, fail_silently, auth_user, auth_password, connection, html_message) 84 if html_message: 85 mail.attach_alternative(html_message, "text/html") ---> 87 return mail.send() File ~/snadeepAlgoTradingPlatform/env/lib/python3.11/site-packages/django/core/mail/message.py:298, in EmailMessage.send(self, fail_silently) 294 if not self.recipients(): 295 # Don't bother creating the network connection if there's nobody to 296 # send to. 297 return 0 --> 298 return self.get_connection(fail_silently).send_messages([self]) File ~/snadeepAlgoTradingPlatform/env/lib/python3.11/site-packages/django/core/mail/backends/smtp.py:127, in EmailBackend.send_messages(self, email_messages) 125 return 0 126 with self._lock: --> 127 new_conn_created = self.open() 128 if not self.connection or new_conn_created is None: 129 # We failed silently on open(). 130 # Trying to send would be pointless. 131 return 0 File ~/snadeepAlgoTradingPlatform/env/lib/python3.11/site-packages/django/core/mail/backends/smtp.py:85, in EmailBackend.open(self) 83 connection_params["context"] = self.ssl_context 84 try: ---> 85 self.connection = self.connection_class( … -
Unable to run the command "python manage.py migrate"
I am trying to setup a virtual environment to test a website I'm working on that is running on django. When I created the project, it didn't include a settings.py file which I got a lot of errors about before and added one using a base example and changed some things. I then added django.contrib.sites to my settings.py file which others said helped, but didn't fix it. I ran the following commands pip install -r req.txt and when I try to run python manage.py migrate I get the error >> Traceback (most recent call last): File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\manage.py", line 22, in <module> main() File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 106, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\migrate.py", line 100, in handle self.check(databases=[database]) File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() ^^^^^^^^^^^^^^ File … -
Image upload for image processing to fill up related form fields in Django
I am new to Django. My task is to upload an image and do some image processing on it and fill up some fields based on the results obtained from the image. Then the user would maybe check if the values that get filled in are correct and if they are they will save the whole form with the image and all the other form fields. So, I am confused about the following. I already have the util functions for the image processing which is in python. How should I obtain the image immediately after the user select the file and do the image processing and receive my data from the processing keeping in mind that this will be happening in the server. My url for this page is "admin/book/add". I am not providing any code because I wanted to the general way of how to do something like this in django. My model includes -> BookModel: name, author, year ImageModel: Image, Image_thumbnail. // this will be filled after image processing Constructs: x, y, z Finally, the user will hit the save button and save I have tried using javascript to send AJAX and send the image only to backend, … -
How do I use a dict to translate ArrayAgg values for an annotation in Django?
I'm using Django 4 with Postgres. Say I have two related models like this: class Company(Model): ... class Address(Model): city = CharField(...) companies = ManyToManyField( Company, through=ThroughCompanyAddress, related_name="addresses" ) ... class ThroughCompanyAddress(Model): company_id = ForeignKey(Company, ...) address_id = ForeignKey(Address, ...) I want to annotate the cities that each company is in. Normally, I would do something like this: Company.objects.all().annotate(cities=ArrayAgg("addresses__city")) Unfortunately, because of the way my DevOps team has the databases configured, these tables are stored on different databases, and I can't do this. Instead, I need to do 2 queries - first, to get a mapping of address ids to city names, and then to somehow use that mapping to annotate them onto the company models. # After the initial query to the first database, I end up with this # Note: The int dict keys are the address model Primary Keys cities = {1: "Paris", 2: "Dubai", 3: "Honk Kong"} # Now how do I use this dict here? Company.objects.all().annotate( city_ids=Subquery( # Not tested, but I think something like this would work ThroughCompanyAddress.objects.filter( company_id=OuterRef('id') ).values("address_id") ) ).annotate(cities=???) How do I use the cities dict in my annotation here to translate city_ids to city names? I probably could do a … -
What does it mean Redis URL must specify one of the following schemes (redis://, rediss://, unix://)
I am getting this error message after a file upload is completed and the redirect is meant to take place. Redis URL must specify one of the following schemes (redis://, rediss://, unix://) I am not sure what the problem is as i am extremely new to django channels and redis, never used it before so i dont even understand this error. Basically i have everything from consumers.py,routing.py and a view function to handle file upload. -
Log results of asynchronous processes to a database field
I am working on a project using Django and Celery which takes large files and processes them in multiple steps. The main object for the file is called Sequencing and only one is created per file. Now for every Sequencing we create many samples, variations etc. Some of these are already in the db so we use a get or create. After the processing of each Sequencing, I would like to have the amount of created and the amount of reused objects written into a json field called metadata in the Sequencing object but as some processes run asynchronously, this does not work out. Some code excerpts: models.py: class Sequencing(...): metadata = models.JSONField( default=dict, blank=True, ) def log(self, level: str, msg: str | list, *args, **kwargs) -> None: """Records messages for users in metadata.""" if "log" not in self.metadata: self.metadata["log"] = [] self.metadata["log"].append( { "date": datetime.datetime.utcnow().isoformat(), "level": level, "msg": msg, } ) self.save() def load(self) -> None: chain( ... sequencing_load_variants.si(self.id), ... ) def load_variants(self) -> None: ... for contig in contigs: sequencing_load_variants_by_contig.delay(self.pk, contig=contig) def load_variants_by_contig(self, contig: str) -> None: # create samples # create variants .... self.log( "info", [f"Variants created for region {region.seqid}: {log_dict['variants_create']}"] + [f"Variants found for region {region.seqid}: … -
Form set admin django
I am a beginner programmer Qiez project There is a task in admin On one page Ability to add questions/answers to questions/mark correct answers on the test set page Tried NestedStackedInline, NestedModelAdmin Lots of settings Is there a better option -
"django.db.utils.ProgrammingError: relation already exists" for unique together constraint
How can I list all uniqueness constraints on a table and delete any ones that conflict with my Django migrations? Lots of other StackOverflow questions have asked about "relation already exist" errors, but this is specific to the uniqueness constraints. I do NOT want the usual recommended method of faking the migration python manage.py migrate --fake. I want to just delete the conflicting constraint so the migration can proceed normally. I tried to add a unique together constraint, it worked fine locally, but caused a "django.db.utils.ProgrammingError: relation already exists" error remotely. Specifically, I am getting an error like this. django.db.utils.ProgrammingError: relation "api_mytable_myfield1_myfield2_cb8c1059_uniq" already exists My migration file looks like this: class Migration(migrations.Migration): dependencies = [ ('api', '...'), ] operations = [ migrations.AlterUniqueTogether( name='mytable', unique_together={('myfield', 'myfield2')}, ), ] How can I make things work again? I am using Postgres. -
django serializer use fields for validation but exclude from validated_data
I have a serializer: class ValidateCreateNoCodeEvent(serializers.Serializer): ALLOWED_PLATFORM_VALUES = [(1, 'Android'), (2, 'iOS')] ALLOWED_GESTURE_TYPES = [ (0, 'Single Tap'), (1, 'Double Tap'), (6, 'Long Press') ] screen_name = serializers.CharField(max_length=100, min_length=1, required=True) gesture_type = serializers.ChoiceField(required=True, choices=ALLOWED_GESTURE_TYPES) view_type = serializers.CharField(required=True) sdk_version = serializers.CharField(required=True) platform = serializers.ChoiceField(required=True, choices=ALLOWED_PLATFORM_VALUES) element_id = serializers.CharField(required=True, allow_null=False, allow_blank=False) name = serializers.CharField(required=True, allow_blank=False, allow_null=False) category = serializers.ListField(required=True, min_length=1) description = serializers.CharField(required=False, max_length=500) def validate_sdk_version(self, sdk_version): ... does some validation return sdk_version def get_fields(self): fields = super().get_fields() exclude_fields = self.context.get('exclude_fields', []) for field in exclude_fields: # providing a default prevents a KeyError # if the field does not exist fields.pop(field, default=None) return fields So I would like to keep, say, platform and sdk_version fields for validation. They are a must for this payload input to proceed further. However, I would like to exclude them once I access payload.validated_data. I have tried to add get_fields method which just pops up whatever fields are passed in the context. context = { 'exclude_fields': [ 'sdk_version', 'platform' ] } payload = ValidateCreateNoCodeEvent(data=request.data, context=context) So this will also exclude the validation. How can I fix this? -
Convert docx to pdf on django
I want convert a docx file to pdf in django. I use from docx2pdf import convert library to convert my file. I add pythoncom.CoInitialize() to my code and it works well on vs.code environment. But in my cpanel environment import pythoncom and structure pythoncom.CoInitialize() do not define and it has error. please help me to make pdf file at cpanel environment. pythoncom.CoInitialize() doc = DocxTemplate("f.docx") context = { 'company_name' : "lllll" } doc.render(context) doc.save("generated_doc.docx") convert('generated_doc.docx') -
Why is Django looking for font in the wrong place and by the wrong name?
I'm trying to render my html page to pdf using django with these functions: def fetch_resources(uri, rel): if settings.STATIC_URL and uri.startswith(settings.STATIC_URL): path = os.path.join(STATIC_ROOT, uri.replace(settings.STATIC_URL, "")) elif settings.MEDIA_URL and uri.startswith(settings.MEDIA_URL): path = os.path.join(STATIC_ROOT, uri.replace(settings.MEDIA_URL, "")) else: path = os.path.join(settings.STATIC_ROOT, uri) return path.replace("\\", "/") def render_pdf(url_template, context={}): pdfmetrics.registerFont(TTFont("Calibri", "static/fonts/Calibri.ttf", "UTF-8")) template = get_template(url_template) html = template.render(context) result = BytesIO() pdf = pisa.CreatePDF(html, result, link_callback=fetch_resources) if not pdf.err: return HttpResponse(result.getvalue(), content_type="application/pdf") return None This is the view: class RenderPDF(View) def get(self, request, *args, **kwargs): pdf = render_pdf("tmp.html") return HttpResponse(pdf, content_type="application/pdf") And this is the template: {% block extra_style %} <style type="text/css"> @font-face { font-family: Calibri; src: url("/static/fonts/Calibri.ttf"); } body { font-family: 'Calibri', sans-serif;} </style> {% endblock %} {% block content %} <body> <p>йоу</p> </body> {% endblock %} As you can see, I'm using Calibri font for cyrillic letters, however when I'm rendering the page I get the following error: TTFError at /download-pdf/ Can't open file "C:\Users\user\AppData\Local\Temp\tmp6o9yikqk.ttf" It seems like the interpreter is looking for the file in a wrong catalog, since my project is on D drive and my font path is in /static/fonts/Calibri.ttf settings.py STATIC_URL = "/static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, "staticfiles")] STATIC_ROOT = os.path.join(BASE_DIR, "static") -
Function to update last sensor value in Django
I have created an API for several environmental sensors using models. I am trying to create a function to receive the latest value from the Django database and retrieve it. This is my models.py file from django.db import models class SensorStation(models.Model): name = models.CharField(max_length=100, unique=True) location = models.CharField(max_length=100) def __str__(self): return self.name class Sensor(models.Model): sensor_type_choices = [ ("TEMP", "Temperature"), ("HUMID", "Humidity"), ("LIGHT", "Light"), ] sensor_unit_choices = [ ("Celsius", "Cel"), ("Humidity", "hmd"), ("Light", "lgt") ] name = models.CharField(max_length=100) sensor_type = models.CharField(max_length=5, choices=sensor_type_choices) sensor_unit = models.CharField(max_length=15, choices=sensor_unit_choices) station = models.ForeignKey(SensorStation, on_delete=models.CASCADE) value = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) timestamp = models.DateTimeField(null=True, blank=True) def __str__(self): return f"{self.name} ({self.get_sensor_type_display()})" def update_latest_value(self, val): latest_value = Sensor.objects.filter(value=val).latest("timestamp") if latest_value: self.value = latest_value.value self.timestamp = latest_value.timestamp self.save() else: self.value = 21.21 #for debugging purposes self.timestamp = None self.save() ... This function doesn't work, as the API returns this json: Also, this is my views.py file: from rest_framework import generics from .models import Sensor, SensorStation, SensorValue from .serializers import SensorSerializer, SensorStationSerializer, SensorValueSerializer from rest_framework.response import Response class SensorList(generics.ListCreateAPIView): queryset = Sensor.objects.all() serializer_class = SensorSerializer class SensorDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Sensor.objects.all() serializer_class = SensorSerializer class SensorTypeList(generics.ListAPIView): serializer_class = SensorSerializer def get_queryset(self): sensor_type = self.kwargs["sensor_type"] return Sensor.objects.filter(sensor_type=sensor_type) class SensorStationList(generics.ListCreateAPIView): queryset = SensorStation.objects.all() … -
Django: how to exclude page being deleted from the object list in queryset
I'm developing a Django website which has a section (an app) "About" with 3-level hierarchy of pages. This section has corresponding 3-level popup menu. In order to minimize queries to the database, I want this menu to be static (html file), rewritten only in cases if the menu changes (i. e. on page create, update or delete). This operation is done by the function get_success_url: def get_success_url(self): object_list = Page.objects.filter(parent=None).order_by("order").prefetch_related("subpages__subpages") text = render_to_string('menu_pages_template.html', {'object_list': object_list}) f = open( 'roo/templates/includes/menu_about.html', 'w+') f.write(text) f.close() ... On page creation or update everything works well. However, on page deletion, its menu item is not deleted, because the page object still exists in the queryset. I tried to exclude current object from the queryset: def get_success_url(self): object_list = Page.objects.exclude(slug=self.kwargs['page']) object_list = object_list.filter(parent=None).order_by("order").prefetch_related("subpages__subpages") But this approach works only with first-level pages. The "child" and "grandchild" pages still remain in the queryset. Possibly they could be also excluded by some filtering, but I suspect that there should be more simple and "pythonic" way to exclude deleted page from the queryset. So, please help me! -
How can I add a Date Picker widget to a Date field in wagtailforms?
I'm using wagtailforms and have followed the example code at https://docs.wagtail.org/en/latest/reference/contrib/forms/ This allows the content editor to define their own fields for a contact form, without the need for me to hardcode the form. One field the editor will add is a Date field. When this is rendered in the template, there is no Date Picker widget associated with it. I'm rendering the form as below - <form action="{% pageurl page %}" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> How can I add a Date Picker here? It's not 100% a Date field will be used, so I don't know the label of the field in advance, and there maybe multiple Date fields too. My models.py has - class FormField(AbstractFormField): page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields') class FormPage(AbstractEmailForm): intro = RichTextField(blank=True) thank_you_text = RichTextField(blank=True) content_panels = AbstractEmailForm.content_panels + [ FormSubmissionsPanel(), FieldPanel('intro'), InlinePanel('form_fields', label="Form fields"), FieldPanel('thank_you_text'), MultiFieldPanel([ FieldRowPanel([ FieldPanel('from_address', classname="col6"), FieldPanel('to_address', classname="col6"), ]), FieldPanel('subject'), ], "Email"), ] -
Email adress on Django API returns 404
I have an endpoint created like this: class OTPSViewSet(viewsets.ViewSet, mixins.RetrieveModelMixin, mixins.CreateModelMixin): """ A simple ViewSet for listing or retrieving users. """ throttle_classes = [OncePerDayUserThrottle] authentication_classes = [] permission_classes = [] def retrieve(self, request, pk=None): response = self.get_otp(pk) return response def create(self, request): serializer = OtpsForms(data=request.data) if serializer.is_valid(): response = self.verify_otp(request) return response else: return response_error(serializer.errors) def get_otp(self, username): """Send OTP by email Args: username (string): username """ username = username.strip().lower() user = _get_all_by_username(username) ... What happens is that when I make a call to the endpoint with a "username" such as "javi", the call "GET /api/otps/javi/ HTTP/1.1" 200" returns a 200, and when the username is an email like "javi@gmail.com" the call is "GET /api/otps/javi@gmail.com/ HTTP/1.1" 404" returning a 404 not found status. I think it has to do with having an at (@) or a dot (.) inside the url but I don't know how to fix it. Thanks in advance! -
Argument of type "dict[str, str]" cannot be assigned to parameter "data" of type "Type[empty]"
I have a very small serializer for the initial user registration: class UserRegistrationSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ "email", "password", ] def validate_password(self, value): try: validate_password(password=value) except ValidationError as e: raise serializers.ValidationError(list(e.messages)) return value Now I am writing tests for this serializer. These are working fine, but my IDE (vscode) shows me an typing error: class UserRegistrationSerializerTestCase(TestCase): def test_invalid_email(self): request_data = {"email": "test@test", "password": "testpwsecure"} serializer = UserRegistrationSerializer(data=request_data) self.assertFalse(serializer.is_valid()) The error refers to my input to the UserRegistrationSerializer, saying that Argument of type "dict[str, str]" cannot be assigned to parameter "data" of type "Type[empty]" I am not sure what Type[empty] actually means and how I can satisfy the static code analysis here ... the test is working fine and as expected, I would just like to understand and learn what the IDE is complaining about. -
How to update field after creation wih Signals
I'm using signals and i want to update one of fields after creation but every time i've got an error maximum recursion depth exceeded How can i solve that? signals.py @receiver(post_save, sender=CompanyUserPhysicalCard) def create_company_card(sender, instance, created, **kwargs): try: company_card_model = CompanyUserPhysicalCard.objects.get( card__user__individual_user=instance.card.user.individual_user) letters = '01234567890' result_str = ''.join(random.choice(letters) for i in range(9)) card_company_name = company_card_model.company.company_name card_company_abbreviation = company_card_model.company.company_abbreviation if len(card_company_name) < 15: result_str += '-' + str(card_company_name) else: result_str += '-' + str(card_company_abbreviation) company_card_model.custom_id = result_str instance.custom_id = company_card_model.custom_id except CompanyUserPhysicalCard.DoesNotExist as e: print(e) @receiver(post_save, sender=CompanyUserPhysicalCard) def save_user_profile(sender, instance, **kwargs): instance.save() -
django refreshed token after patch doesn't contain latest data
I'm executing a patch method, after which I want to refresh the token to update my userdata through the app (I don't know if this is the right way but refresh tokens are linked to my user in the app so it's convenient). The problem is, after having executed a patch method (successfully, because I see that data changed in my db), when I try to refresh the token it simply returns the old data. I added a custom TokenObtainPairSerializer class to have my data in the token but is there something else I need to do? Please tell me if there is a specific piece of code I should add to this post.