Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do i get the value from returned JSON object?
I am trying to implement like function on my site, so when user likes the post,like button changes to unlike button and vice versa. So i wrote a function in my django app side that returns True/False if post is liked/unliked. I get this response: {like: true} How do i get just this true value without anything else? -
Django regroup a regrouped data not working
I have below D table: type month user First 2023-05-01 1 second 2023-04-01 1 second 2023-05-01 1 First 2023-03-01 1 second 2023-02-01 1 First 2023-02-01 1 second 2023-02-01 1 In view: datadump = db.objects.filter(user=request.user) In template I am trying to achive something like this: **type** User - list of all months I have tried below code and I am able to group by type but not able to group by user again. {% regroup datadump by type as ret_type %} {% for type in ret_type %} <h1>{{ type.grouper }}</h1> {% regroup type.list by user as userlist %} {% for user in userlist %} <h4>{{user.grouper}}</h4> {% endfor %} {% endfor %} If I try above code I am getting user list multiple time, instead of grouping user. -
JavaScript Separator
I want to receive data from DJANGO and change HTML VALUE according to the data with JAVASCRIPT. BUT JAVASCRIPT not work. I'll send you what I've made up. I don't know what's wrong ##django view def message(msg): time.sleep(1) return f'{msg} ' def get_data(): status_code =['AB','CD','EF','GH','IJ'] for i in status_code: time.sleep(0.5) print(i) yield message(i) def test_stream(request): stream = get_data() # stream = db_restore_test() response = StreamingHttpResponse(stream, status=200, content_type='text/event-stream') response['Cache-Control'] = 'no-cache' return response def jobs(request): return render(request, 'jobs/index.html') #html (javascript) const arr = oEvent.target.responseText.split(' ') log(arr.reverse()[1]) const data = arr.reverse()[1] if (data == 'AB'){ document.getElementById('step1_status').innerHTML = '시작'; log('1') } else if (data == 'CD'){ document.getElementById('step1_status').innerHTML = '완료'; document.getElementById('step2_status').innerHTML = '시작'; log('2') } else if (data == 'EF'){ document.getElementById('step2_status').innerHTML = '완료'; document.getElementById('step3_status').innerHTML = '시작'; log('3') } else if (data == 'GH'){ document.getElementById('step3_status').innerHTML = '완료'; document.getElementById('step4_status').innerHTML = '시작'; log('4') } else if (data == 'IJ'){ document.getElementById('step4_status').innerHTML = '완료'; log('5') } } WEB Console I dont understand why result only '2'. -
Date fixed but variable month and year in python
I have below code: from datetime import date, datetime, timedelta from dateutil.relativedelta import relativedelta c0 = date.today() c1 = c0 - relativedelta(months=1) c2 = c0 - relativedelta(months=2) c3 = c0 - relativedelta(months=3) c4 = c0 - relativedelta(months=4) c5 = c0 - relativedelta(months=5) Now date today is 2023/06/14, however what I am trying to achieve is that no matter what date it is, I should get 16 as day, and actual current month and year. I have tried adding int to current date but since current date is not fixed, I am not able to get 16 as day. Please suggest a way where I can convert below to a date: day = 16 month = current month year = current year date = year/month/day -
return '<SimpleProducer batch=%s>' % self.async while using KafkaProducer
Here's run.py from app import create_app if __name__ == '__main__': app = create_app() app.run(host='0.0.0.0', port=8000, debug=True) Here's the /app/app/__init__.py from flask import Flask from flask_cors import CORS from app.config import Config from threading import Thread from app.consumer.kafka_consumer import consume_messages def create_app(): app = Flask(__name__) app.config.from_object(Config) app.config['SQLALCHEMY_DATABASE_URI'] = Config.MYSQL_DATABASE_URI app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False CORS(app) consumer_thread = Thread(target=consume_messages) consumer_thread.start() # Register blueprints from app.controller.segmentation_controller import segmentation_bp app.register_blueprint(segmentation_bp) return app Here's the /app/app/consumer/kafka_consumer.py from kafka import KafkaConsumer from app.config import Config from app.service.segmentation_service import SegmentationService def consume_messages(): segmentation_service = SegmentationService() consumer = KafkaConsumer( Config.KAFKA_TOPIC, bootstrap_servers=['localhost:9092'], auto_offset_reset='latest', # Start reading from the latest available offset enable_auto_commit=True, group_id='my-group', value_deserializer=lambda x: x.decode('utf-8'), ) for message in consumer: segmentation_service.process_messages(message) Here's the error message 2023-06-14 11:44:43 Traceback (most recent call last): 2023-06-14 11:44:43 File "run.py", line 1, in <module> 2023-06-14 11:44:43 from app import create_app 2023-06-14 11:44:43 File "/app/app/__init__.py", line 5, in <module> 2023-06-14 11:44:43 from app.consumer.kafka_consumer import consume_messages 2023-06-14 11:44:43 File "/app/app/consumer/kafka_consumer.py", line 1, in <module> 2023-06-14 11:44:43 from kafka import KafkaConsumer 2023-06-14 11:44:43 File "/usr/local/lib/python3.8/site-packages/kafka/__init__.py", line 23, in <module> 2023-06-14 11:44:43 from kafka.producer import KafkaProducer 2023-06-14 11:44:43 File "/usr/local/lib/python3.8/site-packages/kafka/producer/__init__.py", line 4, in <module> 2023-06-14 11:44:43 from .simple import SimpleProducer 2023-06-14 11:44:43 File "/usr/local/lib/python3.8/site-packages/kafka/producer/simple.py", line 54 2023-06-14 11:44:43 … -
django terminology for the two project files
In django, what is the terminology for the two project files created with the same name? Chat gpt says it is Project Directory \ Project Configuration Files. Is this correct? tried googling, but nothing. Thank you in advance! -
Django combine 2 querysets without changing the original order
def get_queryset(self): normal_posts = Post.objects.filter(field1=‘value1’).order_by('another_field_1’) featured_posts = Post.objects.filter(field2=‘value2’).order_by(‘another_field_2') all_posts = (normal_posts | featured_posts) #does not preserve the order return all_posts I'm using DjangoFilterBackend and along with filterset_class for paginated query results. Hence not able to use below. normal_ads.union(featured_ads) #django.db.utils.NotSupportedError: Calling QuerySet.filter() after union() is not supported. I tried using from itertools import chain also, however its not much helpful as its returning a list and not query set. Please suggest. -
AWS Route 53 Routing for Django Application - ALLOWED HOSTS
I am deploying a django application to AWS elastic beanstalk. I’m having troubles getting a Route 53 hosted domain record to route traffic appropriately, and I think it’s a problem on the application side and not AWS. I have a ticket open with AWS, and in their first response their thinking was that it was probably application problem, but they are still investigating. Was hoping someone here could help me on the Django side. I have a hosted zone, “example.com” in Route 53. Within the hosted zone I have 4 records, 2 are the NS and SOA records that come with each hosted zone by default. And I created 2 additional “A” records, that are alias’ to my elastic beanstalk environment. These two records are named “example.com” and “www.example.com”. In my django application I have added my elastic beanstalk CNAME, “example.com”, and “www.example.com” to the ALLOWED_HOSTS, as follows: '''ALLOWED_HOSTS = [‘env-example.eba-emvtkupp.us-west-1.elasticbeanstalk.com’, ‘example.com’, ‘www.example.com’, ‘https://example.com’, ‘https://www.example.com’,]''' Note - i added the https versions of the urls as well…im not sure if this is actually necessary. When i deploy the application to elastic beanstalk everything is normal. I try to access example.com in a browser and it works. I try to access … -
Django - How to filter out row that are same in some fields and differ in others?
i have a model in django like this class Article(models.Model): column_one = ForeignKey() column_two = ForeignKey() column_three = ForeignKey(null=True) class Meta: constraints = [ models.UniqueConstraint( fields=["column_one", "column_two"], condition=Q(column_three=None), name='article_unique_if_no_column_three'), models.UniqueConstraint( fields=["column_one", "column_two", "column_three"], condition=~Q(column_three=None), name='article_unique_if_column_three'), ] How can i filter so that i get all the articles but if there are two that have the same data except the column_three it chose the one with column_three not null and exclude the one with column_three=None thanks in advance -
Running crond as root user when server is going to be running as non-root django container
I'm currently dockerizing my app and am trying to get cron jobs working. For context I am creating my job using the python-crontab module. I would like to run the container as a non-root user (as I believe is best practice) however I am struggling to get the cron task to run. This is the relevant part of my current dockerfile: ######### # FINAL # ######### #Pull base image FROM python:3.9.15-alpine3.16 #Create directory for app user RUN mkdir -p /home/user #create app user RUN addgroup -S app && adduser -S useradmin -G app #create directories ENV HOME=/home/user ENV APP_HOME=/home/user/userapp RUN mkdir $APP_HOME RUN mkdir $APP_HOME/static RUN mkdir $APP_HOME/media WORKDIR $APP_HOME #install dependencies RUN apk update && apk add libpq COPY --from=builder /user/wheels /wheels RUN pip install --no-cache /wheels/* # copy entrypoint.sh COPY entrypoint.sh $APP_HOME # copy project COPY . $APP_HOME RUN python /$APP_HOME/user/cron.py RUN crontab -l > /home/user/crontab.txt RUN crond -f -L /dev/stdout # chown all the files to the app user RUN chown -R user:app $APP_HOME # change to app user USER useradmin # run entrypoint.sh ENTRYPOINT ["/home/user/userapp/entrypoint.sh"] The line RUN crond -f -L /dev/stdout is the only way so far I have found to get the cron jobs … -
How do migration operations (eg. AddField) detect if you're applying or reverting a migration?
A good example is django.db.migrations.AddField. Let's say I've created a simple migration such as: from django.db import migrations, models class Migration(migrations.Migration): dependencies = [] operations = [ migrations.AddField( model_name="foo", name="bar", field=models.TextField(blank=True, null=True), ), ] Running the migration would result in the bar field being added, and reverting to a previous migration would result in the bar field being removed. However when I look under the hood of the AddField class, I don't see the logic for detecting the direction of the applied migration. class AddField(FieldOperation): field: Field[Any, Any] = ... preserve_default: bool = ... def __init__( self, model_name: str, name: str, field: Field[Any, Any], preserve_default: bool = ..., ) -> None: ... I need to create a similar function for collected data that can apply/revert changes based on changes made to the model the data is based on. This function would be used inside migrations in a similar way to AddField, and needs to detect whether the user is applying or reverting a migration. -
Why do I get a different schema when I run generateschema on the command line compared to obtaining it via the api using Django SchemaGenerator?
I am using the Django Rest Framework SchemaGenerator to create a schema for my API. However, I get different results depending on whether I generate a static schema using python manage.py generateschema compared to when I request a dynamic schema through the API endpoint configured as urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), re_path(r'^auth/', include('api.djoser.urls')), re_path(r'^auth/', include('djoser.urls.authtoken')), path('schema/', get_schema_view( title="Morty", description="API to access Morty", version="1.0.0" ), name='morty-schema'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Using the static method I get a complete schema with all the API endpoints. The schema returned from the endpoint in the dynamic method has a number of endpoints missing. The set of endpoints given in the dynamic schema is /auth/users/activation/ /auth/users/resend_activation/ /auth/users/reset_password/ /auth/users/reset_username/ /auth/users/reset_username_confirm/ /auth/token/login/ which is missing the following endpoints that are present in the full static schema /auth/users/ /auth/users/me/ /auth/users/{id}/ /auth/users/reset_password_confirm/ /auth/users/reset_username_confirm/ /auth/users/set_password/ /auth/users/set_username/ /auth/token/logout/ I am using Djoser to get the endpoints and associated views. I thought, perhaps, that the dynamic schema was affected by authorization, but I tried logging in using the /login/ endpoint prior to requesting the schema and got the same results. I feel like I must be missing something obvious. -
Django - not displaying the images (as urls)
I'm following a ytb video, step by step and everything works fine except for the images. I uploaded the link adresses through django admin, but they are not displaying. models.py: from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) class Offer (models.Model): code = models.CharField(max_length=10) description = models.CharField(max_length=255) discount = models.FloatField() index.html: {% extends 'base.html' %} {% block content%} <h1>Products</h1> <div class="row"> {% for product in products %} <div class="col"> <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{ product.image_url}}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.price }} RON</p> <a href="#" class="btn btn-primary">Adauga in cosul tau</a> </div> </div> </div> {% endfor %} </div> {% endblock %} views.py: from django.http import HttpResponse from django.shortcuts import render from .models import Product def index(request): products = Product.objects.all() return render(request, 'index.html', {'products': products}) def new(request): return HttpResponse('Produse noi') The code is the same as in the video. I tried to ask chat gpt if there's something that doesn't seem right but he didn't find anything. I tried to change the name from "image_url" to anything else but didn't work, as expected. -
Where to set a custom middleware's path in "MIDDLEWARE" in "settings.py" in Django?
I created the middleware simple_middleware() in middleware/sample.py following the doc as shown below. *I'm learning Middleware: django-project |-core | └-settings.py |-middleware | |-__init__.py | └-sample.py # Here |-app1 └-app2 # "middleware/sample.py def simple_middleware(get_response): print("Only once the server starts") def middleware(request): print("Before a view is called") response = get_response(request) print("After a view is called") return response return middleware But, I don't know where to set the custom middleware's path in MIDDLEWARE in settings.py as shown below. The 1st, the last or anywhere in MIDDLEWARE?: # "core/settings.py" MIDDLEWARE = [ # "middleware.sample.simple_middleware" # The 1st? "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", # "middleware.sample.simple_middleware" # Anywhere? "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", # "middleware.sample.simple_middleware" # The last? ] Actually, I know that the doc says below in Activating middleware but I want to know exactly where to set it: The order in MIDDLEWARE matters because a middleware can depend on other middleware. So, where should I set the custom middleware's path in MIDDLEWARE in settings.py? -
how to specify response for specific request methods for API action in django
I have an API action in django which accepts GET and POST requests where each of them will have a distinct response schema. If a request is of method "GET" we will return a list, if it is "POST" we will return only the created entity... from drf_spectacular.utils import extend_schema class SessionsViewSet(viewsets.ModelViewSet): ... @extend_schema( parameters=[query_params["extra_query_param"]], responses={ "GET": serializers.ExampleSerializer(many=True), "POST": serializers.ExampleSerializer(many=False), }, ) @action( detail=True, url_path="example", methods=["GET", "POST"], filter_backends=[], ) def example(self, request, pk, *args, **kwargs): match request.method: case "GET": queryset = MyModel.objects.filter(session_pk_id=pk) page = self.paginate_queryset(queryset) serializer = get_serializer(page, many=True) return self.get_paginated_response(serializer.data) case "POST": serializer = get_serializer(data=request.data, many=False ) if serializer.is_valid(): serializer.save() return Response( serializer.data, status=status.HTTP_201_CREATED, ) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) case _: return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED) The problem is that now I am not sure how to define this rule so that the swagger auto-schema will detect and present as such. How can I explicitly state that a response schema or serializer belongs to a specific request method? -
Failing to understand django get_absolute_url
I have this model: class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=600) isbn = models.CharField('ISBN', max_length=13, unique=True) genre = models.ManyToManyField(Genre) language = models.ForeignKey( 'Language', on_delete=models.SET_NULL, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("book_detail", kwargs={"pk": self.pk}) And this view: class BookDetail(DetailView): model = Book It will connect me to the template as well called (book_detail.html). My question is, do I need to also specify in the app's urls.py the url path in this case? path('book/<int:pk>/',views.BookDetail.as_view(),name='book_detail') I thought that if I used get_absolute_url(self) I wouldn't need to do that but I am finding some resources where it says it is necessary. I find it confusing since to me it feels like duplicating the code. Thanks! -
Updating status of one field based on multiple conditions from other fields
I have a class 'Contract' in which I want to set a status based on the fulfillment of certain conditions. The status is used for making lists and table of contracts based on their status. For now, I'm thinking the best solution is to split the code into two parts: Conditions that need to be met before updating an object, and conditions for automatic updates. The first example would be where the user would change the status of a contract from 'PLANNED' to an active contract. In order to do this, the field 'award_date' would have to be filled in before the other possible fields 'signature_date', and 'start_date'. Possible statuses can be 'AWARDED_UNACTIVE' ('signature_date' with a empty or future 'start_date), 'UNSIGNED_ACTIVE' ('start_date' without 'signature_date'). Another example would be that one can only set the status to 'TERMINATED' if the the contract has an active status (planned or expired contracts can not be terminated). The second example would be if a contract has been active ('start_date' is before today) and the date passes 'end_date'. In these cases I would like 'status' to change to 'EXPIRED' without needing a manual update. How would I go about to make this? I'm still a … -
Function-Based Middleware vs Class-Based Middleware in Django
I read the doc, then I could understand that we can define a function-based middleware and a class-based middleware in Django as shown below but I could not understand the difference between them. *I'm learning Middleware: Function-Based Middleware: def simple_middleware(get_response): # One-time configuration and initialization. def middleware(request): # Code to be executed for each request before # the view (and later middleware) are called. response = get_response(request) # Code to be executed for each request/response after # the view is called. return response return middleware Class-Based Middleware: class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response My questions: What is the difference between a function-based middleware and a class-based middleware in Django? Which should I use basically? -
docker nginx django ALLOWED_HOSTS not allowing requests through
I am deploying an api that doesn't require database or gunicorn to be used. With following configurations I am setting up the api: nginx.conf upstream django { server web:8000; } server { listen 80; server_name localhost; location / { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } nginx Dockerfile # Base image for building the Django application FROM nginx:1.19.0-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d ALLOWED_HOSTS django settings.py ALLOWED_HOSTS = ['localhost', '127.0.0.1'] Dockerfile # Base image for building the Django application FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY requirements.txt /code/ RUN pip install --no-cache-dir -r requirements.txt COPY . /code/ EXPOSE 8000 EXPOSE 80 CMD python manage.py runserver 0.0.0.0:8000 --noreload docker-compose.yml version: '3' services: web: build: context: . dockerfile: Dockerfile volumes: - .:/code nginx: build: ./nginx ports: - 80:80 depends_on: - web The purpose is to create an api which will only be called by other client like a Python based client. I am testing this from my local machine but not working. Adding * wildcard works but is too risky. So, what changes should I make for following two cases: 1. To be able to call from my local python client. 2. To be … -
Django - The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance
I have run into a problem that I cannot figure out. First, my code: models.py from django.db import models import random def pass_gen(): password = '' def rand_uni(): return random.randint(33, 126) def rand(): return random.randint(8, 20) code = rand() for num in range(code): r_int = chr(rand_uni()) password += r_int return password # Create your models here. class User(models.Model): username = models.CharField(max_length=200) class Password(models.Model): url = models.CharField(max_length=800) password = models.CharField(default=pass_gen(), max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint(fields=['url', 'user'], name='unique_url_and_user_id') ] Serializers.py: from rest_framework import serializers from vault.models import User, Password class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class PasswordSerializer(serializers.ModelSerializer): url = serializers.CharField(max_length=800) class Meta: model = Password fields = ('url', 'password', "user") views.py: from django.shortcuts import render from django.http import HttpResponse, JsonResponse from rest_framework.parsers import JSONParser from vault.models import User, Password from django.views.decorators.csrf import csrf_exempt from vault.serializers import UserSerializer, PasswordSerializer # Create your views here. # GET list of all users @csrf_exempt def user_all(request): if request.method == 'GET': user = User.objects.all() serializer = UserSerializer(user, many=True) return JsonResponse(serializer.data, safe=False) elif request.method=='POST': data = JSONParser().parse(request) serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) #GET and DELETE unique users @csrf_exempt def user_detail(request, id): … -
Ansible URI module throws SSL error in spite of validate_certs set to false
I am trying to do a readiness check on a docker image deployed using Ansible. I am using Ansible module URI. In spite of validate_certs being set to false, I am receiving an SSL error when I try to get an html deployed on it. Verbose log: <my.ip.v4.address> (1, b'\r\n{"redirected": false, "url": "https://127.0.0.1/xxxx_xxxx/xxxx.html", "status": -1, "elapsed": 0, "changed": false, "failed": true, "msg": "Status code was -1 and not [200]: Request failed: <urlopen error EOF occurred in violation of protocol (_ssl.c:1131)>", "invocation": {"module_args": {"url": "https://127.0.0.1/xxxx_xxxx/xxxx.html", "validate_certs": false, "status_code": [200], "force": false, "http_agent": "ansible-httpget", "use_proxy": true, "force_basic_auth": false, "use_gssapi": false, "body_format": "raw", "method": "GET", "return_content": false, "follow_redirects": "safe", "timeout": 30, "headers": {}, "remote_src": false, "unredirected_headers": [], "unsafe_writes": false, "url_username": null, "url_password": null, "client_cert": null, "client_key": null, "dest": null, "body": null, "src": null, "creates": null, "removes": null, "unix_socket": null, "ca_path": null, "mode": null, "owner": null, "group": null, "seuser": null, "serole": null, "selevel": null, "setype": null, "attributes": null}}}\r\n', b'Shared connection to my.ip.v4.address closed.\r\n') <my.ip.v4.address> Failed to connect to the host via ssh: Shared connection to my.ip.v4.address closed. <my.ip.v4.address> ESTABLISH SSH CONNECTION FOR USER: ubuntu <my.ip.v4.address> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no -o 'IdentityFile="/home/jenkins/agent/workspace/XXXXXX/install/foo.pem"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o … -
Django user.is_superuser not returning true in template if statement
I'm trying to have information about an object show up if the user is a super user. Normally the information is hidden unless the object's public attribute is true. The object.public part works and {{user.is_superuser}} works as expected but {% if user.is_superuser %} does not. <h1>Player Techniques</h1> <h2>{{user.is_superuser}}</h2> {% for object in techniques %} {% if user.is_superuser or object.public%} {% include "unlimited/technique.html" %} {% endif %} {% endfor %} here are my settings 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", ], }, }, ] I have also tried request.user.is_superuser with the same results, correctly displaying True for superuser and False otherwise in the h2, but not passing the if. -
Running django app + psql in vscode debugger causing FATAL: sorry, too many clients already
I have django app with psql database that I run with docker on port 5432. When I run the app and celery worker using vscode debugger after a few requests I see this error psycopg2.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: sorry, too many clients already Can't reproduce same error when I run app in standard way by typing python3 main.py in CLI. I used sudo lsof -i:5432 and discovered that if I run app in standard way, processes are being constantly cleaned, but if I run it using VScode debugger, processes are getting stacked and list if getting bigger until I get FATAL. Since I can only reproduce this error using VSCode debuger I assume it is related to that. Are there any settings to make debuger kill processes on the fly? -
django Image field is not loading current value on edit form and user have to upload again the file
I have a django form that have 3 image fields that are required. What I found is that when I use an instance to create an update form, the image is not loaded un the html input field, so when I send the form to the view to save it into database, I get an invalid form error due to images are missing. I defined the imageField as FileField: class Meta: model = Edicion exclude = ['festival'] widgets = { 'logo': FileInput, 'banner': FileInput, 'poster': FileInput, 'fecha_apertura_inscripciones': DateInput(), 'fecha_cierre_inscripciones': DateInput(), 'fecha_inicio': DateInput(), 'fecha_final': DateInput(), 'fecha_notificacion': DateInput(), } If I define again these fields then it works fine, but i'm not being able to send this field from the view. Many thanks Edit: Form Code: Form.py class createNewEdicion(forms.ModelForm): required_css_class = 'required-field' class Meta: model = Edicion exclude = ['festival'] widgets = { 'logo': FileInput, 'banner': FileInput, 'poster': FileInput, 'fecha_apertura_inscripciones': DateInput(), 'fecha_cierre_inscripciones': DateInput(), 'fecha_inicio': DateInput(), 'fecha_final': DateInput(), 'fecha_notificacion': DateInput(), } help_texts = { 'Nombre': ('Some useful help text.'), } error_messages = { 'Nombre': { 'max_length': ("This writer's name is too long."), }, } View.py if request.method == 'POST': form_festival = createNewFestival(request.POST, request.FILES) form_edicion = createNewEdicion(request.POST, request.FILES) # check whether it's valid: if … -
Unable to use `CheckboxSelectMultiple` for choices in wagtails `FieldPanel`: Form field validation raises an error
In a wagtail settings model I have a CharField-based choice field and want that to behave as a multi select in Wagtails FieldPanel. The choices are rendered correctly as multiple checkboxes, but on submit the form validation will raise an error: Select a valid choice. ['OPT1'] is not one of the available choices. So how do I use text-based choices as a multi select in Wagtails FieldPanel? Do I have to override the form field type to a forms.fields.MultipleChoiceField somehow? Setting the widget attribute to Select - instead of CheckboxSelectMultiple - the correctly rendered and populated select dropdown widget works as expected. My current implementation looks (roughly) like this: # models.py @register_setting(icon='cog') class MySettings(BaseGenericSetting): class MyChoices(models.TextChoices): OPT_1 = "OPT1" OPT_2 = "OPT2" choicefield = models.CharField( max_length=4, blank=True, choices=MyChoices.choices, ) panels = [ FieldPanel( 'choicefield', widget=forms.CheckboxSelectMultiple, ), ] I did not find any hints in the Customising generated forms docs.