Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Replacement in python package in Docker
GraphQL is still not supported in Django 4, so to use it I need to change the line: "from django.utils.encoding import force_text" to "from django.utils.encoding import force_str as force_text" in package "VENV/lib/PYTHON_VERSION/site-packages/graphene_django/utils/utils.py" The problem occurs when using Docker, how could I replace this line when building the container? -
Url decoding problem on deployment with IIS and FastCGI on windows server
I realized an app front Angular, back-end Django, deployed on Windows server using IIS and FastCGI. This app serves media files on a certain URL. It works fine locally on dev server. I can access all my files correctly on path "medias/myfilepath". The problem is in production on IIS. Special characters are encoded in a different way. I think it is FastCGI that does it. I cannot find the encoding rules, and my Django app is not able to decode properly so my requests end up with a 404 error. Here are some examples of the difference of encoding between local server and production server : à | local : %C3%80 | prod : %25C0 ù | local : %C3%99 | prod : %25D9 É | local : %C3%89 | prod : %25C9 I can't find any documentation on the subject, I don't have access to configurations on CGI side. I could update decoding on Django side to fit it, but I can't find which one applies ... Someone would have some ideas on that subject ? -
WARNING: autodoc: failed to import module 'upload_data_to_server' from module 'manual';
I'm trying to document a Django project using Sphinx's autodoc extension. I have two main problems: It's documenting excessivelly in some modules (importing documentation that I don't want from django) It's not documenting one of the packages at all. Here is my django tree: |main_app | core | migrations | static | templates | consumers.py | forms.py | models.py | routing.py | serializers.py | urls.py | views.py | main_app | asgi.py | settings.py | urls.py | wsgi.py | manual | upload_data_to_server.py | manage.py | docs | _build | _static | _templates | conf.py | index.rst | make.bat | Makefile The docs file is the one I created to host the files created by sphinx-quickstart. Then, I changed the conf.py file adding this lines: import os import sys import django sys.path.insert(0, os.path.abspath('..')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main_app.settings") django.setup() extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] And I changed index.rst adding modules: Welcome to yourProject's documentation! ==================================== .. toctree:: :maxdepth: 2 :caption: Contents: modules Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` I executed sphinx-apidoc -o . .. and ./make html. I get something similar to what I want, but I said before, I get too many comments for django files, and no comments at all … -
How to optimize the downlaod big file problem in Django?
My Django project gives an download interface as def download_item_vector(request): return HttpResponse(np.load('item_vector.npy')) I want to return a big numpy array to the client. But it is very slow. Is there any good idea to do that? -
Testing UX with random IO?
So I've found a error in my UX that wasn't cought by test if I press besides a popup it goes into deadstate # they press ok btn = self.browser_adam.find_element(By.ID, "closeBtnMod").click() How do I catch things like reloading a page or this special case? -
Django model default value in response
I want to have a default value in my django model response value Sample model query myModel.objects.filter().values("username", "user_gender") I want to have a default value in response It must be like Select username, user_gender, 'delhi' as country from mytable Please let me know if any suggestions -
How to create a persigned url for a private s3 bucket using django rest framework
models.py def upload_org_logo(instance, filename): ts = calendar.timegm(time.gmtime()) filepath = f"Timesheet/org_logo/{ts}" if instance: base, extension = os.path.splitext(filename.lower()) filepath = f"Timesheet/org_logo/{instance.org_id}/{instance.org_name}{extension}" return filepath class Organisation(models.Model): """ Organisation model """ org_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True) org_name = models.CharField(unique=True,max_length=100) org_code = models.CharField(unique=True,max_length=20) org_mail_id = models.EmailField(max_length=100) org_phone_number = models.CharField(max_length=20) org_address = models.JSONField(max_length=500, null=True) product = models.ManyToManyField(Product, related_name='products') org_logo = models.ImageField(upload_to=upload_org_logo, null=True, blank=True,) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I am saving the Org_logo in the private s3 bucket, I need to get the Image from the s3 bucket using a presigned url. I checked out some solutions but I am not sure how to use it specifically on where like in models or views or other? Can you please help me with how to use it and where to use based on my above code. AWS Settings.py AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' AWS_STORAGE_BUCKET_NAME = '' AWS_QUERYSTRING_AUTH = True AWS_S3_FILE_OVERWRITE = True AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_REGION_NAME = '' AWS_DEFAULT_ACL = None AWS_S3_VERIFY = True DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
how can i filter data between two time i am using date time field for it in django rest framework
I am trying to filter my data with date time field but in my case its not working so please someone suggest me how can i filter my date with time start_time = 2022-05-13 02:19:19.146009 end_time = 2022-05-13 02:20:19.146009 parser_order_mi = ParserOrderMenuItem.objects.filter(menu_item_id=menu_item_id, created_at__range=[start_time,end_end_time]) -
Adding field to Django model when the column already exists in the database
I have a model in Django which represents a MySQL table that has some extra columns. I want to add a field to the model for one of these extra columns but I'm not sure how best to do it. Let's say the person table has an age column. My model looks like: class Person(models.Model): name = models.CharField(min_length=200) If I add an age field like: age = models.IntegerField(db_column="age") then when I migrate I get an error about "Duplicate column name 'age'" because it tries to create it. Is there a way around this? What I've tried: Add the field with a new column and make a migration for that: age = models.IntegerField(db_column="age_2") Create a manual data migration to copy data from original column to new one: UPDATE person SET age_2 = age; Create a manual migration to drop the original column: ALTER TABLE person DROP COLUMN age; Create a manual migration to rename the new column: ALTER TABLE person RENAME COLUMN age_2 TO age; On the model change it to use the age column (db_column="age") and make an automatic migration. This works on my existing database, but when I run my tests, and it applies all the migrations to create … -
Django filtering on a queryset not working
I am trying to add a filter on an existing queryset based on a condition but it doesn't work. This works queryset = None if self.is_instructor == True: queryset = Issue.objects.filter(type=self.type, type_id=self.type_id).filter(status__in=self.status) else: queryset = Issue.objects.filter(type=self.type, type_id=self.type_id, created_by=self.created_by) This doesn't queryset = None if self.is_instructor == True: queryset = Issue.objects.filter(type=self.type, type_id=self.type_id) else: queryset = Issue.objects.filter(type=self.type, type_id=self.type_id, created_by=self.created_by) if len(self.status) > 0: queryset.filter( Q(status__in=self.status) ) queryset.order_by('-created_on') This is how my model looks like STATUS_CHOICES = ( ('UNC', 'Unconfirmed'), ('CNF', 'Confirmed'), ('INP', 'In Progress'), ('UAC', 'User Action Pending'), ('RES', 'Resolved'), ) class Issue(models.Model): UNCONFIRMED = 'UNC' title = models.CharField(max_length=512, blank=False) description = models.TextField(blank=False) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='creator') created_on = models.DateTimeField(auto_now_add=True) status = models.CharField( max_length=3, choices=STATUS_CHOICES, default=UNCONFIRMED ) Assured, self.status holds the required data. I can't use get() because there are multiple records I have seen some other answers but couldn't make progress. Thanks in advance. Basant -
Django: how to count posts related to a category in django?
i have a model class Category and also a model class Course. i want to count all the courses that are related to a model e.g: Web Devlopment - 26 Courses i dont know how to go about this since the this are two diffrent models. class Category(models.Model): title = models.CharField(max_length=1000) class Course(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) course_title = models.CharField(max_length=100, null=True, blank=True) course_category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, null=True, blank=True) -
Indexing 80 million documents to elasticsearch from Django
I am using the latest version of django elasticsearch dsl and I am using the following command to index around 80 million documents: python manage.py search_index --rebuild --models <model> --parallel However, my system can't handle it and crashes at about 12gb of ram usage. CPU usage is 10% and seems to be fine. Is there a way to index this amount of django entries to elasticsearch safely? -
Why does Django use `Meta` inner class in models?
If I want to describe some information such as ordering, if the model is proxy or abstract, which fields must be unique together, then I need to put this information in class named Meta that is inside of my model class. But if I want to change the manager I put information about it in the model class itself. class Product(models.Model): class Meta: unique_together = ... ordering = ... objects = My manager() Why did Django developers made such design decision (forcing to put some information about the model in the Meta inner class instead of the model class itself)? -
Django - Hide labels in inline
How to hide labels in Django inlines? -
why does for loop not working in django template
this is my views : rooms = [ {'id': 1, 'name': 'room-1'}, {'id': 2, 'name': 'room-2'}, {'id': 3, 'name': 'room-3'}, {'id': 4, 'name': 'room-4'}, ] def rooms(request): return render(request, 'rooms.html', {'rooms': rooms}) and template codes : {% for room in rooms %} <li>{{room.id}} -- {{room.name}}</li> {% endfor %} unfortunately for loop is not working. -
Queryset is Containing some items but all() method returns empty array
I have this code: print(f"DEBUG 1: {queryset}") transaction_items = queryset.all() queryset.update(status=TRANSACTION_STATUS_COMPLETED, processing_method=PROCESSING_METHOD_MANUALLY) print(f"DEBUG 2: {len(queryset.all())}") somehow producing this result: DEBUG 1: <QuerySet [<TransactionItem: TransactionItem object (18259)>, <TransactionItem: TransactionItem object (18258)>]> DEBUG 2: 0 CHUAKS: [] 0 It's quite weird because the all() method usually return non-empty array because the queryset itself is not empty. -
Can I use Python Opencv library with React?
I want to build web site with image processing. I have react experience. We are using Python Opencv library in image processing lesson. Is it necessary to use a Django or Flask? -
I want to show the usernames under user.username.0 . Details in Description
For example my name is David and my friend is Daniel. I want to show these two names in their first letter wise . Like D - David, Daniel enter image description here just like these picture. views.py enter image description here template code is enter image description here -
Getting error while partial update data in drf
Hi Everyone i am creating api for partially update record, but getting error [patch() missing 1 required positional argument: 'id'], please help me out views.py class GmsGarageViewset(APIView): def patch(self,request,id): garage_data=GmsGarage.objects.get(id=id) serializer=GmsGarageSerializer(garage_data,data=request.data,partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors,status=HTTP_400_BAD_REQUEST) urls.py path('gms/garage/<int:pk>',GmsGarageViewset.as_view()) output error TypeError: patch() missing 1 required positional argument: 'id' ERROR "PATCH /api/gms/garage/1 HTTP/1.1" 500 19954 -
Django - Display in inline random info without relation to any model
Imagine there is a model: class OrgUnit(models.Model): name = models.CharField(...) type = models.CharField(...) address = models.TextField(...) active = models.BooleanField(...) sapid = models.CharField(...) parent = models.ForeignKey('self', ...) Register it in admin: @admin.register(OrgUnit) class OrgUnitAdmin(admin.ModelAdmin): pass Usually in inline displayed some queryset. But I need to display an errors list (python list). The list example: ['No orgunit name', 'No orgunit type']. No foreign key, no relations at all. How could I do that? -
Pushing a project with passwords in it
I created a django project and want to share it with my team members, however in the settings files it contains some passwords for the database etc. Of course when I push it to GitHub Git Guardian tells me that I have some sensitive information such as DB credentials (username and password) and Django's Secret Key. Now, I know I basically delete those information and push it to GitHub. But I wonder if there is a more sophisticated method to push those kind of projects or a convenient way? Thank you very much. -
Reverse for 'Profile' with no arguments not found
I'm trying to add user Profile in my django project. i was trying to access user post into the user Profile but its throws an error like this: Reverse for 'Profile' with no arguments not found. 1 pattern(s) tried: ['profile/(?P[^/]+)/\Z'] and this error is come from my Home template. i want when a user click on profile it will take him/she to the user profile and shows his/she only post he/she did. like social media profile. the problem is comes from this url in my home template its highlight this urls with this error: NoReverseMatch at /home Reverse for 'Profile' with no arguments not found. 1 pattern(s) tried: ['profile/(?P[^/]+)/\Z'] <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url 'Profile' %}">Profile</a> </li> my urls path('profile/<str:pk>/', views.profile, name='Profile') my views def profile(request, pk): post = get_object_or_404(Photo, id=pk) photo = Photo.objects.get(id=pk) user_post = Photo.objects.filter(user=request.user) context = {'post':post, 'photo':photo} return render(request, 'profile.html') my model class Photo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.CharField(max_length=30,null=True, blank=False) image = CloudinaryField(blank=False, null=False) description = models.TextField(null=True) date_added = models.DateTimeField(auto_now_add=True) phone = models.CharField(max_length=12, null=False, blank=False) price = models.CharField(max_length=30,blank=False) location = models.CharField(max_length=20, blank=False) def __str__(self): return str(self.category) home template <div class="container"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">{{user}}</a> <button … -
count item for months wise python DJANGO
I try to make a bar chart and I want value month wise for last 6 months my models.py class Btdetail(models.Model): id = models.IntegerField(primary_key=True) BatType = models.CharField(max_length=200, default=1) MaxVolt = models.IntegerField() DatePurchase = models.DateTimeField(auto_now_add=True) Manf_ID = models.CharField(max_length=200) here is my view.py, this count all item of last six months but I want month wise data for last six months def index_view(request): months_before = 5 now = datetime.utcnow() from_datetime = now - relativedelta(months=months_before) modified_from_datetime = from_datetime.replace(day=1, hour=0, minute=0, second=0, microsecond=0) month_count = Btdetail.objects.filter(DatePurchase__gte=modified_from_datetime).count() return render(request, "index.html", {'month_count': month_count}) -
Django when a data is entered, write the data in the other model depending on the condition
Hello There is a data(text) in data b on app1. I want to write the data here on d on app2. how can I do that? app.model; class Post(models.Model): a=models.CharField() b=models.TextField() app2.model; class Post2(models.Model): c=models.CharField() d=models.TextField() -
The term 'telnet' is not recognized as the name of a cmdlet, function, script file, or operable program
I'm working on a, specifically sending emails in cmd that makes use of telnet. Unfortunately, I can't start it. I'm receiving the "The term 'telnet' is not recognized as the name of a cmdlet, function, script file, or operable program" from cmd when I type telnet. Can someone please tell me on what to install and its procedures for me to access telnet command in CMD. Thanks!