Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework Many to Many field data from frontend
models.py class PostCategory(models.Model): name = models.CharField(max_length=200, unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.DO_NOTHING) content = models.TextField() post_categories = models.ManyToManyField(PostCategory, blank=True) def __str__(self): return self.title serializers.py class PostSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) class Meta: model = Post exclude = [] def create(self, validated_data): # Retrieve the currently logged-in user user = self.context['request'].user # Add the author user to the validated data validated_data['user'] = user # Create and return the Post instance post = Post.objects.create(**validated_data) return post views.py class PostCreateView(APIView): def post(self, request): if request.user.is_authenticated: serializer = PostSerializer(data = request.data, context={'request': request}) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Passing Data via POST Method from Frontend FormData(3) { title → "Title 1", content → "Content 1", post_categories → "web framework,javascript"} Hi I am using Django REST Framework and trying to implement many to many relationship. I am sending data from frontend to drf backend Now The Error i am facing is post_categories [ "Incorrect type. Expected pk value, received str." ] Which is obvious I believe the error is correct but i dont know how to fix it. I also think once i fix this i will face another … -
How to configure django braces?
How to configure django braces in my django project after successfully installation? pip install django-braces I have installed successfully but don't know how to configure it in my settings.py file. Please help me out on this. -
name '<Class name>' is not defined error in django
I have started with learning django so while doing it i made a class in models.py named "Members" but when i am trying view/add data from python shell into it, it is giving me the following error: enter image description here heres the code: `from django.db import models class Members(models.Model): firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255) phone = models.IntegerField() joined_date = models.DateField()` `from django.db import models class Members(models.Model): firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255) phone = models.IntegerField() joined_date = models.DateField()` -
Why am i getting less points after reading the .png with OpenCV using imread?
I have wrapper.py which integrates C++ DLL to my python code. While integrating a C++ function that uses OpenCV, i am not getting desired output. The respective function in .DLL returns an object which is obtained as in after implementing imread. After reading the image in python code through the respective function of the DLL file, i getting an array of only 4 values and not all the values of the image which the array should represent. This is a function in .DLL file extern "C" __declspec(dllexport) cv::Mat ReadImage(const char* imagePath) { cv::Mat image; // Attempt to read the image image = cv::imread(imagePath); if (image.empty()) { // Handle the error: Log the error message std::cerr << "Error reading image: " << imagePath << std::endl; } return image; } This is a function which integrates the c++ output in wrapper.py def read_image(image_path): image_data = mydll.ReadImage(image_path.encode('utf-8')) print(type(image_data)) if not image_data: return None else: # Convert LP_c_ulong to a bytes object image_bytes = ctypes.string_at(image_data, ctypes.sizeof(ctypes.c_uint)) # Create a NumPy array from the bytes image_array = np.frombuffer(image_bytes, dtype=np.uint8) print('Image Array : \n', image_array.shape, image_array) image = cv2.imdecode(image_array, cv2.IMREAD_COLOR) print('Image : \n', image) return image_data This is how i am expecting it to work in … -
Django Queryset counting number of rows based on aggregated field condition
I have following model: class Purchase(models.Model): date = models.DateField() cost = models.IntegerField(null=False) ... I need to return amount of purchases for each day, with cost that exceeded its average cost of purchases for this day. i tried using: Purchase.objects.values('date').annotate( avg_cost=Avg('cost', output_field=FloatField() ).annotate( purchases_above=Sum(Case(When(cost__gt=F('avg_cost'), then=1), default=0, output_field=IntegerField())) ) but i get error django.core.exceptions.FieldError: Cannot compute Count('<Case: CASE WHEN <Q: (AND: ('cost__gt', F(avg_cost)))> THEN Value(1), ELSE Value(0)>'): '<Case: CASE WHEN <Q: (AND: ('cost__gt', F(avg_cost)))> THEN Value(1), ELSE Value(0)>' is an aggregate I am doing something wrong? Is this even possible? -
How to Version API requests at the Query Level?
I have set up a Django application with a DRF API and Namespace versioning. Already several services are consuming data from my API. Now I have a table like this: class Province(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField() country = models.ForeignKey() I need to update the country field name to: countryId = models.ForeignKey() I don't want to break the queries of the existing consumers so I implemented logic I thought would allow me to maintain different versions of the API. class ProvinceViewset(viewsets.ReadOnlyModelViewSet) def get_serializer_class(self): if self.request.version == 'v1': return ProvinceSerializerV1 else: return ProvinceSerializerV2 return super().get_serializer_class() class ProvinceSerializerV1(serializers.ModelSerializer): country = serializers.PrimaryKeyRelatedField(source='countryId',read_only=True) class Meta: model = Province exclude = ['countryId'] class ProvinceSerializerV2(serializers.ModelSerializer): class Meta: model = Province fields = '__all__' If my API is queried, this effects the fields that are returned, but it has no impact on the queries required by the API For example: localhost:8000/api/v1/provinces?country=1 Does not work, and the required url to filter by country is still the new format: localhost:8000/api/v1/provinces?countryId=1 { "id": 1, "name": "AB", "country": "CA", } Is there a correct way to version the API such that the expected query parameters are not just the latest fields in the model? -
django ckeditor 5 multi-line toolbar
I'm trying to use django-ckeditor-5 and it works fine, but when I try to make a multiline toolbar and add "-" to the toolbar config nothing happens. here is my config: https://pastebin.com/G52EgEVt As you saw in my config, I did put a "-" before bulleted list, but nothing changes: Here is my models.py: class Post(models.Model): title = models.CharField(max_length=120, null=False, blank=False, verbose_name='عنوان') body = CKEditor5Field(config_name='extends', verbose_name='بدنه') -
Django and React version error issues when using materials library
So i'm following a video on youtube that shows how to make a music controller using django and react. While installing the different packages for react I ran into this issue: log file for the error the exact command that is throwing the error is this: npm install @material-ui/core I tried the solutions given here, but nothing worked for me. can someone point me in the right direction? -
Save form data in Django on each http request
I’m new to web programming and Python. I’m having a Django app with multiple questions, each of which has a form (a text field) placed on a separate page. On top there’s a ribbon with buttons - one for every single question, as well as “save and go to next question” button. The problem: form data is lost when other than “save and go next” button is used. I don’t want to lose form data, I want to save on each page change. What I did: I’m about to finish my prototype where I did a small url scheme change: Before: UID/question_ID_to_be_opened After: UID/question_ID_to_be_opened/previous_question_ID The modified view function shall handle the save of “previous_question_ID”, but this don’t look quite elegant. Shall I use signals, or redirects, or something else? There is an autosave script too, it is based on a timer - perhaps I can trigger it manually? Best regards, Ivan -
Python Django - images not showing in templates
My images won't show up in my templates, but it does display a little 'frame' where the image should be displayed. I've tried several things but won't work. I have the exact same settings in my other project and it works fine there. This is what I'm seeing: result on localhost:8000 My settings.py: from pathlib import Path import os import mimetypes BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-xxxx' DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cvapp', ] 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 = 'collabcenter.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], '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', ], }, }, ] WSGI_APPLICATION = 'collabcenter.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.1/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.1/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.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT= os.path.join(BASE_DIR, 'static') STATICFILES_DIR = … -
Django project. creat new file
when typing in the command line:>django startproject myfirstproject, Gives this error: "Django" is not inside or outside command, executable program, or batch file. how to fix or what can i do? I wanted to create a Django project but it didn't work for me -
Running a .jrxml file using django .Error fill report: Erro fill internal: java.lang.NullPointerException
I am trying to run a .jrxml file to turn it into a .pdf file using a django app that is connected to the database, I keep getting this error: Running a .jrxml file using django .Error fill report: Erro fill internal: java.lang.NullPointerException from pyreportjasper import PyReportJasper from platform import python_version def advanced_example_using_database(): try: input_file = 'C:/Users/m.mostafa/Desktop/loan_data.jrxml' output_file = 'output.pdf' pyreportj=PyReportJasper() con={ 'driver': 'oracle.jdbc.driver.OracleDriver', 'username': 'xxxx', 'password': 'xxxx', 'database':'PREE', } pyreportj.config( input_file, output_file, db_connection=con, output_formats=["pdf", "rtf"], parameters={'python_version': python_version()}, ) pyreportj.process_report() except Exception as e: print(e) -
How to redirect old url to new url while migrating to new site in react and django?
I have an old website and new website built with React and django. I'm in the process of migrating from the old site to the new one and need to implement SEO-friendly URL redirects. There are more that 500 old url that needs to be redirected to new ones. I came to know about redirect apps in django (https://docs.djangoproject.com/en/4.1/ref/contrib/redirects/) but dont get how to achieve it on the frontend. I'm not sure how to properly set up SEO-friendly URL redirects from my old url to the new ones while preserving SEO attributes. If I add all those urls in react and call an API to find where i have to redirect will it affect seo? or is there any better way to do this? -
Issue with Rendering Checkboxes and Labels in Django Template
I'm facing issues in my Django template while trying to create checkboxes for food options. I created a form titled cuisine_choices, and I am able to successfully loop through the selection of food from my template, but its not allowing me to properly display it. When I use the following code: {% for food in cuisine.choices %} <input type="checkbox" name="food">{{ food }} {% endfor %} I encounter an unexpected behavior where I get the correct amount of checkboxes but with no label attached to it. However, when I write the code like this: {% for food in cuisine.choices %} <input type="checkbox" name={{ food }}> {% endfor %} I get the properly labeled checkboxes, except each label ends in ">. For example: Mexican"> Chinese"> Italian"> Indian"> Japanese"> French"> Thai"> Mediterranean"> American"> While trying to figure out what was wrong I tried the following code: {% for food in cuisine.choices %} <input type="checkbox" name="Food">Test {% endfor %} And I got the correct amount of checkboxes, each labeled as "Test". Can someone please explain why this is happening and how I can correctly render checkboxes with their labels in my template? -
Django istartswith performance
I have a model with column "name" and I am running query with istartswith and I am using postgresql. I have added django.db.models.Index with Postgresql opclass Index(fields=('name',), name="partial_name_pat_idx", opclasses=("varchar_pattern_ops",), condition=Q(published=True)) But I can't figure out how do make I make use of index for case insensitive search, I have tried with django model function Upper('name') but it is not supported in fields argument. If I pass Upper(F('name')) in expressions django is restricting me to use opclasses=("varchar_pattern_ops",). Is there any way I can create index for queries with LIKE operator and UPPER function on field name? -
Page not found (404) No Product matches the given query
Page not found (404) “C:\Users\TOSHIBA\Desktop\Miniproject\cake_studio\add_to_cart\1” does not exist Request Method: GET Request URL: http://127.0.0.1:8000/add_to_cart/1 Raised by: django.views.static.serve trying to add product in to the cart, getting this error and not get correct data for my website -
Django Restrict the Parent Foreign key to be set as Itself
I am new to Django, I am trying to create a project where a WBS can have other WBS as their parent. My Problem is that when I open the form for edit, I want to simply not display the self in the WBS drop-down so that it can't be set as self parent to avoid strange recursive relationship. def validate_not_self(value): if value and value == value.parent_wbs: raise ValidationError("A WBS cannot be its own parent.") class WBS(models.Model): name = models.CharField(max_length=100) project = models.ForeignKey(Project, on_delete=models.CASCADE) num = models.IntegerField(default=0) parent_wbs = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='child_wbs', validators=[validate_not_self]) created_on = models.DateTimeField(auto_now_add=True) created_by = models.IntegerField(blank=True, default=0) modified_on = models.DateTimeField(auto_now=True) # This field will be automatically updated on each save modified_by = models.IntegerField(blank=True, default=0) # You can specify your own logic for updating this field def __str__(self): return self.name -
Urgent !! Django web server has a sqlite3 problem and can't run! Help~~
Web server is Django4.2.1 with nginx1.18.0. The original Ubuntu20.4 venv(python3.8.10,gcc 9.4.0) directory inside web directory PycharmProjects/WebProjects. It may be due to the installation of python 3.11 in other environments. I do not know why the venv of Python3.8 is affected. An error occurred while running python3 manage.py runserver XXXX: `(venv) dave@dave-X299-WU8:~/PycharmProjects/WebProject$ python3 manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/utils /autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/core/management/base.py", line 485, in check all_issues = checks.run_checks( File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 494, in check for pattern in self.url_patterns: File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/dave/PycharmProjects/WebProject/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File … -
Can't add to head in Django Template
I have the following: bootstrap.html: {% extends 'django_bootstrap5/bootstrap5.html' %} {% block bootstrap5_title %}{% block title %}{% endblock %}{% endblock %} sm/base.html: {% extends 'sm/bootstrap.html' %} {% load django_bootstrap5 %} {% block head %} <meta name="robots" content="all, index, follow" /> {% endblock %} {% block bootstrap5_content %} <div class="container"> <h1>{% block title %}(no title){% endblock %}</h1> {% autoescape off %}{% bootstrap_messages %}{% endautoescape %} {% block content %}(no content){% endblock %} </div> {% endblock %} sm/home.html: {% extends 'sm/base.html' %} {% load django_bootstrap5 %} {% block title %}My title{% endblock %} {% block head %} <meta name="robots" content="all, index, follow" /> {% endblock %} {% block content %} <br/> {% endblock %} When I view the output, I don't see the robot meta in the head. What am I doing wrong? <!DOCTYPE html> <!DOCTYPE html> <html lang="en-ie"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>My title</title> <link crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" rel="stylesheet"> </head> <body> ... -
Compare created_at to an hours_old integer in JsonField in Django
I'm trying to create a django query that compares my models created_at date to see if they are at least x hours old where x is defined in a nested JsonField hours_old. So for example: # This creates a timedelta ("Duration" natively, I think) hours_past = ExpressionWrapper( timestamp.now() - F('created_at'), output_field=DateTimeField() ) Person.objects.annotate( hours_old=F('settings__json__data__hours_old') # Let's say this is an int of 3 hours_past=hours_past # Let's say this is a timedelta of 2 days ).filter( hours_old__lt=hours_past # I want 3 < 48 ) But I can't compare a time duration to a random int obviously. What's the play here? -
Query in django orm to get all users in a list from django authentication group returns empty list
In my code below, the list is empty, it does not contain user name in list. from django.contrib.auth.models import Group, User def first(request): from django.contrib.auth import models groups = Group.objects.all() # Create an empty list to store users all_users = [] # Iterate through the groups and get users for each grou for group in groups: users = group.user_set.all() all_users.extend(users) print(all_users) return render(request,'first.html') I expected to get users details but got an empty list. Why is that and how can I fix it? -
Non atomic transaction inside transaction.atomic() block in Django
I would like to insert in db some objects directly inside transaction.atomic() block, not waiting that block finish. Why do I need this? I need atomic block because of a business logic and without it, I could get invalid state. But, I would like to track process. Process need to be updated inside block, because if executed after atomic block is finished, I only get 100% inserted. Example for example, I would need something like this def my_function(my_list, id): t = Task.objects.get(id) percent = int(100 / len(my_list)) with transaction.atomic(): for i in my_list: MyObject.objects.create(**i) t.progress = t.progress + percent t.save # This should not be atomic!!!! Not a solution I can't move the t.save outside the atomic block because it need to be updated along the code to track process. Directly inserting into database with code with connection.cursor() as cursor: cursor.execute(".... my update statement...") I try and it doesn't work - it still insert after atomic block is finished. -
Making multiple Multiselect forms dynamically in Django admin for the same M2M linked model
Is it possible to have dynamically multiple "Multi-Select" Form in Admin panel that is related to same model based on a certain rule? Like: A separate multi-select form for each category flagged as main/parent category with it's children only as selection options. Details: I have Posts Model and Categories Model, linked to each other via ManyToManyField on POSTS, the plan for categories model to be hierarchal where the top level are main groups of categories and leaf categories are linked to them as parents. In POSTS admin page, I'm doing normal Multi-select Forms, it shows normally as below: The Top level Categories will grow to maybe 6 with 10-15 options in each one.. it will make this form difficult to navigate or manage. So I want Cat and cat2 to have their own multi-select form, where the listed categories in each will be their children only. So even later when I add a third cat3 parent, i'll show in a separate multi-select form as well. I'm trying to avoid building a separate html page for adding Posts for this only, as all other things are ok and i thought there might be a solution for it. Note: checked different Django … -
Why the User data are not updated? in Django?
I have a Model called UserAccount, I have tried several ways to update the data for an existing user, it responds that changes are successful without any error but still nothing is reflecting in Database Here is the Model class UserAccount(AbstractBaseUser,PermissionsMixin): first_name = models.CharField( max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(_("email"),validators=[EmailValidator()],unique=True) date_added = models.DateTimeField(auto_now_add=True) phone = models.CharField(max_length=20, validators=[RegexValidator(r'^\d{12}$', 'Enter a valid phone number.')]) profile_picture = models.ImageField(upload_to='media/users_photos/%Y/%m',null=True,blank=True) employee_id = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(999)], null=True,blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(auto_now_add=True , null=True) objects = CustomUserAccountManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name","phone"] EMAIL_FIELD = "email" class Role(models.TextChoices): ADMIN = "Admin", "Admin" MANAGER = "Manager", "manager" NORMALUSER = "Normal", "normaluser" base_role = Role.NORMALUSER role = models.CharField(max_length=50, choices=Role.choices) def save(self, *args, **kwargs): if not self.pk: self.role = self.base_role return super().save(*args, **kwargs) def __str__(self): if self.first_name and self.last_name: fullname = f'{self.first_name} {self.last_name}' elif self.first_name: fullname = self.first_name elif self.last_name: fullname = self.last_name else: fullname = "Unnamed User" return fullname # Add related_name to avoid clashes groups = models.ManyToManyField( 'auth.Group', related_name='user_accounts', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', verbose_name='groups', ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='user_accounts', blank=True, help_text='Specific permissions for this user.', verbose_name='user … -
Cannot resolve keyword '-name' into field. Choices are: name, account, account_id
Why am I getting this error and is there any alternative way to achieve the result of the below query? Cannot resolve keyword '-name' into field. Choices are: name, account, account_id. self.queryset = Model.objects.order_by( Case( When(status='pending', then=0), When(status='rejected', then=1), When(status='accepted', then=2), default=3 ), Case( When(status='pending', then='-name'), default='-account' ) )