Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CSRF token not saving to browser cookies in Production environment, but working in Development environment
We have created a Django application to create a Shopify Application. We are having issues with out production environment we AJAX calls to the Django application are failing because the CSRF token is not being saved to cookies and therefore nothing gets parsed in the AJAX call headers. We have followed the Django documentation and added {% csrf_token %} in the <head> tag of our base.html file which all other html files reference. Because this is a Shopify App, this app is embedded into a iFrame in Shopify but I am not sure this is the culprit as its the same in our development environment. There does seem to be cookies in the browser from our domain, just not the csrf token: We can't find a solution to why this is happening. We have had to mark our functions dispatch with @csrf_exempt which we don't want to have to do moving forward. For example: @csrf_exempt def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) -
In production, Django doesn't change language. I use Docker. But flags and admin panel language changes
Project works good in development but doesn't in production. My Dockerfile is like that FROM python:3.11.4 ENV PYTHONUNBUFFERED 1 ENV DJANGO_SETTINGS_MODULE=mysite.settings WORKDIR /app COPY . /app RUN pip install -r requirements.txt RUN apt-get update && \ apt-get install -y gettext RUN apt-get install -y locales locales-all ENV LC_ALL en_US.UTF-8 ENV LANG en_US.UTF-8 ENV LANGUAGE en_US.UTF-8 RUN sed -i 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/g' /etc/locale.gen RUN locale-gen RUN LANG=en_US.UTF-8 python manage.py collectstatic --noinput EXPOSE 8080 CMD ["gunicorn", "--config", "gunicorn_config.py", "mysite.wsgi:application"] My settings.py LANGUAGES = [ ('az', gettext_noop('Azerbaijani')), ('en', gettext_noop('English')), ('ru', gettext_noop('Russian')), ] LANGUAGE_CODE = 'az' TIME_ZONE = 'Asia/Baku' USE_I18N = True When i try to makemessages, this occures UnicodeDecodeError: skipped file requirements.txt in . (reason: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte) processing locale en_US.UTF-8 processing locale en -
Django - CSRF verification failed in Cloud Run
I am following this tutorial from Google codelabs. When trying to login to the admin panel, I am getting a CSRF verification failed. The tutorial is about deploying a fresh empty django project to Cloud Run. There's already a provided settings.py and I tried replacing it with this block to no avail: # SECURITY WARNING: It's recommended that you use this when # running in production. The URL will be known once you first deploy # to Cloud Run. This code takes the URL and converts it to both these settings formats. CLOUDRUN_SERVICE_URL = env("CLOUDRUN_SERVICE_URL", default=None) if CLOUDRUN_SERVICE_URL: ALLOWED_HOSTS = [urlparse(CLOUDRUN_SERVICE_URL).netloc] CSRF_TRUSTED_ORIGINS = ['https://django-cloudrun-yd43yjf7ya-uc.a.run.app'] SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") else: ALLOWED_HOSTS = ["*"] I've also tried hardcoding the CLOUDRUN_SERVICE_URL to the url provided on deployment, https://django-cloudrun-yd43yjf7ya-uc.a.run.app but it didn't work. With and without the slash at the end. Also did a sanity check by writing a simple hello world view to check if my changes are really getting through. -
django is not showing image in the browser and no error is shown in the inspect element
enter image description here [2]2 the complete images of the my first practice project is given here no erroe is shown in the browser. what to do? -
why django not able to pic or get uploaded images from database?
this is my index.html code {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Bank{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'money/styles.css' %}" rel="stylesheet"> </head> <body id="bg" style="background-image: url('{% static "money/bg.jpg"%}')"; style="background-image: url('{% static "money/bg.jpg"%}')";> <div class="indexdiv"> <h1 class="indextitle">Gautam Bank</h1> <div class="indexsign"> {% if user.is_authenticated %} Signed in as <strong>{{ user.username }}</strong>. {% else %} Not signed in. {% endif %} </div> <ul class="nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'balance' %}">Balance</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'send' %}">Send Money</a> </li> <li class="nav-item"> <a class="nav-link history-link" href="{% url 'history' %}">Transaction History</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'loan' %}">Apply for Loan</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Logout</a> </li> </ul> <hr> </div> <div class="indeximg"> {% if user_profile and user_profile.image %} <img height="138" width="152" src="{{ user_profile.image.url }}" alt="User Profile Image"> {% else %} <img height="138" width="152" src="{% static 'money/pic.jpg' %}" alt="Default Image"> {% endif %} </div> {% block body %} {% endblock %} </body> </html> ****this is my views.py code **** from django.shortcuts import render from django.contrib.auth import authenticate, login, logout from .models import User,Transaction,BankAccount, UserProfile from django.urls import reverse from django.db import IntegrityError from django.core.exceptions import ValidationError from … -
python manage.py collectstatic on Aws Elasticbeanstalk ends with error: TypeError: expected string or bytes-like object, got 'NoneType'
I try to setup Django website on AWS EB. I have running environment and S3 Bucket. I created superuser for my project and migrated it to postgresql database. The problem is I cannot run collectstatic. This is error message I get: Traceback (most recent call last): File "/var/app/current/manage.py", line 22, in <module> main() File "/var/app/current/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() ^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 338, in copy_file if not self.delete_file(path, prefixed_path, source_storage): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 248, in delete_file if self.storage.exists(prefixed_path): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/storages/backends/s3.py", line 514, in exists self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name) File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/botocore/client.py", line 553, in _api_call return self._make_api_call(operation_name, kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/botocore/client.py", line 946, in _make_api_call api_params = self._emit_api_params( ^^^^^^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/botocore/client.py", line 1072, in _emit_api_params self.meta.events.emit( File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/botocore/hooks.py", line 412, in emit return self._emitter.emit(aliased_event_name, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/botocore/hooks.py", line 256, in emit return self._emit(event_name, kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/botocore/hooks.py", line 239, in _emit response = handler(**kwargs) ^^^^^^^^^^^^^^^^^ File "/var/app/venv/staging-LQM1lest/lib64/python3.11/site-packages/botocore/handlers.py", … -
why the django custom middleware not able to catch the exception?
I have written a custom django middleware to do retries and catch exception if there is any connection related issues between two servers. Below is the code snippet. from requests.adapters import Retry, RetryError, HTTPAdapter, MaxRetryError, ConnectTimeoutError, ProtocolError, ResponseError from requests.sessions import Session from django.http import HttpResponseServerError class RetryCal: def __init__(self, get_response): self.get_response = get_response @staticmethod def process_request(request): try: session = Session() retries = Retry(total=5, backoff_factor=2, status_forcelist=[500, 502, 503, 504]) session.mount('https://', HTTPAdapter(max_retries=retries)) request.retry_session = session except Exception as e: raise e def __call__(self, request): RetryCal.process_request(request) try: response = self.get_response(request) return response except (ProtocolError, OSError) as err: raise ConnectionError(err, request) except MaxRetryError as e: if isinstance(e.reson, ConnectTimeoutError): return HttpResponseServerError("Connection timeout error...") if isinstance(e.reson, ResponseError): raise RetryError(e, request=request) raise ConnectionError(e, request) Below is the placement of the custom middleware 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # custom retry middleware. 'integ.api_retry_custom_middleware.RetryCal', belo this custom middleware I do have other default one's as well. The problem is I am not sure if this is working. I have a access token, In that I added some garbage characters and tried to hit my endpoints. I did see an exception as seen below Internal Server Error: /api/acct/ [24/Jan/2024 14:23:39] "GET /api/acct/ HTTP/1.1" 500 5348 But I can see this error even … -
How to use Django's GeneratedField to keep count of related objects?
Let's say I have the following models: class Shop(models.Model): ... @property def products_count(self): return Product.objects.filter(shop=self).count() class Product(models.Model): shop = models.ForeignKey(Shop, on_delete=models.CASCADE) ... The products_count property is being used to get the number of products in a shop. With the release of Django 5 and generated fields, is there a way to use this to store the count instead? Or am I misunderstanding the use of generated fields? -
Yeild usnig in async function in python Django
In my Django channels (websocket) i want to return data of for loop every time it gets a values using yield. if text_data: received_message = json.loads(text_data) OPEN BOX if received_message.get('open_box', False): rounds = await self.get_boxes_from_database(received_message) for r in rounds: response_data = await self.open_box_operation(received_message, r) data = self.send_group_notification({'type': 'OPEN-BOX', 'data': response_data}) yield data but i am getting error TypeError: object async_generator can't be used in 'await' expression async def receive(self, text_data): -
Celery crash with redis.exceptions.ResponseError: UNBLOCKED
I am using Celery with Django and Redis for everyday tasks. It works actually, but sometimes celery crashes with redis.exceptions.ResponseError, which i can't allow. I saw solution with configuring redis authentication, but it didn't work for me (or i did something wrong). celery auth log [2024-01-24 08:49:17,548: INFO/MainProcess] Connected to redis://default:**@redis:6379/0 error [2024-01-24 08:51:10,365: CRITICAL/MainProcess] Unrecoverable error: ResponseError('UNBLOCKED force unblock from blocking operation, instance state changed (master -> replica?)') Traceback (most recent call last): File "/usr/local/lib/python3.12/site-packages/celery/worker/worker.py", line 202, in start self.blueprint.start(self) File "/usr/local/lib/python3.12/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/usr/local/lib/python3.12/site-packages/celery/bootsteps.py", line 365, in start return self.obj.start() ^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/celery/worker/consumer/consumer.py", line 340, in start blueprint.start(self) File "/usr/local/lib/python3.12/site-packages/celery/bootsteps.py", line 116, in start step.start(parent) File "/usr/local/lib/python3.12/site-packages/celery/worker/consumer/consumer.py", line 742, in start c.loop(*c.loop_args()) File "/usr/local/lib/python3.12/site-packages/celery/worker/loops.py", line 97, in asynloop next(loop) File "/usr/local/lib/python3.12/site-packages/kombu/asynchronous/hub.py", line 373, in create_loop cb(*cbargs) File "/usr/local/lib/python3.12/site-packages/kombu/transport/redis.py", line 1344, in on_readable self.cycle.on_readable(fileno) File "/usr/local/lib/python3.12/site-packages/kombu/transport/redis.py", line 569, in on_readable chan.handlers[type]() File "/usr/local/lib/python3.12/site-packages/kombu/transport/redis.py", line 962, in _brpop_read dest__item = self.client.parse_response(self.client.connection, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/redis/client.py", line 553, in parse_response response = connection.read_response() ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/redis/connection.py", line 524, in read_response raise response redis.exceptions.ResponseError: UNBLOCKED force unblock from blocking operation, instance state changed (master -> replica?) docker-compose services: redis: image: redis:latest container_name: redis restart: on-failure volumes: - ./redis.conf:/usr/local/etc/redis/redis.conf ports: … -
Idea about full stack e-commerce applications
I want to develop e- commerce web application using 3 database 1) mongodb for store user's information 2) my SQL all products, category,price, product title I want store in my SQL database 3) cloudinary for image store I want application like Amazon My question is which technology I can use 1)react+ django 2) react + express 3)next.js Please give detail idea about this project For my e-commerce applications can I use inbuilt admin or can I develop my own admin.. -
Dango: list index out of range after, after 10 loops even though there is more left in the list
Suppose to take entry from a form entry for a list of cards. Then split each entry into a list after a new line. No matter what is in the form text area box, it reaches out of range after 9 entries. Have tried multiple different card examples, no matter what is there will always crash after 9 entries. def new_deck(request): form = mtgForm() current_user = request.user add_deck = Decks(deck_name=request.POST['Deck_Name'], user_id=current_user.id) add_deck.save() decks_id = add_deck.deck_id if request.method == "POST": current_user = request.user cards_from = request.POST['cards'] cards_from_form = cards_from.split("\r\n") cards_from_form[:] = [x for x in cards_from_form if x] for i, dataa in enumerate(cards_from_form): amount_of_cards = ''.join(x for x in dataa if x.isdigit()) pattern = r'[0-9]' ccards_name = re.sub(pattern, '', dataa).lstrip() ccards = Card.where(name=f'"{ccards_name}"').all() #ccard_id = ccards[0:1].number ccard_name = ccards[0].name ccard_type = ccards[0].type ccard_cost = ccards[0].mana_cost ccard_toughness = ccards[0].toughness ccard_power = ccards[0].power ccard_rarity = ccards[0].rarity ccard_set = ccards[0].set ccard_color_idenity = ccards[0].color_identity add_cards = cards(card_name=ccard_name, card_type=ccard_type, card_cost=ccard_cost, card_toughness=ccard_toughness,card_power=ccard_power,card_rarity=ccard_rarity,card_set=ccard_set,card_color_idenity=ccard_color_idenity,deck_id=decks_id) add_cards.save() return HttpResponse("Cards added to deck") else: return render(request, "form.html", {"form": form}) -
Limit editing access to a model in the Django admin panel
this is my model class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(_('نام'), max_length=255) last_name = models.CharField(_('نام خانوادگی'),max_length=255) image = models.ImageField(_('تصویر'),null=True, blank=True) description = models.TextField(_('توضیحات'),) created_date = jmodels.jDateTimeField(_('تاریخ ایجاد'), auto_now_add=True) updated_date = jmodels.jDateTimeField(_('تاریخ آخرین به روز رسانی'),auto_now=True) USERNAME_FIELD = 'user' REQUIRED_FIELDS = [] def __str__(self) -> str: return self.user.email class Meta: ordering = ['-updated_date'] verbose_name = 'پروفایل' verbose_name_plural = 'پروفایل ها' @receiver(post_save, sender=User) def save_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) In the admin panel, I want only the profile owner and super user to have access to edit that profile I don't know where and what changes I should make -
How to allow custom/catch-all domains in nginx?
I want each user to be able to point their own domain names at my Django server. My current nginx config file in /etc/nginx/sites-available/ looks like this: upstream app_server { server unix:/home/zylvie/run/gunicorn.sock fail_timeout=0; } server { if ($host = www.zylvie.com) { return 301 https://$host$request_uri; } # managed by Certbot server_name www.zylvie.com; return 301 $scheme://zylvie.com$request_uri; listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/zylvie.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/zylvie.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { server_name zylvie.com; keepalive_timeout 60; client_max_body_size 4G; access_log /home/zylvie/logs/nginx-access.log; error_log /home/zylvie/logs/nginx-error.log; location /robots.txt { alias /home/zylvie/staticfiles/robots.txt; } location /favicon.ico { alias /home/zylvie/staticfiles/favicon.ico; } location /static/ { alias /home/zylvie/staticfiles/; } location /media/ { allow all; auth_basic off; alias /home/zylvie/zylvie/media/; } # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_connect_timeout 600; proxy_send_timeout 600; proxy_read_timeout 600; send_timeout 600; fastcgi_read_timeout 60; proxy_pass http://app_server; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/zylvie.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/zylvie.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } … -
How to increase custom count value without forloop.counter in django template?
Here is my code to increment count value. i have set variable count and assign default is 1. <div class="main-content"> {% with count=1 %} {% for element in responses %} <!-- TYPE: section --> {% if element.type == "section"%} <div class="wrapper"> <div class="input-wrapper"> <div class="question"> <h3>{{element.label}}</h3> </div> <div class="description"> {{element.instruction}} </div> </div> <hr class="grey-hr" /> </div> <!-- type: time --> {% elif element.type == "time"%} <div class="wrapper"> <div class="input-wrapper"> <div class="question"> <span class="number">{{count}}. </span> <span>{{element.label}}</span> {% if element.isRequired %} <span style="color: #f44336">*</span> {% endif %} </div> <div class="answer"> <p>{{element.answer}}</p> </div> </div> <hr class="grey-hr" /> </div> {% endif %} {% with count=count|add:1 %} {% endwith %} {% endfor %} {% endwith %} </div> I have to increment count value without forloop.counter.It should not be increment please suggest what i'm missing. -
deploy django to elastic beanstalk gert degraded
This is the firs time i trying work deploy python dijango with elasticbeanstalk , it show me successfull but it get degraded and show me this error Connect() failed (111: Connection refused) while connecting to upstream now how to config it to reslove this promblem now how to config it to reslove this promblem -
how to integrate an MTN Momoapi for money collection and disbursement into your django application?
i want itegrate mtn momoapi into my django project so that i can be able to capture the details of apyments in the database i already managed to signup to mtn sandbox, and writen codes but not the one integration of mtn into the system -
Django app deployment on heroku wsgi module not found
I'm trying to deploy my app and gunicorn works locally but on heroku it doesn't work and it returns a module not found error. Locally, I have noticed that when I run gunicorn locally it works when I'm on the same file as manage.py but when I cd into the higher level file that has the procfile and requirements.txt, it states that "No module named 'SC_BASIS.wsgi'" and the app crashes. My current file directory looks like this: SCBASIS_Website -> {Procfile SC_BASIS README.md requirements.txt} and in SC_BASIS there is {SCBASIS SC_BASIS db.sqlite3 files manage.py} or in words: SCBASIS_Website Procfile SC_BASIS SCBASIS SC_BASIS db.sqlite3 files manage.py README.md requirements.txt My procfile has the following process: web gunicorn SC_BASIS.wsgi When I run gunicorn locally it works in the file where manage.py is. (base) antheaguo@Anthea SCBASIS_Website % cd SC_BASIS (base) antheaguo@Anthea SC_BASIS % gunicorn SC_BASIS.wsgi [2024-01-23 14:18:41 -0800] [38700] [INFO] Starting gunicorn 20.1.0 [2024-01-23 14:18:41 -0800] [38700] [INFO] Listening at: http://127.0.0.1:8000 (38700) [2024-01-23 14:18:41 -0800] [38700] [INFO] Using worker: sync [2024-01-23 14:18:41 -0800] [38701] [INFO] Booting worker with pid: 38701 however when I gocd.. to go up a file and run gunicorn SCBASIS.wsgi, it gives me the error message: (base) antheaguo@Anthea SC_BASIS % cd .. … -
How to define factory with specific random choice for Django model?
i would like to define a factory class for a User django model like this : class User(models.Model): name = models.CharField(null=True, blank=True) created_date = models.DateField(null=True, blank=True) but for all fields, i would like to have a fake value from Faker or None because the model allow null. Ideally, the choice between fake value and None is made by probability for example 90% for fake value and 10% for none. i guess a factory like this class UserFactory(factory.django.DjangoModelFactory): name = factory.Faker("random_choice", elements=[factory.Faker("name"), None], p=[0.90, 0.10])) created_date = factory.Faker("random_choice", elements=[factory.Faker("date"), None], p=[0.90, 0.10])) -
Can't validate form with a many=true field in Django-rest
I am trying to use Django-rest as an api for a front end in astro, the think is I am finding a problem when doing my post: {'items': [ErrorDetail(string='This field is required.', code='required')]} My code is the next one: views.py from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import Ticket, Item from .serializers import TicketSerializer, ItemSerializer import json # Create your views here. class TicketView(APIView): def post(self, request, format=None): items = request.data.pop('items')[0] # Items are given as a string with the json format. We need to parse it. items = json.loads(items)[0] # Add the items to the request data data = request.data data['items'] = items data.pop('itemName0') data.pop('itemPrice0') data.pop('itemCount0') print(data) serializer = TicketSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) print(serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializers from .models import Ticket, Item from rest_framework import serializers class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('name', 'price', 'count') class TicketSerializer(serializers.ModelSerializer): items = ItemSerializer(many=True) class Meta: model = Ticket fields = ('img', 'subtotal', 'service', 'tax', 'etc', 'total', 'items') def create(self, validated_data): items_data = validated_data.pop('items') ticket = Ticket.objects.create(**validated_data) for item_data in items_data: Item.objects.create(ticket=ticket, **item_data) return ticket Output of printing the request.data after modifications in the view: … -
Problem in link subdomain in cloudflare to my django app
I have a problem in linking my subdomain on cloudflare to my django app I have a django app on hetzner cloud and I managed to run app on its ip but I could not link it to subdomain in cloudflare xxx.example.com it give me web server is down error 521 What do you think about cloudflare? I managed to run app on hetzner cloud ip -
"from captcha.fields import RecaptchaFields" Is not recognized by wagtailcaptcha
I run my app on docker, and lately, I the web container does not start due to this error File "/usr/local/lib/python3.8/site-packages/wagtailcaptcha/models.py", line 4, in from .forms import WagtailCaptchaFormBuilder, remove_captcha_field File "/usr/local/lib/python3.8/site-packages/wagtailcaptcha/forms.py", line 4, in from captcha.fields import ReCaptchaField ModuleNotFoundError: No module named 'captcha.fields' I have captcha in installed apps, and wagtail-django-recaptcha 1.0 in my requirements.txt. I dropped the container and recreated it but still see the issue. I've read up on different posts including "from captcha.fields import RecaptchaFields" Is not recognized by Pylance but still I could not resolve the issue. -
How do I fix the Cyrillic display?
my_problem_png class Categories(models.Model): name = models.CharField(max_length=150, unique=True, verbose_name="Название") Please help me with this I am very tormented by this problem I'm trying to create a database fixture, but there's some kind of problem with the encoding of Russian characters, according to the guide, everything should work correctly for the YouTuber, but I have some kind of misunderstanding python manage.py dumpdata goods.Categories > fixtures/goods/carts.json -
Django login username label not being overwritten
I added email to be used as an alternative input for the default Django login form and wish to change the label to Username/Email but the common solution I find isn't working. I tried variations on the following and some other solutions with no change to the default Username label. Create a custom login form extending the normal one. class CustomLoginForm(AuthenticationForm): username = forms.CharField( label="Your Custom Label", widget=forms.TextInput(attrs={'autofocus': True}) ) Configure a view to use the custom form with the custom login template. # views.py from django.contrib.auth.views import LoginView from .forms import CustomAuthenticationForm class CustomLoginView(LoginView): authentication_form = CustomAuthenticationForm template_name = 'login.html' Configure the url. # urls.py from django.urls import path from .views import CustomLoginView urlpatterns = [ path('login/', CustomLoginView.as_view(), name='login'), # other URL patterns ] I'm using crispy forms if that matters so in my template I'm using {{ form|crispy }}. I simply want to change the label but am usually getting doubled up labels with common solutions if I include another {{ form.username|as_crispy_field }} in addition to a label tag. Can I remove the label from this latter implementation somehow as a potential solution? I also tried: class CustomAuthenticationForm(AuthenticationForm): def __init__(self, request=None, *args, **kwargs): super().__init__(request, *args, **kwargs) self.fields['username'].label = … -
Is it possible to deploy a Django application that has no frontend component (i.e. is just a backend API)?
Question I have an app that uses Next.js in the frontend and a Django backend. I was able to get the frontend deployed simply enough but I am not sure how to deploy the backend. There is quite a lot of magic happening when using the Vercel deploy so I am not sure how to debug this. According to the Vercel CLI the deploy has completed successfully (I just used the no-arg vercel tool directly from the Django project root directory). The deploy tool appears to have figured out the project was based on Django/python and installed the missing dependencies and such. But now what? When you run a Django server it listens on port 8000 by default. Does Vercel set up a reverse proxy that forwards :80 and :443 connections on to the right place? As far as I am aware, Django does not itself natively support SSL connections (but the default deploy sets up certs and uses it). I suppose this is managed somehow? The behavior I see is that the deployment appears to complete successfully but when I try to hit the domain name in a browser I just see the NOT_FOUND error page: 404: NOT_FOUND Code: …