Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM - How to concatenate or Group ManyToMany field values in queryset
I am building my first Django App, am very new to it and have come undone trying to handle instances where a field has multiple values in a queryset. My specific example is that I am trying to fetch all unique machine_name's with their most recent handover_id and the handover model's associated fields. ct_limitations is a ManyToManyField in the handover model and contains multiple values - Whilst I am expecting only 5 unique machines, one of which has two ct_limitations, I get a new row for each ct_limitaion value as below: MySQL Screenshot Any assistance or pointers would be greatly appreciated My code as follows: Models.py from django.db import models from django.contrib.auth.models import User # Machine Type class MachineType(models.Model): machine_type = models.CharField(max_length=50, blank=True) def __str__(self): return str(self.machine_type) # Purpose class Purpose(models.Model): purpose = models.CharField(max_length=50, blank=True) def __str__(self): return self.purpose class Meta: # Add verbose name verbose_name_plural = 'Purposes' # Status class Status(models.Model): status = models.CharField(max_length=50, blank=True) def __str__(self): return self.status class Meta: # Add verbose name verbose_name_plural = 'Statuses' # CT Limitations class CTLimitations(models.Model): ct_limitations = models.CharField(max_length=50, blank=True, verbose_name='CT limitations') def __str__(self): return self.ct_limitations class Meta: # Add verbose name verbose_name_plural = 'CT limitations' # Machine class Machine(models.Model): machine_name = … -
django.urls.reverse doesn't work as expected
I set urls at project level: urlpatterns = [ url(r'^$', homepage_view, name='index'), ] urlpatterns += [ ... url(r'^system_notifications/$', SystemNotificationsView.as_view(), name='system_notifications'), url(r'^script_runner/$', ScriptRunnerView.as_view(), name='script_runner'), ] ... And there is no urls set at app level. SystemNotificationsView and ScriptRunnerView are placed in the same app. View: class ScriptRunnerView(View): def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: return {} When I try in test do this: reverse('script_runner') I got: django.urls.exceptions.NoReverseMatch: Reverse for 'script_runner' not found. 'script_runner' is not a valid view function or pattern name. but reverse('system_notifications') works well. How to set urls for script_runner correctly? -
NextJS Images replaces each other
I got so strange problem with NextJS Images. I use Django as my backend server and fetching data and Image URLs from Django in my NextJS project. Look import React, { FC, Suspense } from 'react'; import Link from 'next/link'; import Loader from '../Loader'; interface ProducerClientProps {} async function getProducers() { let res = await fetch(`http://localhost:8000/api/market/producers`); return res.json(); } const ProducerClient: FC<ProducerClientProps> = async ({}) => { const data = await getProducers(); return ( <aside className="min-w-max flex flex-col gap-5"> <div className="grid grid-cols-2"> {data.map((producer: Producer) => ( <div className="flex justify-center"> <Link href={`/producers/${producer.slug}`} className="flex items-center" > <div className="hover:scale-105 transition-transform duration-100 p-5"> <Image src={producer.image === null ? '/' : producer.image} alt={producer.title} width={80} height={80} style={{ objectFit: 'contain' }} /> </div> </Link> </div> ))} </div> </aside> ); }; export default ProducerClient; So in this code my Images replaces each other sometimes and even doubles. Like if I have Image_1.png, so I could see Image_1.png instead of Image_2.png in mapped data. Feels like observer effect, because when I make breakpoints in DevTools - everything works fine. Optimized Image Unoptimized Image (how it should look) Then I have Carousel component. import Image from 'next/image'; import React, { FC, useState } from 'react'; import Loader from '../Loader'; interface … -
celery issue while running periodic task via admin dashboard
I have setup celery on my server and tasks are running fine if we send them by command line but from admin dashboard the task hits are not coming in the celery worker logs. How can we fix it? i tried to run a periodic task from the admin dashboard -
Django. Console error 404 wpad.dat windows
Django console: Not Found: /wpad.dat [23/Jun/2023 12:31:18] "GET /wpad.dat HTTP/1.1" 404 2537. This error is sent to the console every 10 seconds I have not found any information on this error how to remove/fix this error -
Updating the file contents of a Django FileField during upload results in I/O error
I'm trying to encrypt the contents of a file that is being uploaded. This is the relevant code snippet: class AppFile(models.Model): app_file = models.FileField(upload_to=upload_to, validators=[validate_file_size]) encrypted_data_key = models.CharField(max_length=500, blank=True) def encrypt_file_with_data_key(self, data_key): cipher = Fernet(data_key) with self.app_file.open(mode='rb') as file: file_data = file.read() encrypted_data = cipher.encrypt(file_data) with self.app_file.open(mode='wb') as encrypted_file: encrypted_file.write(encrypted_data) def save(self, *args, **kwargs): if self._state.adding is True: # New image being uploaded encrypted_data_key, data_key = self.generate_data_key_from_vault() self.encrypted_data_key = encrypted_data_key # Encrypt the uploaded image file self.encrypt_file_with_data_key(data_key) super().save(args, kwargs) I prefer this approach as this is agnostic of the StorageProvider being used. I also want to avoid detaching the file to a temporary folder, and re-attach it after encryption. However, this results in the following error: Traceback (most recent call last): File "/Users/jeroenjacobs/.pyenv/versions/myapp/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/jeroenjacobs/.pyenv/versions/myapp/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/jeroenjacobs/.pyenv/versions/myapp/lib/python3.11/site-packages/django/views/generic/base.py", line 84, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/jeroenjacobs/.pyenv/versions/myapp/lib/python3.11/site-packages/django/views/generic/base.py", line 119, in dispatch return handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/jeroenjacobs/.pyenv/versions/myapp/lib/python3.11/site-packages/django/views/generic/edit.py", line 184, in post return super().post(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/jeroenjacobs/.pyenv/versions/myapp/lib/python3.11/site-packages/django/views/generic/edit.py", line 153, in post return self.form_valid(form) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/jeroenjacobs/.pyenv/versions/myapp/lib/python3.11/site-packages/django/contrib/messages/views.py", line 12, in form_valid response = super().form_valid(form) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/jeroenjacobs/.pyenv/versions/myapp/lib/python3.11/site-packages/django/views/generic/edit.py", line 135, in … -
Python, django. Hierarchy in a tree-like structure
I'm using Python and Django. How can I create a web page that displays the employee hierarchy in a tree-like structure? For example: Employee-1 (Manager -) Employee-2 (Manager:Employee-1) Employee-3 (Manager :Employee-2) Employee-4 (Manager:Employee-3) Employee-5 (Manager :Employee-1) Employee-6 (Manager:Employee-5) Employee-7 (Manager :Employee-6) Employee-8 (Manager:Employee-5) Currently, my code looks like this: models.py: class Employee(models.Model): name = models.CharField(max_length=100) position = models.CharField(max_length=100) hire_date = models.DateField() salary = models.DecimalField(max_digits=8, decimal_places=2) manager = models.ForeignKey('self', on_delete=models.CASCADE, related_name='subordinates') How can views.py and the employee_hierarchy.html template look like? And where is the best place to implement the logic: in the model, view, or template? Thank you in advance! I tried the following code in views.py: def employee_hierarchy(request): employees = Employee.objects.select_related('manager').all() return render(request, 'employees/employee_hierarchy.html', {'employees': employees}) employee_hierarchy.html: <body> <h1>Employee Hierarchy</h1> <ul> {% for employee in employees %} {% include 'employees/employee_item.html' with employee=employee %} {% endfor %} </ul> </body> employee_item.html: <li>{{ employee.name }} ({{ employee.position }}) - Manager: {% if employee.manager %}{{ employee.manager.name }}{% endif %}</li> {% if employee.subordinates.all %} <ol> {% for subordinate in employee.subordinates.all %} {% include 'employees/employee_item.html' with employee=subordinate %} {% endfor %} </ol> {% endif %} I obtained the following result: Employee-2 - Manager: Employee-1 Employee-3 - Manager: Employee-2 Employee-3 - Manager: Employee-2 Employee-4 - Manager: Employee-1 … -
Django MPTT get descendants subquery
I am trying to get the same queryset I would get if I used get_queryset_descendants(queryset, include_self=True) without losing the queryset (keeping it as a subquery). Because of how get_queryset_descendants works, the queryset is being resolved and is not being a part of a subquery. If I do this, Model.objects.filter(id=1) is not being used as a subquery - I won't be able to use OuterRef("pk") descendants = Model.tree.get_queryset_descendants( Model.objects.filter(id=1), include_self=True, ) print(str(descendants.query)) # id 1 is not part of query Here's a sample of the models I use import django import mptt class Model1(mptt.models.MPTTModel): objects = django.db.models.Manager() tree = mptt.managers.TreeManager() class Model2(django.db.models.Model): model1 = django.db.models.ForeignKey(Model1) I'd like to do something like this: from django.db.models import ( Count, IntegerField, Subquery, ) model1_with_visible_model2 = Model1.objects.annotate( visible_model2_count=Subquery( ( Model2.objects .filter( model1__id__in=( # instead of just model1=OuterRef("pk") Model1.tree.get_queryset_descendants( Model1.objects.filter( # id=6347, # No error id=OuterRef("pk"), # This is my goal ).all(), include_self=True, ) ).values_list("id", flat=True), is_visible=True, ) .distinct() .values("model1") .annotate(count=Count("pk")) .values("count") ), output_field=IntegerField(), ), ) I am not using model1=OuterRef("pk") because model2 instances (even though not directly related to the parent model1 instance) should still be counted as long as they are related to a descendant of the parent model1 instance. -
Got 404 error after adding SSL certificate
I use Django, Docker-compose to create this project. It worked properly before i started to connect SSL certificate. In every page i get 404 error. Nginx wants to get html file but I can't underctend were I should find it. In nginx log i found the following errors: [error] 31#31: *4 open() "/etc/nginx/html/.well-known/acme-challenge/Lyi2pfq05iW1lx8c75fguhZ38nOnzLEY6jE7Dwh49x4" failed (2: No such file or directory), client: 18.223.43.49, server: plantsfinder.net, request: "GET /.well-known/acme-challenge/Lyi2pfq05iW1lx8c75fguhZ38nOnzLEY6jE7Dwh49x4 HTTP/1.1", host: "plantsfinder.net", referrer: "http://plantsfinder.net/.well-known/acme-challenge/Lyi2pfq05iW1lx8c75fguhZ38nOnzLEY6jE7Dwh49x4" "GET /plants/deciduous/ HTTP/1.1" 404 555 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" "-" 2023/06/22 15:50:19 [error] 31#31: *7 "/etc/nginx/html/plants/deciduous/index.html" is not found (2: No such file or directory), client: 5.29.13.184, server: plantsfinder.net, request: "GET /plants/deciduous/ HTTP/1.1", host: "plantsfinder.net" I do not understand were this html files should be. URL from django.urls import path from . import views app_name = 'plants' urlpatterns = [ path('<str:category>/', views.plants_list, name='plants_list'), ] view function: def plants_list(request, category): """Creates plant selection pages.""" template = 'plants/finder.html' filters = request.GET plant_type_model = PLANTS_TYPES[category] category_verbose_name = plant_type_model._meta.verbose_name_plural.title() plants = plant_type_model.objects.all() filters_min_max = {} if filters: plants, filters_min_max = filter_plants(plants, filters) page_obj, pagination = get_pagination(request, plants, PLANTS_PER_PAGE) context = { 'request': request, 'plant_category': category, 'category_verbose_name': category_verbose_name, 'plants': page_obj, 'fields': plant_type_model.fields, 'filters': filters_min_max, … -
how to run a python selenium celery task as asnyc task when celery is up and ready to work in Windows?
I need to run a celery task when the Celery is started (at start up) and it's ready to work in a Django environment. I have more than 5 celery tasks and those are running parallel without problem. but when i call Selenium task below, other tasks are paused and after Selenium task is done, other 5 tasks continue their work. selenium task must works as async forever in a While True: ... block code and this task tries to login to a website and do something on logged-in account. the selenium task should not have pause impact on other tasks are running. this selenium task just should be called one time. itself has While True:... loop code. celery.py: import os, redis from celery import Celery from celery.schedules import crontab celery_app = Celery('ea_games') celery_app.config_from_object('django.conf:settings', namespace='CELERY') celery_app.control.discard_all() celery_app.control.purge() celery_app.autodiscover_tasks() BASE_REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379') celery_app.conf.broker_url = BASE_REDIS_URL celery_app.control.discard_all() celery_app.control.purge() tasks.py: ## when Celery is launched and it's ready to work, it will run the ```task_get_selenium_token``` task. @worker_ready.connect def at_start (sender, *args, **kwargs): with sender.app.connection() as conn: sender.app.send_task("ea_app.tasks.task_get_selenium_token", args, connection=conn) @celery_app.task def task_get_selenium_token(): get_token() ## this python function works permanently in a ```While True:...``` code. Note: i tried to do it with celery-beat. … -
Why does Railway tell me it can't find the start command
I'm doing a tutorial on MDN and I'm getting to the implementation part. I need to upload my GitHub project to Railway. Only Railway gives me this error: Using Nixpacks Nixpacks build failed ╔═══════════════════════════════ Nixpacks v1.9.0 ══════════════════════════════╗ ║ setup │ python310, gcc ║ ║──────────────────────────────────────────────────────────────────────────────║ ║ install │ python -m venv --copies /opt/venv && . /opt/venv/bin/activate ║ ║ │ && pip install -r requirements.txt ║ ║──────────────────────────────────────────────────────────────────────────────║ ║ start │ ║ ╚══════════════════════════════════════════════════════════════════════════════╝ Error: No start command could be found I have to admit that I'm a beginner and I'm also working on Windows, and I haven't had a chance to test the server in production locally (gunicorn doesn't run on windows). Can you tell me what I'm doing wrong? Thanks. MDN tutorial: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment GitHub repository: https://github.com/mihaiparpalea/locallibrary I followed the instructions in the tutorial exactly. -
Automate Company selection after login in Quickbooks
I have to authenticate QuickBooks in flask. all things are working proper. But once generate AUTH URL run that URL in browser, then need to select company. is there any way to skip company selection or automate company select. I don't want to select company. enter image description here I don't want this screen, How can I select company auto? -
How to make complex query? | ChartJS and Django
I have a chart created using Chart JS library below: My models.py below: class Organization(models.Model): name = models.CharField(max_length=250, unique=True) def __str__(self): return self.name class AppealForm(models.Model): form_name = models.CharField(max_length=100) def __str__(self): return self.report_form_name class Appeal(models.Model): organization = models.ForeignKey(Organization, on_delete=models.SET_NULL, blank=True, null=True) appeal_form = models.ForeignKey(AppealForm, on_delete=models.CASCADE, blank=True, null=True) appeal_number = models.CharField(max_length=100, blank=True, null=True) applicant_first_name = models.CharField(max_length=100, blank=True, null=True) applicant_second_name = models.CharField(max_length=100, blank=True, null=True) date = models.DateField(blank=True, null=True) appeal_body = models.TextField() Script of Chart JS used to create choosen line graph: new Chart(chartTwo, { type: 'line', data: { labels: ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'], datasets: [ { label: 'written', data: [ Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), ], borderColor: "green", backgroundColor: "green", }, { label: 'oral', data: [ Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), ], borderColor: "blue", backgroundColor: "blue", }, ] }, options: { responsive: true, scales: { y: { min: -20, max: 120, } } }, }) Qestion: how the query will look like for this graph using AppealForm model? P.s. I want to get a count of each AppealForm model … -
Saving images from Django Quill Editor to Amazon S3?
I'm working on a Django project and using the Quill Editor for rich text editing. I want to allow users to insert images into the editor and save them to an Amazon S3 bucket. I have successfully set up the integration with S3 for other file uploads, but I'm unsure how to handle the image upload specifically from the Quill Editor. I am using Django Admin along with Django Quill Editor, specifically the QuillField(), in my project. I would like to store images uploaded through the Quill Editor directly in an Amazon S3 bucket. Can someone please guide me on how to configure and implement this functionality? I would appreciate any instructions or code examples related to configuring S3 and handling image uploads from the Quill Editor in Django Admin. -
Suggest Front-End Technology for Django monolith Site to Webservice architecture Conversion
Converting Django monolith Site to Webservice architecture. Which front-end tecnology I sould use. Few in my mind are Angular: Framework, with most of the features inbuilt, but steep learning curve React: Liberary, easy to start with, lots of package available Vue: Quick and easy implemenation. Major selection factors are easy to implement and future prospects Please suggest I tried with angular, found it steep learning curve, vue.js is good but not very popular and react.js is library, which require additional package installation for site to work. -
Django: ordering numerical and string value with order_by
My problem is, that obviously the data is ordered by UTF-8 codes since it's a Charfield, with the predictable results .. it sort the data like this; My Data is: 1,8,7,2a, 4, 2, 11, 10... I want this ordered list: 1,2,2a,4,7,8,10,11 .. I really don't know how I can order this properly .. -
Typeerror at /blog/: expected string or bytes-like object, got 'QuerySet'
I am Trying To Create A Basic Blog Website with multiple urls working in django. For the Blog Page I have created a Custom template tag which will return the first few words from the content data of blog from Models. But when i am trying to execute it always displaying the same error 'expected string or bytes-like object, got 'QuerySet' This Is My :Models.py from django.db import models # Create your models here. class blogdata(models.Model): post_id=models.AutoField(primary_key=True) title=models.CharField(max_length=50,default="") heading=models.CharField(max_length=500 ,default="") content=models.CharField(max_length=900 ,default="",null=True) date=models.DateField() thumbnail=models.ImageField(upload_to='static/',default="") def __str__(self): return self.title This is my post_tags.py import re from django import template from ..models import blogdata register=template.Library() @register.simple_tag def FewFirst(): my_str=blogdata.objects.values_list('content') result = re.findall(r'\w+', my_str)[:10 ] result = " ".join(result) return result Note: Directory structure and file names are correct idk the main reason behind this error -
Jenkins unable to connect to github private repo
I'm running Jenkins on an AWS Amazon Linux 2 EC2 instance. I have setup the instance and have jenkins running as well. I'm currently trying to add the job to deploy my private repo (Django web app) to the EC2 instance. I have used ssh-keygen and placed the public key in my github SSH keys and the private key in my credentials within Jenkins. I have been researching and almost every source does exactly what I've been doing. Any ideas on how to resolve this? I know that github changed some of their login capabilities in the last few years, so i'm not sure if these posts are outdated. This is the error I'm getting You can see my credentials config below: And my github ssh key here: -
Django nested OuterRef
Trying to understand and get working nested OuterRef on simple example (just for this test) class User(AbstractUser): pass class Issue(models.Model): due_date = models.DateField() class UserIssue(models.Model): issue = models.ForeignKey(Issue, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) assigned_to = models.DateField() class Calendar(models.Model): calendar_date = models.DateField() @classmethod def report(cls): main_qs = cls.objects.all() second_subquery = ( Issue.objects.filter(due_date=OuterRef(OuterRef("calendar_date"))) .values("due_date") .annotate(count=Count("due_date")) .values("count") ) first_subquery = ( UserIssue.objects.filter(assigned_to=OuterRef("calendar_date")) .annotate(today_due_date=Sum(second_subquery)) .values("today_due_date") ) qs = main_qs.annotate(today_due_date=first_subquery) print(qs.query) return qs When call Calendar.report() got django.db.utils.ProgrammingError: column "users_calendar.id" must appear in the GROUP BY clause or be used in an aggregate function and have no idea how to fix it. Printed SQL is SELECT "users_calendar"."id", "users_calendar"."calendar_date", (SELECT SUM((SELECT COUNT(U0."due_date") AS "count" FROM "users_issue" U0 WHERE U0."due_date" = ("users_calendar"."calendar_date") GROUP BY U0."due_date")) AS "today_due_date" FROM "users_userissue" V0 WHERE V0."assigned_to" = ("users_calendar"."calendar_date") GROUP BY V0."id") AS "today_due_date" FROM "users_calendar" and when manually add GROUP BY "users_calendar"."id"; then it works so my question is how to achieve the same using ORM? Thanks -
Elastic BeansTalk: Yum does not have this package available for installation
this is 01_packages.config file inside .ebextensions folder packages: yum: git: [] postgresql93-devel: [] commands: 01_python_devel_install: command: 'yum install -y python39-devel' 02_postgresql_install: command: 'yum install -y postgresql93 postgresql93-devel' when i do eb deploy I get error in the logs (cfn-init.txt, to be precise): 2023-06-23 00:34:37,835 [INFO] -----------------------Starting build----------------------- 2023-06-23 00:34:37,853 [INFO] Running configSets: _OnInstanceBoot 2023-06-23 00:34:37,856 [INFO] Running configSet _OnInstanceBoot 2023-06-23 00:34:37,859 [INFO] Running config AWSEBBaseConfig 2023-06-23 00:34:38,510 [INFO] Command clearbackupfiles succeeded 2023-06-23 00:34:38,514 [INFO] Running config AWSEBCfnHupEndpointOverride 2023-06-23 00:34:38,533 [INFO] Command clearbackupfiles succeeded 2023-06-23 00:34:38,535 [INFO] ConfigSets completed 2023-06-23 00:34:38,535 [INFO] -----------------------Build complete----------------------- 2023-06-23 00:36:16,303 [INFO] -----------------------Starting build----------------------- 2023-06-23 00:36:16,309 [INFO] Running configSets: Infra-EmbeddedPreBuild 2023-06-23 00:36:16,311 [INFO] Running configSet Infra-EmbeddedPreBuild 2023-06-23 00:36:16,311 [INFO] ConfigSets completed 2023-06-23 00:36:16,311 [INFO] -----------------------Build complete----------------------- 2023-06-23 00:41:25,793 [INFO] -----------------------Starting build----------------------- 2023-06-23 00:41:25,800 [INFO] Running configSets: Infra-EmbeddedPreBuild 2023-06-23 00:41:25,803 [INFO] Running configSet Infra-EmbeddedPreBuild 2023-06-23 00:41:25,805 [INFO] Running config prebuild_0_backend 2023-06-23 00:41:28,430 [ERROR] postgresql93-devel is not available to be installed 2023-06-23 00:41:28,430 [ERROR] Error encountered during build of prebuild_0_backend: Yum does not have postgresql93-devel available for installation Traceback (most recent call last): File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 579, in run_config CloudFormationCarpenter(config, self._auth_config, self.strict_mode).build(worklog) File "/usr/lib/python3.9/site-packages/cfnbootstrap/construction.py", line 244, in build changes['packages'][manager] = CloudFormationCarpenter._packageTools[manager]().apply(packages, File "/usr/lib/python3.9/site-packages/cfnbootstrap/rpm_tools.py", line 76, in apply raise … -
My modelserializer is not working properly
I had this previoys serializer that was working fine. But i was asked to change it into a model serializer and now it is not passing all tests. This is the original version: from rest_framework import serializers from rest_framework.validators import UniqueValidator from .models import User class UserSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) username = serializers.CharField( validators=[ UniqueValidator( queryset=User.objects.all(), message="A user with that username already exists.", ) ], ) email = serializers.EmailField( validators=[UniqueValidator(queryset=User.objects.all())], ) password = serializers.CharField(write_only=True) full_name = serializers.CharField(max_length=50, required=False) artistic_name = serializers.CharField(max_length=50) def create(self, validated_data: dict) -> User: return User.objects.create_user(**validated_data) def update(self, instance: User, validated_data: dict) -> User: for key, value in validated_data.items(): setattr(instance, key, value) if key == 'password': instance.set_password(value) instance.save() return instance And this is MY version: from rest_framework import serializers from rest_framework.validators import UniqueValidator from .models import User class UserSerializer(serializers.ModelSerializer): def create(self, validated_data): return User.objects.create_user(**validated_data) class Meta: model = User fields =[ "id", "username", "email", "full_name", "artistic_name" ] extra_kwargs = {"password": {"write_only": True}} For some reason, everytime i run tests for my version there're three errors which are: 1# AssertionError: False is not true : Check is password is being updated in PATCH route /api/users/8/ 2# AssertionError: Items in the first set but not the second: E 'password': … -
Python Setup On Windows
Please a Step by Step on Setting Up Python and Installing Django and Running Environment variable i installed python proper added Path and Installed Django but still the my Django is not running properly, it shows Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings -
kombu.exceptions.OperationalError: [Errno 111] Connection refused
I´m trying to use django with celery and rabbitmq on containers Docker. It works well without docker, but when I run on containers I recieve this erro : kombu.exceptions.OperationalError: [Errno 111] Connection refused. Here is my docker-compose: version: '3.4' services: rabbitmq: image: rabbitmq:3.12.0-management container_name: 'rabbitmq' ports: - 5672:5672 - 15672:15672 restart: always celery: build: context: . command: celery -A loan worker --loglevel=info depends_on: - rabbitmq restart: always loan: image: loan build: context: . dockerfile: ./Dockerfile ports: - 8000:8000 depends_on: - rabbitmq - celery I saw some people saying to put from .celery import app as celery_app __all__ = ('celery_app',) on init.py, but I already put on it. -
I'm testing my django project with a pytest. argument of type 'News' is not iterable
While testing content i got TypeError: argument of type 'News' is not iterable There is two asserts in my test. i'm testing detail view of news page for anonymous user 1 checks if the news is in the response context of the page 2 i check ordering by date of comments second part works correctly, but the first gives TypeError: list indices must be integers or slices, not News fixtures: @pytest.fixture def news(): news = News.objects.create( title='Новость', text='Невероятное событие', date=datetime.today(), ) return news @pytest.fixture def two_comments(author, news): now = timezone.now() list_of_comments = [] for index in range(2): comment = Comment.objects.create( news=news, author=author, text=f'Tекст {index}', ) comment.created = now + timedelta(days=index) comment.save() list_of_comments.append(comment) return list_of_comments test code: @pytest.mark.django_db def test_comments_order(two_comments, news, client): detail_url = reverse('news:detail', args=(news.id,)) response = client.get(detail_url) object_list = response.context['news'] assert news in object_list news = response.context['news'] print(news) list_comments = news.comment_set.all() assert list_comments[0]. created < list_comments[1].created code of error: @pytest.mark.django_db def test_comments_order(two_comments, news, client): detail_url = reverse('news:detail', args=(news.id,)) response = client.get(detail_url) > assert news in response.context self = [[{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf.<locals>._get_val at ...'object': <News: Новость>, 'news': <News: Новость>, 'view': <news.views.NewsDetail object at 0x000001CD39C53D30>}, {}]] key = <News: Новость> def __getitem__(self, key): if … -
Dynamic Foreign Key Links in Django Model
I have models in Django. Instances of one of the model can have 'parents' from the same table or any other table within the project or no parents at all. If I pass the parent as an argument to the model class, can I then 'process' the parent in the save() function and set the foreign key value in save()? To clarify, my issue is mainly that I don't know what 'model type' the parent will be, so I need the model am working on to determine this before setting the ForeignKey value. Pseudo code to explain myself: model_instance_being_created = ModelType( parent = parentinstance other_attributes ) model_instance_being_created.save() In models.py: class ModelType(models.Model): #bunch of attributes parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) def save(self, *args, **kwargs): parent_type = self.parent.__class__ self.parent = parent.objects.get(id=self.parent.id) super().save(*args, **kwargs)