Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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)); // … -
API takes longer to load first time opening my webpage
I have a Django app configured on AWS Lambda with zappa. In this app I created some basic APIs with DRF. On the otherside I have a ReactJS frontend that makes these GET requests to load in my data. On my frontend I make a call to get my ID's based on some condition, with this response I get max. 30 ID's where I loop through and make another call for every ID to get their data. The first time I do this, my api to get the ID's loads perfectly and fast enough, but then when it loops, some api's to get the data goes really fast and some just takes around 10-20 seconds to load. this only happens the FIRST time I load my page, after that, if I refresh my page, it is up and running in under 1s. I did some research and I know that AWS Lambda is serverless and shuts down when no one is using the application, so with that in mind, I thought this was why its always slower the first time. But then I found a setting on zappa "keep_warm" to keep my server running, I also made sure that "keep_warm_expression" … -
uwsgi /nginx/ setup on django on centos
i need second pair of eyes , i want to setup my theta.ini file , but uwsgi geta borted for an obscure permission denial in log # this my theta ini file located at /etc/uwsgi/vassals/theta.ini [uwsgi] http=:8000 socket=/opt/uwsgi/sock/theta.sock chdir=/home/tbricks/theta pythonpath=/home/tbricks/theta/django_project home=/home/tbricks/env virtualenv=/home/tbricks/env module = django_project.wsgi uid = uwsgi chmod-socket = 664 chown-socket = uwsgi the below result of running wsgi from log first issue my virtualenv is not getting selected , i don't understand why second the permission error which does make sense, whether env owner is root or uwsgi i get this error , i'm using django 3.0.8 and uwsgi 2.0.14 , python 3.6.8 *** Starting uWSGI 2.0.20 (64bit) on [Thu May 12 14:47:51 2022] *** compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-44) on 11 May 2022 19:17:58 os: Linux-3.10.0-1160.53.1.el7.x86_64 #1 SMP Fri Jan 14 13:59:45 UTC 2022 nodename: django-server machine: x86_64 clock source: unix detected number of CPU cores: 1 current working directory: / detected binary path: /home/tbricks/env/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! setgid() to 993 setuid() to 996 *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 3873 your memory page size is … -
how to change folder location to save file - DJANGO FileSystemStorage
so i want when i upload a file, the file will go to media/mp3 not media/txt. how to change save file location? views.py: def homepage(request): if request.method == 'POST' and request.FILES['upload']: upload = request.FILES['upload'] fss = FileSystemStorage() file = fss.save(upload.name, upload) file_url = fss.url(file) return render(request, 'homepage.html', {'file_url': file_url}) return render(request, 'homepage.html') -
How can I display data from django model and save at the same time using class based views?
I am creating a quiz app using Django. The requirements are: I need to first display all the topics available for the quiz on the homepage. Clicking on a particular page should redirect us to a new page where we will see the questions. Each time one question should be displayed. The next button should load the next question and the user cant go back to the previous question. After attempting all the questions, the user should be taken to another page that displays the score. For each question being attempted, the process should be displayed like 5/10 question, 6/10 question. If a user logs out before completing the quiz, he/she must be displayed the same question once he logs in. I am able to display the topics . The problem is I am not able to display one question at a time and store the user's answer using the class based view. Also I am confused how will I display progress and store the user record if he/she logs out without completing the quiz and redirect them to the very next question till where they had attempted. I am new to django and trying to develop this. Please HELP! … -
Save Form data to use on Request DJANGO Python
I have this pure code writing in Python and requests url = 'https://192.168.1.99/rest' username = 'admin' password = '2626' response = requests.get(url + '/interface', auth=HTTPBasicAuth(username,password), verify=False) When I print the Response, I receive what I expected. So the code is working. But I'm trying to do the same thing with Django, and I don't know how to proceed. On Django, I have a form to save data in to model. Working. But I don't know what's next. Also, the response is a JSON object, but if I use JsonResponse I get an error. -
How to disable "django login" hyperlink while accessing swagger ui in drf-yasg?
I'm using drf-yasg to add swagger auto schema to my endpoints. The swagger-ui is being visible at /api/v1/swagger/ At my local setup this link is working fine and I'm getting the proper schema as required. /api/v1/swagger at my local setup But while accessing the same link when my application is deployed at the server, It is showing a "django login" hyperlink as: /api/v1/swagger at server And this "django login" hyperlink is navigating to -> SERVER_IP/accounts/login/?next=/api/v1/swagger/ which is showing 404 Not found page as: 404 Not found page after clicking on django login hyperlink Even though the openAPI yaml file is being successfully generated of the endpoints at server, but the UI is not getting visible. There was one similar question at stackoverflow: Similar question at SO, but the solution mentioned there was not working for me. Thanks.