Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issues with django file logger
I have a created a django logger settings. It is intended that console django.db.backends should not be applied to console. But it is printing in console as well. LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "%(levelname)s %(asctime)s %(module)s " "%(process)d %(thread)d %(message)s" } }, "handlers": { "file": { "level": "DEBUG", "class": "logging.handlers.TimedRotatingFileHandler", "filename": "debug/debug.log", 'when': 'W0', # Weekly log staring from Monday 'interval': 1, 'backupCount': 10, }, "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "verbose", }, }, "root": {"level": "INFO", "handlers": ["console"]}, "loggers": { 'django.db.backends': { 'level': 'DEBUG', 'handlers': ['file'], } }, } This is my logger configuration. With this it is logging sql commands in file as well as console. I want this to be logged only for file. Please help if you have encountered this issue before. -
django-allauth and django-phone-auth clash on EmailAdress.User mutual accessors
I have my auth app in Django and a custom user defined as #auth/models.py class User(AbstractUser): pass And it is set as the user_model in settings: AUTH_USER_MODEL = 'auth.User' I'd like to use django-phone-auth for authenticating with phone or email, and django-allauth to authenticate with social providers. After I add the both to my virtual environment and try migrate I get the error: account.EmailAddress.user: (fields.E304) Reverse accessor 'User.emailaddress_set' for 'account.EmailAddress.user' clashes with reverse accessor for 'phone_auth.EmailAddress.user'. The problem is in the same-named models having foreign key relation to the user model in the two packages. #allauth/account/models.py class EmailAddress(models.Model): user = models.ForeignKey( allauth_app_settings.USER_MODEL, verbose_name=_("user"), on_delete=models.CASCADE, # # !!!! related_name='accountuser' would solve the conflict ) ... vs. #phone-auth/models.py class EmailAddress(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ... The clash is due to reverse reference conflict, and adding related_name='accountuser' to any of the user fields does solve it. But changing original code of installed packages is not a good idea. Can anyone advise how it should be sorted out, please. Many thanks! -
Django rest framework nested data receiving from JavaScript nested form-data
My problem is that creating nested form-data and receiving them. Here is my models.py: class BridgeReport(models.Model): bridge = models.ForeignKey(Bridgedata, on_delete=CASCADE, related_name='report') title = models.TextField(blank=True, null=True) def __str__(self): return self.title class MajorInspection(models.Model): major_inspection = ForeignKey(BridgeReport, related_name='major_inspection', on_delete=CASCADE) damaged_member = models.TextField(blank=True, null=True) grade = models.TextField(blank=True, null=True) # choice class MajorInspectionReport(models.Model): major_inspection_report = ForeignKey(MajorInspection, related_name='major_inspection_report', on_delete=CASCADE) defect_type = models.TextField(blank=True, null=True) cause = models.TextField(blank=True, null=True) maintenance_and_reinforcement_plan = models.TextField(blank=True, null=True) special_note = models.TextField(blank=True, null=True) attached_file = models.ImageField(upload_to = custom_upload_to_MajorInspection, blank=True) Here is my serializers.py class MajorInspectionReportSerializer(serializers.ModelSerializer): class Meta: model = MajorInspectionReport exclude = ['major_inspection_report'] def create(self, validated_data): # Handle the creation of a MajorInspectionReport instance here return MajorInspectionReport.objects.create(**validated_data) class MajorInspectionSerializer(serializers.ModelSerializer): major_inspection_report = MajorInspectionReportSerializer(many=True, read_only=True) major_inspection_reports = serializers.ListField( child = CustomField(), write_only = True, required=False ) def create(self, validated_data): print("1Validate data", validated_data) major_inspection_reports = validated_data.pop("major_inspection_reports") major_inspection_report = MajorInspection.objects.create(**validated_data) if major_inspection_reports: print("2major_inspection_reports: ",major_inspection_reports) for dic in major_inspection_reports: print("3mana:",dic.get('[defect_type]', '')) print("dic is ", dic) MajorInspectionReport.objects.create( major_inspection_report=major_inspection_report, defect_type=dic.get('[defect_type]', ''), cause=dic.get('[cause]', ''), maintenance_and_reinforcement_plan=dic.get('[maintenance_and_reinforcement_plan]', ''), special_note=dic.get('[special_note]', ''), attached_file=dic.get('[attached_file]', ''), ) return major_inspection_report return MajorInspection.objects.create(**validated_data) class Meta: model = MajorInspection exclude = ['major_inspection'] class BridgeReportSerializer(serializers.ModelSerializer): major_inspection = MajorInspectionSerializer(many=True, read_only=True, required=False) model_3d = ThreeDModelSerializer(many=True, read_only=True, required=False) upload_major_inspections = serializers.ListField( child = CustomField(), write_only = True, required=False ) class Meta: model = BridgeReport exclude … -
Django Rest Framework: Unable to Retrieve Authorization Token from Header on Hosted Server
I have hosted a Django Rest Framework API on a domain. In my code, I retrieve the Authorization token from the header using the following line: request.headers.get('Authorization', None) This code works perfectly fine on my local server and when I run the server using python manage.py runserver with an IP address. However, when deployed on my hosted server, I'm getting None as a result. Any help or insights would be greatly appreciated. Thank you! I have already added my domain to the ALLOWED_HOSTS setting in Django's settings file. The server is hosted on a Linux environment. Is there any additional configuration that I need to apply for a hosted deployment, specifically on a Linux server, to ensure that the Authorization header is correctly received? -
Seeking Guidance on Building an Online Compiler with Django and Testing Features [closed]
Hello Stack overflow community, I have an ambitious project in mind, and I'm seeking guidance and insights from experienced developers. I'm interested in creating an online compiler similar to platforms like HackerRank, and I'd like to use Django, a web framework, to help achieve this. Here's the vision: Users can access a code editor on the platform. I can provide questions or coding challenges to users. Users write and run their code within the platform. After running the code, the system should automatically check it against various test cases, just like HackerRank. The code is evaluated, and it's marked as either "pass" or "fail." My question is, are there any existing open-source projects, codebases, or tutorials that can help me get started on this project, specifically using Django as the foundation? I'd appreciate any advice or resources that can assist me in building this platform, including insights on how Django can be utilized for this purpose, along with technologies and libraries that could complement it. I'm aware that this is a substantial project, and I'm excited to take on the challenge with Django. Your expertise and guidance would be invaluable to me as I embark on this journey. Thank you … -
Django, MySQL, JSONField - Filtering Issue with JSON Data
I'm encountering an issue with filtering JSON data stored in a Django JSONField. While attempting to filter data using the icontains lookup, it seems to treat the JSON data as a string field, and the filtering doesn't work as expected. Here's a brief overview of my setup: Model: I have a Django model with a JSONField like this: from django.db import models class ChatMessage(models.Model): template_message = models.JSONField(null=True) The JSON data is stored in the following format in the database: { "header": { "type": "text", "content": "Hello" }, "body": "Hi there", "footer": "Hello there" } Problem Description: The problem I'm facing is with the filtering code. I want to filter objects based on values within the JSON data, but the icontains lookup seems to be treating it as a string field rather than a JSON field. ChatMessage.objects.filter( Q(template_message__header__content__icontains=search_key) | Q(template_message__body__icontains=search_key) | Q(template_message__footer__icontains=search_key) ) Expected Outcome: I expect the filtering to consider the JSON structure and filter based on the presence of search_key within any of the JSON values, such as in the content, body, or footer fields. Error Messages: I haven't received any error messages, but the filtering doesn't work as expected. -
UnboundLocalError at /subscribe/ local variable 'customer' referenced before assignment in stripe payment
else: try: customer = stripe.Customer.create( email = request.user.email, plan = order.plans, description = request.user.email, card = payment_form.cleaned_data['stripe_id'], ) except stripe.error.CardError: messages.error(request, "Your card was declined!") return redirect(reverse('subscribe')) finally: subscription = Subscription( user = request.user, plan = plan_ids[order.plans], customer_id = customer.id ) -
django-distill not exporting URL's correctly
I am using django-distill to create a static HTML output of my Django site. I am having an issue with how distill converts {% static %} and {% url %} tags into relative HTML URLs. Worth noting that I have also tried Django-bakery and am encountering exactly the same problem. Let's start with the homepage. This is an 'index.html' file in the parent directory. This is the output I get from distill: <link rel="stylesheet" href="/static/css/styles.css"> The '/' at the front of the URL appears to be causing a problem. With the code above, the style sheet does not load in the browser. But if I manually remove the '/', the following code works: <link rel="stylesheet" href="static/css/styles.css"> For HTML pages nested in subdirectories, the same problem is occurring but the solution is more complex. Distill outputs the code as below: ` However, I believe the correct output should start with "../../" to indicate to the browser that the static folder is up 2 levels in the parent directory. The following code works correctly when I edit it manually: <link rel="stylesheet" href="../../static/css/styles.css"> The same problem occurs with both static links and URL links. As I'm struggling to pinpoint where in my django … -
How to Override Django ManyRelatedManager Methods and Enforce Validations
I have the following two models that have a Many-to-Many (m2m) relationship. I want to implement validation rules when creating a relationship, particularly when the Field object is controlled. class Category(models.Model): name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=50, unique=True, editable=False) fields = models.ManyToManyField("Field", related_name="categories") class Field(models.Model): controller = models.ForeignKey( "self", models.CASCADE, related_name="dependents", null=True, blank=True, ) label = models.CharField(max_length=50) name = models.CharField(max_length=50) When creating a relationship between a Category and a Field objects via the add() method, I would like to validate that, for a controlled field, the controller field must already be associated with the category. When creating via the set(), I would like to validate for any controlled field in the list, the controller field must also be in the list, OR is already associated with the category. # Category category = Category.objects.create(name="Cars", slug="cars") # Fields brand_field = Field.objects.create(name="brand", label="Brand") model_field = Field.objects.create(name="model", label="Model", controller=brand_field) # controller should already be associated or raises an exception category.fields.add(model_field) # Controller must be inclded in the list as well, # OR already associated, or raise an exception category.fields.set([model_field]) Where can I enforce this constraints? I'm thinking of overriding ManyRelatedManager's add() and set() methods but I do not understand how they're coupled to … -
Image uploaded via CKEditor in Django extends beyond the div
I'm working on my very first Django project, a blog, and I'm almost done with it. However, I've got this quirky issue: the images I upload through CKEditor spill out of the div they're supposed to stay in. Any ideas on how to fix that? This is how I upload the image: I understand that when uploading, I am able to set the image size. However, I would like the image width to be 100% of the div automatically, while maintaining the original image's aspect ratio for the height. This is how it is displayed: Here is the template: {% extends "mainapp/base.html" %} {% block content %} <div id="main-container"> <div id="second-container"> {% if article.article_image %} <img src="{{article.article_image.url }}" id="article-image"> {% endif %} <p>Published: {{article.publication_date}} {% if article.last_edit_date != None %} Last edit: {{article.last_edit_date}} {% endif %} </p> <h1>{{article.title}}</h1> <p>{{article.body|safe}}</p> {% if user.is_superuser %} <a href="{%url 'mainapp:edit_article' article.id %}"><button type="button">Edit</button></a> <a href="{%url 'mainapp:delete_article' article.id %}"><button type="button">Delete</button></a> {% endif %} </div> <br> <br> <div id="second-container"> <h3>Comments section</h3> {% for comment in comments %} <p> {{comment.publication_date}} {% if comment.author == "ravdar (op)" %} <span style="color: orangered; font-weight: bold;">{{ comment.author }}</span> {% else %} {{ comment.author }} {% endif %} <p>{{comment.text}}</p> {% endfor %} … -
Django & Djoser - AttributeError: 'NoneType' object has no attribute 'is_active' when registering a new user
I am trying to implement user registration using djoser. I believe I am passing in all the correct data in the body but I return a 500 error: "AttributeError: 'NoneType' object has no attribute 'is_active'" I have tried overwriting list_display and list_filter in BaseUserAdmin. I also have tried moving the is_active attribute to different areas of the model. models.py from django.contrib.auth.models import AbstractUser, AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ # managing the creation and user and superuser class UserAccountManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): # first_name, last_name, if not email: raise ValueError('Users must provide an email address.') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_active') is not True: raise ValueError('Superuser must have is_active=True.') if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email serializers.py from djoser.serializers import UserCreateSerializer from django.contrib.auth import get_user_model … -
Website fails to load after db data upload
The website I am working with is based on django v3.2.19 with a mysql v8.0.32 back end, in a windows 10 environment. The database had limited data, so I updated the db from a backup of the same db set up on a different system (AWS, linux). The website, up until an hour ago was up and running. After the data upload, I was unable to start the server with 'python manage.py runserver'. The stacktrace that is displayed ends with: C:\Users\jw708\Documents\Gain\gain>python manage.py test Traceback (most recent call last): File "C:\Users\jw708\Documents\Gain\gain\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Program Files\Python311\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Program Files\Python311\Lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "C:\Program Files\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\Python311\Lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Program Files\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'dal' Several online sites suggested that 'dal' needs be installed. The 'dal' is the first app listed in the INSTALLED_APPS list of the settings.py file … -
rabbitmq returns [Errno 111] Connection refused when connecting to celery
In my app I have rabbitmq as message broker and celery to manage the tasks from BE. When trying to run any Celery @shared_task im getting this error: kombu.exceptions.OperationalError: [Errno 111] Connection refused This is my docker-compose.yml file: version: "3.9" services: app: build: context: . args: - DEV=${IS_DEV} restart: always ports: - "${APP_PORT}:8000" volumes: - "./src:/app/src" - "./scripts:/app/scripts" - "./Makefile:/app/Makefile" - "./pyproject.toml:/app/pyproject.toml" - "./Dockerfile:/app/Dockerfile" depends_on: - postgres-main - celery command: > sh -c ". /app/venv/firewall_optimization_backend/bin/activate && python3 /app/src/manage.py migrate && python3 /app/src/manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=${DB_HOST} - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} - IS_DEV=${IS_DEV} - DJANGO_SECRET_KEY=${DJANGO_SECRET_KEY} - DEFAULT_LOOKUP_CONFIG_FILE=${DEFAULT_LOOKUP_CONFIG_FILE} postgres-main: image: postgres:15-alpine3.18 restart: always volumes: - postgres-main-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=${POSTGRES_DB} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} rabbitmq: image: "rabbitmq:management" ports: - "${RABBIT_MQ_MANAGEMENT_PORT}:15672" - "${RABBIT_MQ_PORT}:5672" celery: build: . command: > sh -c ". /app/venv/firewall_optimization_backend/bin/activate && celery -A src.celery_config worker --loglevel=info" volumes: - "./src:/app/src" - "./scripts:/app/scripts" - "./Makefile:/app/Makefile" - "./pyproject.toml:/app/pyproject.toml" depends_on: - rabbitmq environment: - DB_HOST=${DB_HOST} - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} - IS_DEV=${IS_DEV} - DJANGO_SECRET_KEY=${DJANGO_SECRET_KEY} - CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672// volumes: postgres-main-db-data: -
Informix "21005 Inexact character conversion during translation" error
currently am working on a django project that connect to an informix database using (CSDK/ODBC) and the connection is established correctly, but when i try inserting data in darabic language i get this error: "21005 Inexact character conversion during translation". The thing is that some arabic letters are inserted without any problem (the arabic characters from U+060C to U+063A in ascii code) but onece i insert one of the characters after the unicode U+063A i get the error. i have tried changing client_local and db_local variables (maybe i didn't do it correctly) but nothing seems to work. i would be very greatfull if you could help me even with a hint or a suggestion. thank you in advance. -
Change logic for admin views in django
I am creating a website in pure django where I have the following model. class GoodsDetails(models.Model): serial_number = models.CharField(max_length=100) goods_description = models.CharField(max_length=100) quantity = models.CharField(max_length=100) gross_weight = models.CharField(max_length=100) is_active = models.BooleanField() def __str__(self): return f"{self.serial_number}" I have registered the model in the administration and I want to show all the model instances to the superuser but to non-superusers, I want to show only those instances where is_active = False. How can this be achieved in django administration? I researched about it and think that I should create a custom permission for this job. However, I think that modifying the admin views logic would be better because in this case, changing the ORM query a bit will get the job done. Any other approaches are also welcome. Thank you for your suggestions and/or solutions :) -
Add custom user field for each product in django
I have just started to use django for web development and couldn't figure something out, I want to be able to define different required fields for my e-commerce django website and those input fields show up in the product page. Then users fill those input fields when adding them to them to their cart. For example in a t-shirt product page be able to define 'color' , 'size' and 'custom print' Any help would be much appreciated -
django specified database table different from what is specified
In my django model I am specifying the db table i want to use with class Meta: db_table = 'users' however I am getting the error django.db.utils.ProgrammingError: (1146, "Table 'db.users' doesn't exist") why is django adding the database name before the table name when trying to look for the table name? I've looked in the migrations file and options={ 'db_table': 'users', }, is specified -
Django gives Forbidden: 403 for POST request with my live react website but not when using postman
When I try to send the request given below from my react website, Django returns a 403 error. axios.post(apiUrl, formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(response => { console.log('Attendance uploaded successfully:', data); }).catch(error => { console.error('Error uploading attendance:', error); }); I get Forbidden (403) error. But when I run the code from my local server (localhost:3000), it does not give an error, and return 200. Same for Postman, it does not return any error and returns 200. My settings.py file looks like: ALLOWED_HOSTS = ['domain', '10.17.51.139', 'localhost', '127.0.0.1'] CORS_ALLOW_ALL_ORIGINS = True CSRF_TRUSTED_ORIGINS=['https://domain', 'http://domain', 'http://10.17.51.139', 'http://localhost:3000'] Can anyone explain why? I tried including cookies in the header, but that was of no use, I also applied the @csrf_exempt tag in my view, but same error again. I also tried to remove middleware but still no difference GET requests do not give any trouble and return 200 for live website as well. Can someone explain why this is happening and suggest a solution -
Python MYSQL Server Eror "Can't connect to MySQL server on 'mysql' ([Errno -2] Name or service not known)"
I'm encountering an issue while trying to run my Django application within a Docker container using Docker Compose. I've set up a Docker Compose configuration with a Django app and a MySQL database. However, when I try to run my code through Docker, I'm getting the following error: (venv) buckberry@Buraks-MacBook-Pro OrderDashboard % docker build -t my-django-app . [+] Building 7.8s (14/14) FINISHED docker:desktop-linux => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 722B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 235B 0.0s => [internal] load metadata for docker.io/library/python:3.8 1.8s => [auth] library/python:pull token for registry-1.docker.io 0.0s => [1/8] FROM docker.io/library/python:3.8@sha256:862b9d1a0cb9098b0276a9cb11cb39ffc82cedb729ef33b447fc6b7d61592fea 0.0s => [internal] load build context 1.3s => => transferring context: 2.27MB 1.1s => CACHED [2/8] ADD requirements/base.txt /tmp/requirements.txt 0.0s => CACHED [3/8] ADD requirements/dev.txt /tmp/requirements-dev.txt 0.0s => CACHED [4/8] RUN pip install --upgrade pip && pip install -r /tmp/requirements.txt && pip install -r /tmp/requirements-dev.txt 0.0s => CACHED [5/8] RUN mkdir -p "/opt/python/log/" && touch /opt/python/log/dashboard.log 0.0s => CACHED [6/8] RUN chmod 755 /opt/python/log/dashboard.log 0.0s => [7/8] ADD . /app 3.3s => [8/8] WORKDIR /app 0.0s => exporting to image 1.4s => => exporting layers 1.4s => => writing image sha256:2a520d3ef291be98fddbb5a9078c098cec78062b861412ee1e5e043e5d616b3e 0.0s => => … -
swagger not working after deploying to vercel
When deploying my code I see this under the /docs endpoint (swagger) https://python-django-project.vercel.app/docs - link My settings.py: from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = "django-insecure-rjo^&xj7pgft@ylezdg!)n_+(6k$22gme@&mxw_z!jymtv(z+g" DEBUG = True INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "api.apps.ApiConfig", "rest_framework_swagger", "rest_framework", "drf_yasg", ] SWAGGER_SETTINGS = { "SECURITY_DEFINITIONS": { "basic": { "type": "basic", } }, "USE_SESSION_AUTH": False, } REST_FRAMEWORK = { "DEFAULT_PARSER_CLASSES": [ "rest_framework.parsers.JSONParser", ] } MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "app.urls" 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", ], }, }, ] APPEND_SLASH = False WSGI_APPLICATION = "app.wsgi.app" # Normalnie te zmienne bylyby w plikach .env na platformie vercel DATABASES = { "default": { "ENGINE": "", "URL": "", "NAME": "", "USER": "", "PASSWORD": "", "HOST": "", "PORT": 00000, } } ALLOWED_HOSTS = ["127.0.0.1", ".vercel.app", "localhost"] # Password validation # https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, { "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, { "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] # Internationalization # https://docs.djangoproject.com/en/4.2/topics/i18n/ LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = "static/" # Default primary … -
Razorpay API Request Error - Emojis Causing Internal Server Error (500) and Bad Request (400)
I'm encountering an issue with Razorpay API requests in my web application. When emojis are included in the API request data, I'm receiving "Internal Server Error (500)" and "Bad Request (400)" responses from Razorpay. I suspect that the emojis in the data are causing the problem, as the error message suggests. However, I'm not sure how to handle this issue effectively. I am getting a 500 Internal Server Error when I send emojis in my API request. The error message says: This error occurs when emojis are sent in the API request. We are facing some trouble completing your request at the moment. Please try again shortly. Check the API request for emojis and resend. These errors are print in the browser console 1} checkout.js:1 Unrecognized feature: 'otp-credentials'. 2} GET https://browser.sentry-cdn.com/7.64.0/bundle.min.js net::ERR_BLOCKED_BY_CLIENT 3} Canvas2D: Multiple readback operations using getImageData are faster with the willReadFrequently attribute set to true. See: https://html.spec.whatwg.org/multipage/canvas.html#concept-canvas-will-read-frequently 4} checkout.js:1 POST https://lumberjack-cx.razorpay.com/beacon/v1/batch?writeKey=2Fle0rY1hHoLCMetOdzYFs1RIJF net::ERR_BLOCKED_BY_CLIENT 5} checkout-frame.modern.js:1 Error: <svg> attribute width: Unexpected end of attribute. Expected length, "". 6} checkout-frame.modern.js:1 POST https://api.razorpay.com/v1/standard_checkout/payments/create/ajax?session_token=1195957E22CEDC68FA41546EAFCB32822446AFCE189C65DEEA3D65FD8A5954842A4CC50914376849E37749EDAC80962106F2D99A99F0DAA2D1745E12FEBA19FEF4AC340FEC0AF9C18340A00E7828A099572C469DAF2518EA61D0369B75A7AEAF8BF61EEE979B536EF040F8E777EDFE695FEF10951EE8EA0B49E9DED09695E32582159FA5A03EE334DD16116CC22B759BB98C 500 (Internal Server Error) I'm using Razorpay for payment processing, and I have both JavaScript and Python code involved. Here's a simplified overview of my code: HTML/JavaScript (Frontend): … -
How do I get a .USDZ file to automatically open in iOS quicklook without the need to click on an image
I am currently serving my .USDZ model from django and have the following view. def download(request, id): file_path = os.path.join(settings.MEDIA_ROOT, 'files/{0}.usdz'.format(id)) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="model/usd") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 This page is accessed through a QR code but when the code is scanned with an i-phone the page opens and displays an image of a 3D cube. The picture then needs to be clicked in order to start the AR. Is it possible to automatically start the quicklook AR without needing to click on the image? Not sure if it would be possible with hosting the link on a page then using javascript to automatically click the link? -
Can't make post from template
Can't make post from template, but can from admin panel.... and i wanna fix it so I can make post from template, there is no error in console... Help needed. template/create_post.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h1 style="text-align:center; margin-block:50px; color:red;">Hey {{user}}, Write something</h1> <form method="POST" action="." enctype="multipart/form-data" style="margin-left:150px;"> {% csrf_token %} {{form|crispy}} <input type="submit" value="Save" style="margin-block:50px;"> </form> {% endblock content %} main/views.py from .forms import PostForm from django.contrib.auth.decorators import login_required @login_required def create_post(request): context = {} form = PostForm(request.POST or None) if request.method == "POST": if form.is_valid(): author = Author.objects.get(user=request.user) new_post = form.save(commit=False) new_post.user = author new_post.save() return redirect("home") context.update({ "form": form, "title": "Create New Post", }) return render(request, "create_post.html", context) main/urls.py from django.urls import path from .views import home, detail, posts, create_post, latest_posts urlpatterns = [ path("", home, name="home"), path("detail/<slug>/", detail, name="detail"), path("posts/<slug>/", posts, name="posts"), path("create_post", create_post, name="create_post"), path("latest_posts", latest_posts, name="latest_posts"), ] main/forms.py from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ["title", "content", "categories", "tags"] Earlier it was working, but I make some mistake and now it is not... last time there was some errors but I fixed them just by modify slug … -
Trying to find out total no of votes, but could not understand how it is done in serializers. I'm new to django, How is it done?
Here is my model : class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') answer = models.CharField(max_length=1000, default="", blank=False) author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) createdAt = models.DateTimeField(auto_now_add=True) upVotes = models.IntegerField(default=0) downVotes = models.IntegerField(default=0) def __str__(self): return str(self.answer) Here is the serializer: class AnswerSerializer(serializers.ModelSerializer): votes = serializers.SerializerMethodField(method_name='get_votes', read_only=True) class Meta: model = Answer fields = ('id', 'question', 'answer', 'author', 'createdAt', 'votes') def get_votes(self, obj): if obj.upVotes and obj.downVotes: total_votes = (obj.upVotes + obj.downVotes) return total_votes Here is my upVote view : @api_view(['POST']) @permission_classes([IsAuthenticated]) def upvote(request, pk): answer = get_object_or_404(Answer, id=pk) author=request.user voter = upVote.objects.filter(author=author, answer=answer) if voter.exists(): return Response({ 'details':'You cannot vote twice' }) else: upVote.objects.create( answer=answer, author=author ) answer.upVotes += 1 answer.save() return Response({ 'details':'Vote added' }) How to find total number of votes and that should be directed to answers model. How to do this kind of operations in serializers? -
Django Form List Value Multiple Choice in Form based on values in other fields in same form
I have a problem in Django Form Basically I am developing a Form which shows the following information: Date From Date To Client Select Jobs to be reviewed: Now i have a model where the jobs are linked to a clients and the jobs have a date when they were created and when they were terminated. I would like that in the form as soon as the user inputs the date from of the review and Date To of the review and the client in question by default a list of jobs will be displayed for the user to select. The list of jobs is based between the active jobs during the period selected and also the client. Is there a way to achieve this dynamically in the same form in Django ? Any ideas how to achieve it? I tried using ChainedManyToManyField so that based on the client selected in same form the list of jobs would be displayed and I succeeded. The problem is that i do not know how to also filter by the job creation date and job terminated date ?