Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DjangoJobStore Randomly Deletes Jobs
I have apscheduler running with a DjangoJobStore from a management command in django, but every so often some (not all) of the jobs will be deleted from the database. The scheduler still runs, still gets other jobs, but doesnt find the specific one in the code below. When i check the admin, its deleted. Restarting the command fixes it as it adds the job back for a random amount of time before deleting again. I added a listener for EVENT_JOB_REMOVED and it is never fired, and i added breakpoints in all the delete methods for DjangoJob and none of them ever hit. the function must_reply simply checks an email inbox and sends a reply back over smtp, nothing in there accesses the DjangoJob table, nor does anything in the rest of the code. must_reply is decorated with @close_old_connections removing DjangoJobStore as a job store fixes the problem, but obviously I would like to use it haha Has anyone experienced this? And what are some solutions or ideas to try for fixing this. It is truly strange. class Command(BaseCommand): help = "Runs APScheduler." def handle(self, *args, **options): executors = { 'default': ThreadPoolExecutor(max_workers=10) } job_defaults = { 'coalesce': True, 'misfire_grace_time': 10 } … -
Dockerized Django + Nginx startup & mounting issue
I want to create a enviroment for my personal project hovewer I'm strugling and can't resolve the issue. I had it working, made some reorganization in the project structure to structure it like i want (or think is best) and broke it trying to fix it :/ And to be honest i had simmilar issue in the past, I strugled with it ... i guess I did not learn anything and forgot how i fixed it (wasnt dockerized). The project is just basic default configuration to have it running as i want, so I have the comfort of the CI/CD jenkins deployement and can run and play across docker containers. I will share the relevant parts as well as the project structure. Project file structure: RaC/ ├── django/ │ ├── Dockerfile │ ├── .env │ ├── manage.py │ ├── files/ │ │ ├── media/ │ │ └── static/ │ └── rac_backend/ │ ├── __init__.py │ ├── asgi.py │ ├── requirements.txt │ ├── settings.py │ ├── urls.py │ ├── wsgi.py ├── jenkins/ ├── nginx/ ├── postgres/ ├── redis/ ├── templates/ ├── venv/ ├── manage.py └── docker-compose.yml docker-compose.yml version: '3.8' services: jenkins: build: context: ./jenkins ports: - "8080:8080" - "50000:50000" volumes: - … -
Issues with sending emails through Outlook using the Win32 library in Django
I'm using Win32 for sending emails on my website. In general, the emails are sent and reach the recipient, but the problem is that the recipient does not change. Initially, when I started this project, I used a single test email to use in different scenarios. This email was "email1@outlook.com". Later, I added another email for another user named User 2 with their own email "email2@outlook.com". The problem is that the recipient does not change. I specifically select that my recipient is "email2@outlook.com", but I always receive all emails at "email1@outlook.com". outlook = win32.Dispatch('Outlook.Application') mail = outlook.CreateItem(0) mail.SentOnBehalfOfName = 'xxxxxxxx@outlook.com' mail.To = email mail.Subject = 'NUEVA SOLICITUD DE PRUEBAS DE LABORATORIO' mail.BodyFormat = 2 html_body = f""" <html> <body style="font-family: 'Arial', sans-serif; background-color: #f4f4f4; margin: 0; padding: 0;"> <div style="max-width: 600px; margin: 20px auto; background-color: #ffffff; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);"> <h1 style="color: #333; margin-bottom: 10px;">Nueva solicitud de pruebas de laboratorio de {full_name}</h1> <p style="color: #555; margin-bottom: 20px;">El usuario {full_name} ha creado una nueva solicitud de pruebas de laboratorio para el cliente {customer} con una fecha requerida para el {require_date}. A continuación, se detallan más información y enlaces:</p> <ul style="list-style-type: none; padding: 0;"> … -
How do i prevent djagno from deleting leading zeros in a CharField?
I need to store strings like "0000", "0001" in my model fields, but fields like CharField, TextField and SlugField are deleting leading zeros and i end up with "0" and "1". How do I prevent this behaviour? I tried using all types of string containers in djagno Models and adding self.code.zfill(4) to save method of the model, but nothing helped. That's what my field looks like: `class User(django.contrib.auth.models.AbstractUser): objects = UserManager() code = django.db.models.UUIDField( "код", unique=True, null=True, blank=True, max_length=4, validators=[], ) def save(self, *args, **kwargs): self.code = str(self.code.zfill(4)) super().save(*args, **kwargs)` -
Creating groups
I want to create groups but i am unsure how, is this the correct way? whats the next step after creating this from django.core.management.base import BaseCommand from django.contrib.auth.models import Group, Permission class Command(BaseCommand): help = 'Creates initial groups for the application' def handle(self, *args, **options): # Define the list of group names and descriptions along with associated permissions groups_data = [ { 'name': 'Students', 'description': 'Group 1: Students', 'permissions': ['create_portfolio', 'view_own_portfolio', 'change_own_portfolio', 'delete_own_portfolio'] }, { 'name': 'Lecturers', 'description': 'Group 2: Lecturers', 'permissions': ['view_all_portfolios'] }, { 'name': 'Local admin', 'description': 'Group 3: Local admin', 'permissions': ['view_all_portfolios'] }, { 'name': 'Organisation admin', 'description': 'Group 4: Organisation admin', 'permissions': ['view_all_portfolios'] }, # Add more groups as needed ] # Create groups with associated permissions for data in groups_data: group, created = Group.objects.get_or_create(name=data['name']) if created: group.description = data['description'] group.save() # Add permissions to the group for perm_codename in data['permissions']: permission = Permission.objects.get(codename=perm_codename) group.permissions.add(permission) self.stdout.write(self.style.SUCCESS(f'Group "{group}" created successfully')) else: self.stdout.write(self.style.WARNING(f'Group "{group}" already exists')) -
Publish messages to MQTT using Celery-Beat scheduled tasks
I am developing a Django+Vue web application along with an MQTT server. I want to implement Celery Beat to execute scheduled tasks, which I define in the "calendarios" models where I input the tasks according to the date, interval, repetition, and others. In "eventosCalendarios," I save each task with the time and date to execute. What I aim for is that upon executing each task, I can publish to a specific topic on the MQTT server. Models.py class calendarios(models.Model): nombre=models.CharField(max_length= 100, verbose_name='Nombre', unique=True) acciones=models.ForeignKey(acciones, null=True,blank=True,on_delete=models.CASCADE,verbose_name='Acciones') fecha_inicio = models.DateField(null=True, blank=True) fecha_fin = models.DateField(null=True, blank=True) repeticion= models.CharField(max_length=1, choices=repeticionChoices, default='D') # Ej: 'diaria', 'semanal', 'mensual' intervalo = models.IntegerField(null=True, blank=True) # Número de días, semanas o meses dependiendo de la repeticion todoCultivo= models.CharField(max_length=1, choices=SioNO, default='S') hora_repeticion_1 = models.TimeField(null=True, blank=True) # Hora de la primera repetición diaria hora_repeticion_2 = models.TimeField(null=True, blank=True) # Hora de la segunda repetición diaria hora_repeticion_3 = models.TimeField(null=True, blank=True) cultivo=models.ManyToManyField(cultivo, verbose_name="Cultivos",blank=True) plantas=models.ManyToManyField(plantas, verbose_name="Plantas",blank=True) def __str__(self): return self.nombre class Meta: verbose_name = 'Calendario' verbose_name_plural = 'Calendarios' db_table = 'calendarios' ordering = ['id'] class eventosCalendarios(models.Model): title = models.CharField(max_length=100) start = models.DateTimeField() calendario = models.ForeignKey(calendarios, on_delete=models.CASCADE) allDay = models.BooleanField(default=False) def __str__(self): return self.title class Meta: verbose_name = 'Evento calendario' verbose_name_plural = 'Eventos calendarios' db_table = … -
docker-compose: how to connect two projects so they could send requests to each other
Let's say, I have two projects: spam-service and eggs-service. Here is the spam's YAML-file: version: '3' services: spam-db: image: postgres:11.4 restart: unless-stopped environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: spam volumes: - postgres_data:/var/lib/postgresql/data/ spam-service: build: context: . dockerfile: ./config/local/Dockerfile container_name: spam-service restart: unless-stopped depends_on: - spam-db environment: DEBUG: True APP_ENV: 'LOCAL_DOCKER' BROKER_HOST_NAME: redis-spam POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: spam POSTGRES_HOST: spam-db POSTGRES_PORT: 5432 ports: - '127.0.0.1:8877:8000' The Egg's service is absolutely identical, just replace 'spam' to 'eggs' and ports are also different. How can I connect these two containerized projects so the could send api requests to each other? And what precisely URL I have to use to send such requests. I tried something like this but no success: version: '3' services: ... spam-service: build: context: . dockerfile: ./config/local/Dockerfile container_name: spam-service restart: unless-stopped depends_on: - spam-db environment: ... ports: - '127.0.0.1:8877:8000' networks: &networks - local-network networks: local-network: external: true POST http://spam-service:8877/api/v1/cache/ [2024-03-20 22:04:32,730: ERROR/ForkPoolWorker-4] Error on send data to spam_cachenotok: HTTPConnectionPool(host='spam-service', port=8000): Max retries exceeded with url: /api/v1/cache/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x760d642e54c0>: Failed to establish a new connection: [Errno 111] Connection refused')), url: http://spam-service:8001/api/v1/cache/, data: {'blah': 'blah'} What am I doing wrong? -
Django Sessions not saving between different views/api's
the session data isnt saving from one view to another: in one view I have this: try: df = pd.read_excel(excel_file) request.session['dataframe'] = df.to_json() Then in another view: if 'dataframe' not in request.session: print("Session is Currently Empty") df_json = request.session.get('dataframe') # Access file from session cache if not df_json: print('not df_json') return JsonResponse({'error': 'No data available'}, status=404) The settings/Middleware should be right. and I added additional lines like .save and modify = true and still nothing. this is my first time using django, if anyone has tips or advice pls lmk -
Hosting a django-rest api on hostinger
I have a project which uses django as a backend, I wish to deploy it on hostinger, anyone has already done this before? I searched alot and didn't find much help, if someone already knows, please write me the steps to successfully deploy the django backend app to hostinger I searched alot and didn't find someone who did this before -
Creating one common model`s field both for email and telegram nickname depending on user's authorization way in Django(DRF)
I have been struggling with a task for two days and can not find an appropriate solution, so I would be very grateful for any help. The task is as follows: when a user logs in via Yandex/Google (I use drf_social_auth2), upon saving them in the database, the value of the username field becomes the user's email address. However, when logging in via Telegram, the value of the same username field should be the user's Telegram nickname. The first part is implemented through the USERNAME_FIELD attribute and the get_username method. The question is, how can we accomplish the second part, so that the username equals the Telegram nickname? One option I considered was using the username field from parent AbstractUser model to store the necessary value depending on the method, but there's an issue with the fact that drf_social_oauth2, which I use for authorization, saves the email as the email value, and I can't find ways to make it save email to username field. Here is the code for my User: class User(AbstractUser, TimeStampedUUIDModel, PermissionsMixin): # First and last name do not cover name patterns around the globe name = CharField(_("Name of User"), blank=True, max_length=255) email = EmailField(_("email address"), unique=True) … -
Wagtail field change does not show up in Page Revisions
I have a field on a Wagtail Page model(BlogPage) that is a m2m to a Django model(ExternalAuthor). When this field is changed(i.e adding or removing an ExternalAuthor) to a BlogPage, this change is NOT logged in the page revision. I'm wondering if I need to extend from something specific or somehow enable this feature somewhere for this specific field to force a log entry to the page revision? The client would like to see this change as they have multiple people making content updates, and need to know who is adding/removing these ExternalAuthors from a BlogPage. -
django DRF permission_classes = isAuthenticated not working as intended
I am using drf 3.14.0 and simple_jwt for my logging. The authentication seems to work well when i enter a valid token, but permission classes doesn't stop a an AnonymousUser from acceding my view. settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'users.authentification.CustomJWTAuth', ) } view class UserViewSet(viewsets.ViewSet): def list(self, request): permission_classes = [IsAuthenticated] print(request.user.is_authenticated, file=sys.stderr) u_serializer = GetUserSerializer(request.user) user_data = JSONRenderer().render(u_serializer.data) return Response(user_data, 200) When i do an api call without a valid user and the following view the call enters list and prints me false on request.user.is_authenticated, which shouldn't be possible I believe. I welcome any ideas -
I'm getting incorrect values when counting annotations
When I filter with one or two tags, the number of likes is displayed correctly. However, if I filter by three tags, the number of likes is multiplied by the number of tags associated with the question. Otherwise, the function works correctly. The like values themselves do not change in the database def tagAndFilter(request): tags_string = request.GET.get('tags', None) if tags_string: tags_list = [tag.strip() for tag in tags_string.split(',') if tag.strip()] tags = QuestionTag.objects.filter(name__in=tags_list) questions = Question.objects.filter(tags__in=tags).distinct() questions = questions.annotate(likescount=Count('likes')) context = { 'questions': questions } return render(request, 'question/category.html', context) models.py class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='likes') created_at = models.DateTimeField(auto_now_add=True) as I understand it, the “multiplication” of results occurs in the line questions = questions.annotate(likescount=Count('likes')) -
can't install psycopg2 in windows
ERROR: Command errored out with exit status 1: 'C:\Users\computer\AppData\Local\Programs\Python\Python36\python.exe' -u -c 'import io, os, sys, setuptools, to kenize; sys.argv[0] = '"'"'C:\Users\computer\AppData\Local\Temp\pip-install-tcmjfuu0\psycopg2_9679e782c5f144bdbc57c64ce0e24caf\setup.py'"'"'; file ='"'"'C:\Users\computer\AppData\Local\Temp\pip-install-tcmjfuu0\psycopg2_9679e782c5f144bdbc57c64ce0e24caf\setup.py'"'"';f = getattr(tokenize, '"'"'ope n'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\computer\AppData\Local\Temp\pip-record-iw5_prz4\install-reco rd.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\computer\AppData\Local\Programs\Python\Python36\Include\psycopg2' Check the logs for full command output. I tried, pip install psycopg2 pip install psycopg2- binary pip install pipwin pipwin install psycopg2 pip3 install psycopg2 python -m pip install -U pip python -m pip install psycopg2 py -m pip install "psycopg2 -
updating user in test function
I am facing an issue with a failure while trying to update an instance of worker in test function. Each time I try to transmit worker data in post method like: response = self.client.post(url, worker_2) it fails to update in my case I just change an email. In a debugger terminal it displays a mistake like "two password field didn't match". But it's very strange because I didn't transfer 2 password within input data, just initially retreiving worker from database with existing password, changing email, and transferring this data as inputs in post method. And so it showed that this field "email" was not changed. How can I effectively fix this problem? I tried to drop password after retreiving a worker from database and then set "password1" + "password2" for this worker. But unfortunately it didn't work. I have no any clear idea what actions can I undertake else to achieve a result - to update this object. -
I cannot authenticate user with the jwt token in my django project
I'm trying to authenticate a user with jwt token generated in the login view, while copying the jwt token and adding it into the headers for authorization it says: { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } class loginapi(APIView): def post(self, request): try: data = request.data serializer = LoginSerializer(data=data) if serializer.is_valid(): email = request.data['email'] password = request.data['password'] user = CUser.objects.filter(email=email).first() #check for user. if user is None: return Response({ 'status':400, 'message':'User not found', 'data': {} }) if not user.check_password(password): return Response({ 'status':400, 'message':'Wrong password', 'date': {} }) payload = { 'id': user.id, 'exp': timezone.now() + datetime.timedelta(minutes=60), 'iat': timezone.now() } token = jwt.encode(payload, 'secret', algorithm='HS256') #token_string = token.decode('utf-8') response = Response() response.set_cookie(key='jwt', value=token, httponly=True) response.data = { 'jwt':token } return response return Response({ 'status':400, 'message':'Something went wrong', 'date': serializer.errors }) except Exception as e: return Response({'message': str(e)}, status=400) class userapi(APIView): def get(self, request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('Unauthenticated') try: payload = jwt.decode(token, 'secret', algorithms=\['HS256'\]) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated') user = CUser.objects.filter(id=payload\['id'\]).first() serializer = UserSerializer(user) return Response(serializer.data) these are my login and user views -
Publish messages to MQTT using Celery-Beat scheduled tasks
I am developing a Django+Vue web application along with an MQTT server. I want to implement Celery Beat to execute scheduled tasks, which I define in the "calendarios" models where I input the tasks according to the date, interval, repetition, and others. In "eventosCalendarios," I save each task with the time and date to execute. What I aim for is that upon executing each task, I can publish to a specific topic on the MQTT server. Models.py class calendarios(models.Model): nombre=models.CharField(max_length= 100, verbose_name='Nombre', unique=True) acciones=models.ForeignKey(acciones, null=True,blank=True,on_delete=models.CASCADE,verbose_name='Acciones') fecha_inicio = models.DateField(null=True, blank=True) fecha_fin = models.DateField(null=True, blank=True) repeticion= models.CharField(max_length=1, choices=repeticionChoices, default='D') # Ej: 'diaria', 'semanal', 'mensual' intervalo = models.IntegerField(null=True, blank=True) # Número de días, semanas o meses dependiendo de la repeticion todoCultivo= models.CharField(max_length=1, choices=SioNO, default='S') hora_repeticion_1 = models.TimeField(null=True, blank=True) # Hora de la primera repetición diaria hora_repeticion_2 = models.TimeField(null=True, blank=True) # Hora de la segunda repetición diaria hora_repeticion_3 = models.TimeField(null=True, blank=True) cultivo=models.ManyToManyField(cultivo, verbose_name="Cultivos",blank=True) plantas=models.ManyToManyField(plantas, verbose_name="Plantas",blank=True) def __str__(self): return self.nombre class Meta: verbose_name = 'Calendario' verbose_name_plural = 'Calendarios' db_table = 'calendarios' ordering = ['id'] class eventosCalendarios(models.Model): title = models.CharField(max_length=100) start = models.DateTimeField() calendario = models.ForeignKey(calendarios, on_delete=models.CASCADE) allDay = models.BooleanField(default=False) def __str__(self): return self.title class Meta: verbose_name = 'Evento calendario' verbose_name_plural = 'Eventos calendarios' db_table = … -
getting rank of specific user with windows function in djago
this is my query which gives me the ranking of all user: rank = Wallet.objects.filter(type=0, space_id=space.id).annotate( rank=Window( expression=DenseRank(), order_by=F('point_amount').desc(), ) ).order_by('rank').values("user__id","user__username","rank") but how can i get rank of specific user in this query?(i don't want to handle this whit python) i already try this: rank = Wallet.objects.filter(type=0, space_id=space.id, user_id=user.id).annotate( rank=Window( expression=DenseRank(), order_by=F('point_amount').desc(), ) ).order_by('rank').values("user__id","user__username","rank") but it gives me rank 1 which is not correct note: this raw query gives me the right answer but i don't konw how to convert this in to django orm query query = f''' SELECT FIND_IN_SET( `transaction_wallet`.`point_amount`, ( SELECT GROUP_CONCAT(`transaction_wallet`.`point_amount` ORDER BY `transaction_wallet`.`point_amount` DESC) FROM `transaction_wallet` WHERE `transaction_wallet`.`type` = 0 AND `transaction_wallet`.`space_id` = {space.id} ) ) AS `rank` FROM `transaction_wallet` WHERE `transaction_wallet`.`type` = 0 AND `transaction_wallet`.`space_id` = {space.id} AND `transaction_wallet`.`user_id` = {self.id}; ''' ``` -
KeyError in Django 'id_user'
Here, i have to take a user id from the url and use it to search for the user in the Profile model and return it , but when username = self.kwargs['id_user'] runs, it gives the KeyError VIEWS class SearchUser(generics.ListAPIView): serializer_class = ProfileSerializer queryset = Profile.objects.all() def list(self, request, *args, **kwargs): username = self.kwargs.get['id_user'] logged_in_user = self.request.user users = Profile.objects.filter(Q(user__username__icontains=username)) if not users.exists(): return Response( {"detail": "No users found."}, status=status.HTTP_404_NOT_FOUND ) serializer = self.get_serializer(users, many=True) return Response(serializer.data) SEERIALIZER class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields=['id','user', 'id_user', 'department', 'degree', 'year', 'bio','profileimg'] MODELS class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() department= models.CharField(max_length=50,blank=True) degree= models.CharField(max_length=20,blank=True) year= models.CharField(max_length=20,blank=True) bio = models.TextField(blank=True) profileimg= models.TextField(blank=True) def __str__(self): return self.user.username URLS path("search/<username>/", views.SearchUser.as_view()) -
How reset Django DB? (ValueError: The field <field> was declared with a lazy reference to <app.model>, but app <app> doesn't provide model <model>.)
The Problem I'm using Django and I was having the error after attempting manual fixes on the migrations folder.: ValueError: The field API_Materials.ModelParams.material_param was declared with a lazy reference to 'API_Materials.materialparams', but app 'API_Materials' doesn't provide model 'materialparams'. The structure in models.py for those two classes cited in the error mensage ("MaterialParams", and "ModelParams") is: class MaterialParams(models.Model): material = models.ForeignKey(Material, models.CASCADE, related_name='params') name = models.CharField(max_length=50) submitted_by = models.ForeignKey(User, models.SET_NULL, null=True, related_name='material_params') class ModelParams(models.Model): model = models.ForeignKey(Model, models.CASCADE, related_name='params') material_param = models.ForeignKey(MaterialParams, models.CASCADE, related_name='model_params') submitted_by = models.ForeignKey(User, models.SET_NULL, null=True, related_name='params') params = models.JSONField() # {"x": 10, "z": 40, "output_do_outro" : 30} // {"input": [12, 1, 3.4], "output":} class Meta: constraints = [ models.UniqueConstraint(fields=['model', 'material_param'], name='unique_model_params') ] Attempts As usual with migrations, I tried to comment those classes, create a makemigrations, and then uncomment, but it didn't work. I also attempted to comment the "material_param" with the constraints in "ModelParams", but with the same result. Looking for similar questions in Stack Overflow, usually they were related to the User or by the lack of "Model.models" heritance. Later I deleted the "ModelParams" table in the DB Server to attempt to remove this error, but without positive results. At some point, I tried to … -
How can i filter by many-to-many field in other table Django ORM?
My models: class Job: id = models.UUIDField() name = models.CharField() category = models.UUIDField() class JobReviewers: user_id = models.UUIDField() name = models.CharField() categories = models.ManyToManyField(Category, related_name='reviewers') class Category: id = models.UUIDField() I want to filter all job's where user is reviewer for job with name and category user_id = uuid.uuid4() all_jobs = Job.objects.all() jobs_where_user_is_reviewer = ... If it'll be filter just by name without category i can write this: job_names_where_user_reviewer = JobReviewers.objects.filter(user_id=user_id).values('name', flat=True) jobs_where_user_is_reviewer = all_jobs.filter(name__in=job_names_where_user_reviewer) How can i do this with categories m2m field? -
Error connecting gitlab ci pipeline to redis service
I have been having issues connecting my redis to my gitlab ci to run some tests I keep getting this error Error -2 connecting to redis:6379. Name does not resolve This is my docker-compose.yml section for redis redis: image: "redis:alpine" and this is my .gitlab.ci file image: docker:19.03.5 services: - docker:19.03.5-dind - redis:latest stages: - Build - Push variables: APK_CACHE: "/etc/cache/apk" REDIS_PORT: 6379 REDIS_HOST: redis REDIS_URL: redis://redis:6379 before_script: - apk add python3 - apk add --update docker-compose - docker-compose run --rm app sh -c "python manage.py migrate && python manage.py test --parallel" Build: stage: Build before_script: [] script: - mkdir data/ - docker build --compress -t ecr_image . - docker save --output data/image.tar ecr_image artifacts: name: image paths: - data/ -
Django test TypeError: Field 'id' expected a number but got ()
I got this error 3 times in my code. I searched on other question and I didn't find anything that worked. Does anyone have any idea? Thank you. models.py class Exam(models.Model): code = models.CharField(max_length=50) name = models.CharField(max_length=100) semester = models.IntegerField(default=1) year = models.CharField(max_length=9) users = models.ManyToManyField(User, blank=True) test_models.py class ExamModelTestCase(TestCase): def setUp(self): self.user = User.objects.create(username='test_user', first_name='Test', last_name='User') self.exam = Exam.objects.create(code="EXAM1", name="Exam 1", semester=1, year="2024") error Found 12 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). .....EEEEEE. ====================================================================== ERROR: test_exam_str_method (examc_app.tests.test_models.ExamModelTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/lucile/examreview/venv/lib/python3.10/site-packages/django/db/models/fields/__init__.py", line 2053, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a real number, not 'tuple' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/lucile/examreview/examc_app/tests/test_models.py", line 9, in setUp self.exam = Exam.objects.create(id="1", code="EXAM1", name="Exam 1", semester=1, year="2024") TypeError: Field 'id' expected a number but got (). -
antd Global color setting
I am new to antd and need to set the global theme to one of the antd colour palettes. I am building an app using Django, React and antd. I have installed the colours package: npm install @ant-design/colors --save Then I added the palette to my Layout.js file, my default layout: import { purple } from '@ant-design/colors'; Which shows up in the console console.log(purple); console.log(purple.primary); I am struggling with how to make this override the default colours and display the purple ones. I have tried to include in the theme: const theme = { primary: purple[5] }; I have also tried to add to the token: const { token: { purple, colorBgContainer, borderRadiusLG }, } = theme.useToken(); -
Unable to migrate in Second Multi database in Django
I have implemented multi-DB concept inside my Django project where for whole project i am using default db and for User I am using separate DB here are the settings.py file configs: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': default_db, 'USER': env('DB_USER'), 'PASSWORD': env('DB_PASSWORD'), 'HOST': env('DB_HOST'), 'PORT': env('DB_PORT'), }, 'auth_db': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'user_auth_db', 'USER': env('DB_USER'), 'PASSWORD': env('DB_PASSWORD'), 'HOST': env('DB_HOST'), 'PORT': env('DB_PORT'), }, } # ADDING ROUTE TO SPECIFY DB ROUTING SPECIFIC user RELATED CHANGES TO REFLECT Into auth_db database not inside default db DATABASE_ROUTERS = ["main_Project_directory.db_routers.UserAuthRouter"] Now this is the db_routers.py file class UserAuthRouter: """ A router to control all database operations on models in the auth and contenttypes applications. """ route_app_labels = {"auth_user", 'contenttypes'} # Apps to be include inside auth_db def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return "auth_db" return None def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return "auth_db" return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth or contenttypes apps is involved. """ if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label …