Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 ? -
Celery' pytest fixtures don't work as expected during http request
everyone. Probably I'm missing somethig on how to use celery' pytest fixtures during a test that involves a task execution during an http request. Celery' docs that shows the pytest integration: https://docs.celeryq.dev/en/v5.3.4/userguide/testing.html#pytest Using 'celery_session_app' and 'celery_session_worker' fixtures I can directly call the task and use wait() or get() to wait for task execution. Sample code for this case: from django.core import mail from django.test import TestCase from polls.tasks import task_send_mail @pytest.mark.usefixtures('celery_session_app') @pytest.mark.usefixtures('celery_session_worker') class SendMailTestCase(TestCase): def test_send_mail(self): task: AsyncResult = task_send_mail.delay( email_address='mail@mail.org.br', message='Hello' ) # waits for task execution that just sends a simple mail using # from django.core.mail import send_mail task.get() # it passes because the code waited for mail send self.assertEqual(len(mail.outbox), 1) However, if I call the same task inside a django view, the task is executed assynchronous and the test fails because the assert is tested before the mail is sent. # view from rest_framework import serializers from rest_framework.generics import ListAPIView from rest_framework.response import Response from django.contrib.auth.models import Group from polls.tasks import task_send_mail class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ['__all__'] class GroupView(ListAPIView): http_method_names = ["get"] queryset = Group.objects.all() serializer_class = GroupSerializer def get(self, request, *args, **kwargs): # task is sent to async execution task = … -
Como resolver os erros de time zone?
ValueError: ZoneInfo keys must be normalized relative paths, got: America/ [31/Oct/2023 10:51:57] "GET /admin/login/?next=/admin/ HTTP/1.1" 500 59 Já instalei a biblioteca tzdata e certifiquei que o arquivo de fuso horário para UTC-3 esteja instalado. Me certifiquei de que a configuração TIME_ZONE esteja definida para a chave de fuso horário normalizada. -
Integration of angular template with Django
I'm a complete beginner in both Django and Angular, and I have an existing Angular project or a purchased Angular template. I want to integrate this Angular frontend with my Django application. Could you please provide step-by-step guidance on how to achieve this integration, considering my beginner-level knowledge in both Django and Angular? I'm using VS Code for Angular and IntelliJ for Django. I need a detailed explanation in simple and understandable terms. Iam able to lauch angular and django project successfully. -
Djnago admin custom form with uploading data
I've a question. I need to add second functionality to may Django Administration panel: I have 2 models (City and Region), one Region has many Cities in it; In my admin panel I want to add excel file with cities list when I'm creating new Region models.py class City(models.Model): name = models.CharField('Город', max_length=50, unique=True) slug = models.SlugField(max_length=50, unique=False, blank=True, null=True) city_latt = models.CharField('Широта', max_length=50, blank=True, null=True) city_long = models.CharField('Долгота', max_length=50, blank=True, null=True) country = models.CharField('ISO код страны', max_length=5) class Meta: verbose_name = 'Город' verbose_name_plural = 'Города' def __str__(self): return self.name class Canton(models.Model): """ Canton list """ canton_name = models.CharField('Название', max_length=255, blank=False) canton_city = models.ManyToManyField(City, verbose_name='Города', blank=False) canton_code_for_map = models.CharField('Код для карты', max_length=20, null=True, blank=True, default=None) canton_shortify = models.CharField('ISO обозначение', max_length=3, null=True, blank=True) country = models.CharField('ISO код страны', max_length=5) slug = models.SlugField('url', max_length=255, unique=True, blank=True) def __str__(self): return self.canton_name def get_cities(self): return ", ".join([c.name for c in self.canton_city.all()]) get_cities.short_description = "Города" get_cities.admin_order_field = 'canton_city' class Meta: verbose_name = 'Территориальные еденицы' verbose_name_plural = 'Территориальные еденицы' so how I can create custom form in my admin where I can upload file and than assign specific Region to uploaded cities? now my admin for Regions looks like this: admin.py class CantonForm(forms.ModelForm): canton_city = forms.ModelMultipleChoiceField(queryset=City.objects.order_by('name'), … -
AuditLog rows have a wrong timezone in timestamp column
I installed AuditLog according to the documentation. Changes are being logged just fine and are save to DB with the right timezone (UTC+6). But when I browse them in admin panel, they come in UTC+0 timezone. Any common ways to fix this? How to change the tz in records stored by the usage of django-auditlog in django admin panel This did not help. -
Display Output von Python subprocess in HTML
I created a website with Django. Various suprocesses are started via a Python script, from which I would like to see the output displayed on my website. This is my python script "example.py" result = subprocess.Popen(<Command>, stdout=subprocess.PIPE) Now i want to display the Output in HTML. I also dont reall know which item i should use to display. However, I don't know how this works and haven't found the right answer yet. -
AWS Lambda: deterministic=True requires SQLite 3.8.3 or higher
I have a website already hosted on AWS Lambda and testing to see if the api works. But when I run it on the website it gives me the error. NotSupportedError at /api/ deterministic=True requires SQLite 3.8.3 or higher Request Method: GET Request URL: https://2dx7zf9yt5.execute-api.us-east-1.amazonaws.com/dev/api/ Django Version: 4.2.4 Exception Type: NotSupportedError Exception Value: deterministic=True requires SQLite 3.8.3 or higher Exception Location: /var/task/django/db/backends/sqlite3/_functions.py, line 45, in register Raised during: blog_api.views.PostList Python Executable: /var/lang/bin/python3.11 Python Version: 3.11.6 Python Path: ['/var/task', '/opt/python/lib/python3.11/site-packages', '/opt/python', '/var/lang/lib/python3.11/site-packages', '/var/runtime', '/var/lang/lib/python311.zip', '/var/lang/lib/python3.11', '/var/lang/lib/python3.11/lib-dynload', '/var/lang/lib/python3.11/site-packages', '/opt/python/lib/python3.11/site-packages', '/opt/python', '/var/task'] Server time: Tue, 31 Oct 2023 12:14:06 +0000 I saw a different related question that shows me that I have to install pysqlite3, but I keep ending up with the error ERROR: Failed building wheel for pysqlite3 Even when I installed the wheel, setuptools and cmake. I am running Python3.11.3 I am hoping to learn django from this experience hosting on awls but its abit tough. -
QuerySet object has no attribute _meta showing
'QuerySet' object has no attribute '_meta' def bugtracker_add(request): if request.method == "POST": try: project_id = Project.objects.get(id=project) users_created_by = Users.objects.filter(id=request.session['user_id']).filter(~Q(status=2)) # when filtering we need to pass in array list [] it will save default in database we not passing any request.post.get. Just passing through instance how login and save id by passing array list assigned_users_id = Users.objects.get(id=assigned_to) report_users_id = Users.objects.get(id=bugtracker_report_to) bugtracker_details = BugTracker.objects.create(name=name, project=project_id, priority=priority, assigned_to=assigned_users_id, report_to=report_users_id, status=status, description=description, created_by=users_created_by[0]) bugtracker_details.save() bug_id = BugTracker.objects.get(id=bugtracker_details.id) users_updated_by = Users.objects.filter(id=request.session['user_id']).filter(~Q(status=2)) bughistory_details = BugHistory.objects.create(bug_tracker=bug_id, status=bugtracker_details.status, updated_by=users_updated_by[0]) bughistory_details.save() if bugtracker_details: sender = BugTracker.objects.filter(created_by=request.session['user_id']).filter(~Q(status=2)).filter(~Q(status=4)) assigned = Users.objects.filter(id=assigned_to) print(assigned) for ass in assigned: assign = ass.user.id print(assign) receiver = User.objects.get(id=assign) sended = bugtracker_details.created_by message = f'Hello to you assigned BugTracker by {sended.first_name}' print(message) notify.send(sender, recipient=receiver, verb='Message', description=message) except Exception as e: print(e) return redirect("pms_project:bugtracker_list") try: project_data = Project.objects.values('id', 'name').filter(~Q(status=2)) users_data = Users.objects.values('id', 'first_name').filter(~Q(status=2)) users_report_data = Users.objects.values('id', 'first_name') return render(request, 'bugtracker/add.html', {"project_id": project_data, 'users_id': users_data, 'users_report_id': users_report_data}) except Exception as e: print(e) return render(request, 'bugtracker/add.html', {}) not getting where to change in my app i am using with out app name I have stored with model name in database. when written to send notification from custom model to user model at reciptient gettting insingle instances only but. still …