Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hello everyone, please how do I call the constant messages that comes with a Validation Error into my program?
views.py I want each validation messages to be displayed in the home page according to the type of error message. for example: if the password input is too short, it should only display the password input when it redirects the user back to the home page. Thank you in advance! from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth import authenticate,login,logout #from django.contrib.auth.models import User from django.core.mail import send_mail from .models import User from django.contrib.auth.password_validation import validate_password,UserAttributeSimilarityValidator,CommonPasswordValidator,MinimumLengthValidator,NumericPasswordValidator from django.contrib.messages import constants as messages_constants MESSAGE_LEVEL = messages_constants.DEBUG # Create your views here. def signup(request): if request.method == "POST": username = request.POST.get("username") fname = request.POST.get("fname") lname = request.POST.get("lname") email = request.POST.get("email") password = request.POST.get("password") password2 = request.POST.get("password2") if password: try: new = validate_password(password,user=None,password_validators=None) except: messages.error(request, ) return redirect('home') -
Rpy2 Error in Django - Conversion 'py2rpy' not defined for objects of type '<class 'str'>
I have never used R before, and am trying to call an R function from python using rpy2. It works on a standalone python terminal, but not in Django. But rpy2 does not seem to be able to convert python strings to r objects. I am using a custom library given by a coworker and would like to know if the problem is on his side. Because I have seen other people on SO using the exact same method to run R functions from python. Here's the code from config import celery_app from rpy2.robjects.packages import importr from pathlib import Path import math base = importr("base") my_lib = importr("my_lib") @celery_app.task() def calculate_r_bindings(file_path): """ """ g = my_lib.fit_bindingCurves(input = file_path,tass = 200,tdiss = 530,conc_M = 1.2*math.exp(-7),generate_output = False) return g I am using rpy2 version 3.5.5 Here's the error: File "/Users/user.ali/Projects/ProjectDev/project_env/lib/python3.9/site-packages/rpy2/robjects/conversion.py", line 240, in _py2rpy raise NotImplementedError( NotImplementedError: Conversion 'py2rpy' not defined for objects of type '<class 'str'>' -
psycopg2.OperationalError: SSL connection has been closed unexpectedly
My application is using Django==3.0.6 with psycopg2==2.8.6. I am using Django ORM not SQl-Alchemy. I get this error every 4-5 days randomly. Unable to reproduce this error on local. Any suggestions what can be the reason for this? If I restart my application container, application starts working normally without any errors till I get same error in next 4-5 days. Traceback (most recent call last): ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute ma-datamanagement_1 | return self.cursor.execute(sql, params) ma-datamanagement_1 | psycopg2.OperationalError: SSL connection has been closed unexpectedly ma-datamanagement_1 | ma-datamanagement_1 | ma-datamanagement_1 | The above exception was the direct cause of the following exception: ma-datamanagement_1 | ma-datamanagement_1 | Traceback (most recent call last): ma-datamanagement_1 | File "/insightsmax_datamanagement_app/datastaging/data_upload.py", line 97, in get_s3_bucket_name ma-datamanagement_1 | project_obj = models.Project.objects.get(display_project_id=project_id) ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method ma-datamanagement_1 | return getattr(self.get_queryset(), name)(*args, **kwargs) ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 411, in get ma-datamanagement_1 | num = len(clone) ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 258, in len ma-datamanagement_1 | self._fetch_all() ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 1261, in _fetch_all ma-datamanagement_1 | self._result_cache = list(self._iterable_class(self)) ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 57, in iter ma-datamanagement_1 | results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) ma-datamanagement_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1151, in execute_sql ma-datamanagement_1 … -
Django - why my widget is cleared out during save?
I'm struggling with a django custom widget used to present HTML data. I've started with a template from standard django's textarea: class Descriptionarea(forms.Widget): template_name = "widgets/descriptionarea.html" def __init__(self, attrs=None): super().__init__(attrs widgets/descriptionarea.html: <textarea name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}> {% if widget.value %}{{ widget.value }}{% endif %}</textarea> Which works fine as an element of my inline form: class InlineForm(forms.ModelForm): description = forms.CharField(widget=Descriptionarea) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) which is part of my TabularInline (django-nested-admin in use): class TabularInline(NestedStackedInline): form = InlineForm fields = ("title", "description") readonly_fields = ("title", ) model = MyModel max_num = 0 I'd like to present the description as HTML document, so I've changed the template: <details> <summary>description</summary> <pre name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}> {% if widget.value %}{{ widget.value | safe }}{% endif %} </pre> </details> Unfortunately, it does not work, as now I cannot use save on admin pages, as Django complains about: This field is required. Indeed during save, the whole widget is cleared out. Second question - when I add the description field to the list of readonly_fields, then it becomes a simple label. Is it possible to provide my own readonly widget? -
Add a .well-known folder to Django urls.py
I want to verify my SSL certificate to verify my server. What makes it more confusing is, it works just fine on my current certificate. But since it's expiring soon, I'm renewing it. But the auth file inside pki-validation folder can't be read. This is what it redirects to when I'm trying to check if the auth file is accessible: I'm using zeroSSL for my SSL. I'm suspecting that the .well-known folder can't be found by the server. So the answer is to specify the folder to the Django urls.py, but I'm having trouble on trying to add a hidden folder (.well-known) to the Django's urls.py file. Tried following this solution https://stackoverflow.com/a/55133603/20029765 but no luck, it redirects to a page saying "Internal Server Error": Is there any other solutions that I can try? -
Django rest framework serializer object from ID
I have this serializer: class OrderLineSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField(source="item.id") name = serializers.ReadOnlyField(source="item.name") price = serializers.ReadOnlyField(source="item.price") quantity = serializers.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(MAXNUMBERSIZE)] ) class Meta: model = OrderLine fields = ("id", "name", "price", "quantity", "sub_total") and it's fine when I send data to the user but is there a way to serialize data that I receive from the API without creating another serializer. if I receive some API request with this content {id : 123, quantity : 10} if doesn't get the item from the db. is there a way to do it or I have to create a dedicated serializer? -
Read Image present in Django Model
The code of the model is as follows class Post(models.Model): title = models.CharField(max_length=100) file = models.FileField(null=True,blank=True,upload_to='Files') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) I want to read the file (image or video). Let's say its an image. I want to read this image in an array format. I tried with the following code but i just get the file name and not a image matrix img = Post.objects.all()[0].file print(img) OR print(np.array(img)) Output is : car-1.jpg Expected output : 2d Array -
How to increase speed on select query?
I have a table that has 4 Foreign Keys,and this table contains only 2000 rows. The table was created by using Django ORM. I am using Postgresql as a database. when I send Select query to Database or GET request to that endpoint, data comes in 15 seconds. I have created 2 more indexes, data came in 18 seconds, I have deleted all foreign key indexes and kept only primary key index, data came in roughly 15 seconds again. How can I speed it up? it is simple Select query, SELECT * from table, this is the first time I encounter such thing, I have no idea what to improve. -
ProgrammingError at / column projects_project.prequalif_state does not exist LINE 1: SELECT "projects_project"."id", "projects_project"."prequali
I know the question has already been asked several times, but nothing worked for me I have a project that works properly locally, but when I deployed it on a virtual machine (working with CentOS), many problems related to the database appeared. When I try to print the fields of my 'Project' model from the shell, they are displayed correctly, but I can't display any object from this model : Same error when I try to create a Project object : This happens only with the models of my 'projects' application, I have another application who works correctly I removed all my migrations files and run makemigrations and migrate, nothing changed. If someone can give me any suggestion, I'm interested (nothing important in the database, I can reset it if necessary) Don't hesitate to tell me if you need me to add infomrations to my post -
How to pass request as an arguement to serializer in serializer method field
I have a main serializer, and I also have a serializer for my BOOK model so I made a method to return a serialized queryset using my BOOK SERIALIZER BUT the problem is ** I can't access my main serializer context through BookSerializer** What can I do? Views.py: class BookMainPage(ListModelMixin, RetrieveModelMixin, GenericViewSet): queryset = Book.objects.select_related('owner').all() def get_serializer_context(self): return {'user': self.request.user, 'book_id': self.kwargs.get('pk'), 'request': self.request} def get_serializer_class(self): if self.kwargs.get('pk') is None: return MainPageSerializer return BookComplexSerializer MainPageSerializer: class MainPageSerializer(serializers.Serializer): @staticmethod def get_new_books(self): return BookSimpleSerializer(Book.objects.all().order_by('-created_at')[:10], many=True).data @staticmethod def get_popular_books(self): return BookSimpleSerializer(Book.objects.all().order_by('-bookRate')[:10], many=True).data @staticmethod def get_most_borrowed(self): return BookSimpleSerializer(Book.objects.all().order_by('-wanted_to_read')[:10], many=True).data new_books = serializers.SerializerMethodField(method_name='get_new_books') popular_books = serializers.SerializerMethodField(method_name='get_popular_books') most_borrowed_books = serializers.SerializerMethodField(method_name='get_most_borrowed') BookSimpleSerializer: class BookSimpleSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ['id', 'picture'] def get_picture(self, obj: Book): request = self.context['request'] photo_url = obj.picture.url return request.build_absolute_uri(photo_url) picture = serializers.SerializerMethodField(method_name='get_picture') class CategorySimpleSerializer(serializers.ModelSeria -
How to set up javascript and django applications to exchange jwt tokens
I have a SAP implemented on the Netlify platform. The processing for the app is implemented in a django api running on a hosted server. Users are authenticated on the Netlify app, but do not need to be authenticated in django. I now want authorised users to be able to post data to the api and the django server objects with the message Forbidden (CSRF cookie not set.): /api/save-archive/{...}/ I am looking at implementing JWT cookies and have considered djangorestframework_simplejwt but that seems to require that the user is authenticated in django My question is, what software elements do I need to be able to generate and consume a token is this scenario? -
Dynamically create a form / dynamically add fields to a form
I've been facing this issue in django and I don't know how to do. Here it is. I have the Product model, and a form allowing a person (not admin) to register a product. I would like to give the possibility to an admin to "build this form or update it", with the fields he wants. The Product template will then be updated with new fields, and the form filled by a person too. Is there a way to do this? Thanks -
Concatenate Properties of Django QuerySet
Can I join Django ORM Model properties/attributes into a string without introducing loops? I have a django model: class Foo(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=1000, db_collation='Latin1_General_CI_AS') I want to select the names into a string from a result of filtering: foos = Foo.objects.filter(id=[1,2,3]) Something equivalent of this piece of C#: using System; using System.Collections.Generic; using System.Linq; public class Program { public class Foo { public string Name { get; set; } } public static void Main() { List<Foo> foos = new List<Foo>(); foos.Add(new Foo { Name = "A1" }); foos.Add(new Foo { Name = "A2" }); Console.WriteLine(string.Join(",", foos.Select(x => x.Name))); } } Which outputs A1,A2. -
Get latest item date where item field_1 & item field_2 have duplicates
I'm using Django 4.0, and Python 3.8. I have a product that has a modification date, department name and designation. I want to retrieve each product but, for products that have the same designation and the same department, I only want to retrieve the last entry. Here is what i have now: ` products = Product.objects.all().order_by('designation') ` I tried sorting on the result and removing duplicate rows it worked for 10 rows but for 100 its dead For the following data: item: designation, date, department item_1, 01/01/1970, department_1 item_2, 01/01/1970, department_2 item_3, 01/01/1970, department_3 item_1, 01/02/1970, department_1 I want: item_1, 01/02/1970, department_1 item_2, 01/01/1970, department_2 item_3, 01/01/1970, department_3 Do you have any advice please ? -
Django/Wagtail Rest API URL Filter with no response
I am using Wagtail and I have an API called 127.0.0.1:8000/api/v2/stories. In the API I am having this JSON response { "count": 81, "results": [ { "id": 122, "title": "Test Blog", "blog_authors": [ { "id": 82, "meta": { "type": "blog.BlogAuthorsOrderable" }, "author_name": "Test", "author_website": null, "author_status": false, }, { "id": 121, "title": "Test Blog 1", "blog_authors": [ { "id": 81, "meta": { "type": "blog.BlogAuthorsOrderable" }, "author_name": "Test", "author_website": null, "author_status": false, }, } The main problem I am fetching is that I want to filter by author name. I have done this query in the URL ?author_name=Test & ?blog_authors__author_name=Test & ?author__name=Test But the response was { "message": "query parameter is not an operation or a recognised field: author_name" } I have added these fields in known_query_parameters but the response was the same as api/v2/stories/. I have tried DjangoFilterBackend but I got the same response every time. How Can I filter by author_name & author_status in the API? Here is my api.py class ProdPagesAPIViewSet(BaseAPIViewSet): renderer_classes = [JSONRenderer] pagination_class = CustomPagination filter_backends = [FieldsFilter, ChildOfFilter, AncestorOfFilter, DescendantOfFilter, OrderingFilter, TranslationOfFilter, LocaleFilter, SearchFilter,] known_query_parameters = frozenset( [ "limit", "offset", "fields", "order", "search", "search_operator", # Used by jQuery for cache-busting. See #1671 "_", # Required … -
Can't associate the correct IDs using the reverse ManyToMany relationship
**Hello, I'm trying to merge two models that are related through a ManyToMany field. Basically I want to establish a reverse relationship between the model "Position" and the model "Sale". Each sale can have multiple positions, but each position should be specific to its sale. Here is what happens. I filter through dates I know there's data (sales) and I get: sale_df sales_id transaction_id total_price customer salesman 0 11 3B6374D5ED85 300.0 Test Testuser 2022-10-25 1 12 D52E5123EDBE 900.0 Test Testuser 2022-10-24 (I purposefully removed "created" and "updated" because they didn't fit nicely here) position_df position_id product quantity price sales_id 0 10 TV 3 300.0 11 1 10 TV 3 300.0 11 2 11 Laptop 1 600.0 12 WHEN positions_df sales_id *should be* => position_id product quantity price sales_id 0 10 TV 3 300.0 11 1 10 TV 3 300.0 12 2 11 Laptop 1 600.0 12 It seems like when I get the sale_id in reverse through the method "get_sales_id()" it associates it with the first instance of the position, instead of prioritizing the sale_id Here is the code: models.py from django.db import models from products.models import Product from customers.models import Customer from profiles.models import Profile from django.utils import timezone … -
Is it OK to use Django development server for single-user applications?
I'm developing an application that controls some piece of complex hardware and exposes a front-end to the users (currently with Django templates, but soon with a separate front-end through DRF calls). My main points of interest are: user management. Admin users have more access session management. Ideally, one cannot login from multiple IPs at the same time. web-socket support for asynchronous notifications and real-time monitoring. asynchronous background operations. e.g. with celery workers Note that the users of these application are the hardware operators which are usually no more than 3-5 tops, and most of the times, only one of them is actively working on it so no real user concurrency, neither real need to scale. So my question is: Is there a real reason I would need to distribute my application using a production server such as gunicorn instead of simply running manage.py runserver? -
How to get exact values of the foreignkeys in django admin
class Mio_terminal(models.Model): terminal = models.CharField(max_length = 50) gate = models.CharField(max_length = 50) gate_status = models.CharField(max_length = 50, default = 'open') #open, occupied, under_maintenance class Meta: unique_together = [['terminal', 'gate']] class Mio_flight_schedule(models.Model): fact_guid = models.CharField(max_length=64, primary_key=True) airline_flight_key = models.ForeignKey(Mio_airline, related_name = 'flight_key', on_delete = models.CASCADE) source = models.CharField(max_length = 100) destination = models.CharField(max_length = 100) arrival_departure = models.CharField(max_length=12) time = models.DateTimeField() gate_code = models.ForeignKey(Mio_terminal, related_name = 'terminal_gate', null = True, on_delete = models.SET_NULL) baggage_carousel = models.CharField(max_length = 100) remarks = models.CharField(max_length = 100) terminal_code = models.ForeignKey(Mio_terminal, related_name = 'airport_terminal', null = True, on_delete = models.SET_NULL) this is models for terminal and flight schedule. I want to have terminal name and gate code instead of the object ... i know we can get this by using str method in models....but we get only single value for this...not more than one please let me know how should i deal with this? -
Creating a rating system scale 1-5 and average rating
enter image description here] This is in python with Django and using SQL as database. I am new to this language. I am having issues with creating the average rating for books. I want to get a list of books that userid's have rated and get the average of it. I don't know if I can use querysets. I also want to know how I can create a comment to warn people on postman that the scale is only 1-5. I don't know if I can do it as an if-else statement or not I look into the django website on aggregation to see if the average works but I can't seem to figure it out. I tried creating an if else statement but > is not supported between instances of -
How to associate an existing user with multiple social accounts (different emails)? [DRF_SOCIAL_OAUTH2]
I'm trying to associate user with multiple social accounts in Django Rest Framework. After user login, user can associate with social accounts (it doesn't matter same email or different email). Now I am using the library drf-social-oauth2. I have done signIn/singUp part. According to Social_Auth_Pipeline, I added this code to associate user SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) The endpoint "http://localhost:8000/auth/convert-token" can handle the singin/singup using social auth.(eg. Facebook, Google) social_core.pipeline.social_auth.associate_by_email managed to associate the user if same email. My Question is How can I connect/associate Social Accounts (* different email/same email) with current login user using drf_social_oauth2? Do I need to add field in user table to associate? OR Do I need to add something to setting.py?... Please advise me. Thank you. -
Active or inactive users
I'm trying to design a django application where users' accounts can only be activated after making payments...Inactive users are denied all the web functionalities until the make payments. How can I go about this? -
Django rest framework user model permissions
I am building a web app using REST API and I have a 4 users that I want them to access only the content they have added to the backend. I have created 3 users say farmers(3 farmers) and added content using each one of them. However, I have been unable to implement permissions such that a farmer can view and delete only what they added. Here's is my code in models.py User = get_user_model() # Create your models here. class Tender(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() date_due = models.DateField(default=datetime.date.today) location = models.CharField(max_length=255, null=False) contact = models.PositiveIntegerField(null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Input(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.DecimalField(max_digits=10, decimal_places=2) contact = models.PositiveIntegerField(null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Investor(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() location = models.CharField(max_length=255, null=False) contact = models.PositiveIntegerField(null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name Here's what I implemented in permissions.py from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, … -
Problem using npm of chart.js in django Project
I tried to use Chart.js in my Django project , when I Use NPM package it's not working but when I use CDN It work Perfectly char.js version 3.9.1 here is my index.html file on my project <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {# <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>#} <script type="application/json" src="/node_modules/chart.js/dist/chart.js"></script> </head> <body> <canvas id="myChart" width="400" height="400"></canvas> <script> const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> </body> </html> my console error in browser is : (index):17 Uncaught ReferenceError: Chart is not defined at (index):17:17 I tried to use chart.min.js in my script but not working. I also Try previous version of charj.js but … -
Python sleep if a function runs for 20 times
I have a function for sending an email which is used in a celery task i need to make the code sleep for a second if that email function is ran for 20 times how can i make this happpen. @app.task(bind=True) def send_email_reminder_due_date(self): send_email_from_template( subject_template_path='emails/0.txt', body_template_path='emails/1.html', template_data=template_data, to_email_list=email_list, fail_silently=False, content_subtype='html' ) so the above code is celery periodic task which runs daily i filter the todays date and send the email for all the records which are today's date if the number of records is more than 20 lets say so for evry 20 emails sent we need to make the code sleep for a second send_email_from_template is function which is used for sending an email -
Group Session in Django Channels
I'm looking for a solution where I want to create a group with n number of users and let them-users join the group. and then finally, delete this group once the work is complete. (the creator of the group can delete this or when everyone from the group disconnects). I have been thinking to design this for the last 3-4 days but I'm not able to. I'm building the transcriber app and this group is to maintain sessions on each topic. For every new topic/scenario, a new group/session is required. The question is - How and when should I delete the group? Suppose I created a group and then everyone joins, I can maintain a database and delete this group when everyone disconnects from this group, somehow I don't think this to be the best option Can anyone guide me to design the best possible option? Will provide more details if required.