Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
Syntax Error when deploying django on apache2
I am trying to host a django application on a server using apache2 and mod_wsgi. The project itself is located at the path /usr/share/django-projects/mysite The virtual environment is located at the path /home/zakhar/django_test/env It's part of apache2 (2.4 version) conf file. In venv python version is 3.8.13 WSGIDaemonProcess mysite user=www-data group=www-data python-path=/usr/share/django-projects/mysite:/home/zakhar/django_test/env/lib/python3.8/site-packages python-home=/home/zakhar/django_test/env It's last error from apache arror.log File "/home/zakhar/django_test/env/lib/python3.8/site-packages/django/db/models/aggregates.py", in line 84 if (default := c.default) is None: ^ SyntaxError: invalid syntax I think apache use python 3.6.9 in global env, but not in venv I would be very grateful if someone could help me -
ERROR:: --system is intended to be used for pre-existing Pipfile installation, not installation of specific packages. Aborting
I finished my django project.And ı want to deploy my project on aws.I pulled from github my project and then on virtual computer on aws(ubuntu) run pipenv install,I am getting this error every time. ERROR:: --system is intended to be used for pre-existing Pipfile installation, not installation of specific packages. Aborting. How can I fix that -
How to bind a function to an html button without a form in Django
I'm new to Django and I need to bind a function from python to a button using onclick from a file views.py. I saw a lot of discussions where they do this with forms, but I want to do without them index.html: <div class="submit"> <button type="button" name="submit" onclick="">Get Info</button> </div> views.py: from django.shortcuts import render def index(request): return render(request, 'index.html') def get_info(): print("It works") Need to bind get_info() -
Is it able to resume downloading when the connection is lost in Django?
from django.http import FileResponse def send_file(): #some processes response = FileResponse(open(file_name, 'rb'),as_attachment=True) return response The connection sometimes lost. I want to resume downloading the file. How can I do that? Many thanks. -
how do I make a page only to be accessed through redirection from a stripe checkout session page, in django?
I want a page (view) to be only accessed through redirection from stripe checkout session page, and not accessible in any other way. Here is the page that I want to only be accessed through redirection from the stripe checkout session page: def successView(request): data = cartData(request) cartItems = data['cartItems'] context = {'cartItems':cartItems} return render(request, 'store/success.html', context) Here is the stripe checkout session page that redirects to the page: class CreateCheckoutSessionView(View): def post(self, request, *args, **kwargs): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] line_items_list=[] for item in items: quantity=item['quantity'] price_stripe=item['product']['stripe-price'] line_items_list.append( { 'price': price_stripe, 'quantity': quantity, } ) checkout_session = stripe.checkout.Session.create( payment_method_types=['card'], shipping_address_collection={'allowed_countries': ['DK']}, line_items=line_items_list, automatic_tax={ 'enabled': True, }, mode="payment", success_url=YOUR_DOMAIN + 'success/', cancel_url=YOUR_DOMAIN + 'kurv/' ) return redirect(checkout_session.url) -
Default value in Django Model
I have a model named "Product" and it has an attribute like price, quantity, and remarks. Thru the models.py, if remarks has a property of "null=True", it will return a value "None" but I want it to be a dash(-). If you will be adding a "default='-'" into the remarks column in the model, once its form is created and loaded, it has a dash('-') on it but I want nothing on the form when it's loaded. Do you have any ideas if that's possible? -
Connecting to MSSQL from django 1.8 on Ubuntu
I need to connect to MSSQL database from Django 1.8 and preserve Django 1.8 (not upgrade to newer version od Django). I installed pip install django-mssql . ENGINE in settings.py is sqlserver_ado. It ended with error message ModuleNotFoundError: No module named pythoncom. Django 1.8 is running on Ubuntu 18.04 According to this page I see that django-mssql needs PyWin32. So I returned back to my snapshot in virtual machine and tried it with pip install django-mssql-backend and changed the ENGINE in settings.py to sql_server.pyodbc Now I have error message sql_server.pyodbc isn't an available database backend. So I returned back to my snapshot in virtual machine and tried it with pip install mssql-django and ENGINE is mssql. This upgraded Django to 3.4.1. So I returned to my snapshot of virtual machine. How can I connect to MSSQL from Django 1.8 without upgrading Django? Or is it impossible? Why? -
Create Dynamically table and save data in database on django
if i'm Create Dynamically table using jquery this is working This is my .html file code. <!DOCTYPE html> <html> <head> <title>test page</title> <link rel="stylesheet" href= "https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity= "sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <script> $(document).ready(function () { // Denotes total number of rows var rowIdx = 0; // jQuery button click event to add a row $('#addBtn').on('click', function () { // Adding a row inside the tbody. $('#tbody').append(`<tr id="R${++rowIdx}"> <td class="row-index text-center"> <p>${rowIdx}</p> </td> <td class="row-index text-center"> <input type="text" name="organization"> </td> <td class="row-index text-center"> <input type="text" name="designation"> </td> <td class="row-index text-center"> <input type="date" name="date_from"> </td> <td class="row-index text-center"> <input type="date" name="date_to"> </td> <td class="text-center"> <button class="btn btn-danger remove" type="button">Remove</button> </td> </tr>`); }); // jQuery button click event to remove a row. $('#tbody').on('click', '.remove', function () { // Getting all the rows next to the row // containing the clicked button var child = $(this).closest('tr').nextAll(); // Iterating across all the rows // obtained to change the index child.each(function () { // Getting <tr> id. var id = $(this).attr('id'); // Getting the <p> inside the .row-index class. var idx = $(this).children('.row-index').children('p'); // Gets the row number from <tr> id. var dig = parseInt(id.substring(1)); // …