Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
Django Unit Test for downloading a file
Here are the items from the FileResponse object that was returned when I called the API to download the file (not requests library). I am using django test client. How do I download the Example file.json. from django.test import Client c = Client() response = c.get(<URL>) print(response.items()) ('Content-Type', 'application/json') ('Content-Length', '2') ('Content-Disposition', 'attachment; filename="Example File.json"') ('X-Frame-Options', 'DENY') ('Vary', 'Cookie') ('X-Content-Type-Options', 'nosniff') ('Referrer-Policy', 'same-origin') ('Cross-Origin-Opener-Policy', 'same-origin') The following two statements print empty list print(response.getvalue()) # prints b'[]' print(json.loads(b"".join(response.streaming_content))) # prints b'[] I am trying to get to print the contents of the json file - 
        
HTTPSConnectionPool Error with pip install django
I am trying to install django in my windows pc. but I have same Error every time. I uninstalled python,my ide,disable firewall and antiviruse but my Error till exist. PS C:\Users\toranj> python -m pip install django Collecting django WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/d9/40/6012f98b14b64b4d3dc47b0c2f116fccbd0795ab35515d0c40dac73b81b8/Django-4.2-py3-none-any.whl WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/d9/40/6012f98b14b64b4d3dc47b0c2f116fccbd0795ab35515d0c40dac73b81b8/Django-4.2-py3-none-any.whl WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/d9/40/6012f98b14b64b4d3dc47b0c2f116fccbd0795ab35515d0c40dac73b81b8/Django-4.2-py3-none-any.whl WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/d9/40/6012f98b14b64b4d3dc47b0c2f116fccbd0795ab35515d0c40dac73b81b8/Django-4.2-py3-none-any.whl WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")': /packages/d9/40/6012f98b14b64b4d3dc47b0c2f116fccbd0795ab35515d0c40dac73b81b8/Django-4.2-py3-none-any.whl ERROR: Could not install packages due to an OSError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Max retries exceeded with url: /packages/d9/40/6012f98b14b64b4d3dc47b0c2f116fccbd0795ab35515d0c40dac73b81b8/Django-4.2-py3-none-any.whl (Caused by ReadTimeoutError("HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. (read timeout=15)")) - 
        
How to modify my ORM to show the date in the select?
I would appreciate your help friends since I am new and there are several things that I do not master! I have a data record and a date is saved in each of the records, then I need to display the information depending on the date it was saved, when viewing the date data in my select it is displayed as follows enter image description here This is the code of my forms where I create the select, I imagine that the answer to my problem is to modify the ORM (which I have tried in several ways and I can't do it) and the data must be distinct so that the month does not repeat class Report2Form(Form): reportDate = ModelChoiceField( queryset=ConsElect.objects.values_list('date', flat=True), widget=Select(attrs={ 'class': 'form-control', # ('F , Y') This is how it appears to me as 'April, 2023' }), ) This is my model class ConsElect(models.Model): pgd = models.ForeignKey(TipoPGD, on_delete=models.CASCADE, related_name='conselect') date= models.DateField(default=datetime.now) read_morning = models.IntegerField(default=0) read_day = mod I need help so that my select is as I need! - 
        
Django: django.urls.exceptions.NoReverseMatch: Reverse for 'view_name' not found. 'view_name' is not a valid view function or pattern name
I'm trying to run a test for my view and I get this error: Django: django.urls.exceptions.NoReverseMatch: Reverse for 'create' not found. 'create' is not a valid view function or pattern name. Here is my test: from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from users.models import User class UsersTests(TestCase): def setUp(self): self.client = APIClient() self.user = User.objects.create(chat_id=123456789, language='en') def test_create_valid_user(self): response = self.client.post( reverse('users:create'), data = { 'chat_id': 1234, 'language': 'en' }, format='json' ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(User.objects.count(), 2) users/urls.py: from django.urls import path from . import views app_name = 'users' urlpatterns = [ path('get-all/', views.get_all), path('create/', views.create), path('get-by-chat-id/<int:chat_id>/', views.get_by_chat_id), path('update/<int:chat_id>/', views.update) ] app/urls.py (main urls.py): from django.urls import path, include urlpatterns = [ path('users/', include('users.urls', namespace='users')), ] output of $ python manage.py show_urls: /users/create/ users.views.create /users/get-all/ users.views.get_all /users/get-by-chat-id/<int:chat_id>/ users.views.get_by_chat_id /users/update/<int:chat_id>/ users.views.update I believe the problem comes from reverse function, and I tried a lot of things and couldn't fix it. Please tell me how to fix it. - 
        
TemplateSyntaxError at /posts/post
I want to make the form display the value of the average rating for each post. Вот мой tamplate <a class="nav-link px-2 text-muted" href="{% url 'posts:post_detail' post.id %}"> <h2>{{ post.school_name }}</h2> <p>Average rating: {{ post_ratings.get(post=post).avg_rating }}</p> <p>Автор: {{ post.author }}</p> <p>Опубликовано: {{ post.created_at }}</p> <p>Обновлено: {{ post.updated_at }}</p> <a href="{% url 'posts:post_edit' post.id %}">Редактировать</a> <a href="{% url 'posts:post_delete' post.id %}">Удалить</a> </a> my view def post_list(request): posts = Post.objects.all() post_ratings = Comment.objects.values('post').annotate(avg_rating=Avg('score')) context = { 'posts': posts, 'post_ratings': post_ratings } return render(request, 'post_list.html', context) my models class Post(models.Model): school_name = models.CharField(max_length=200, default='') country = models.CharField(max_length=200, default='KZ') city = models.CharField(max_length=200, default='') content = models.TextField() website = models.CharField(max_length=200, default='') your_email = models.EmailField(default='') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() created_at = models.DateTimeField(auto_now_add=True) score = models.IntegerField(default=0, validators=[MaxValueValidator(5), MinValueValidator(1)]) def __str__(self): return self.text def get_absolute_url(self): return reverse('post_detail', args=[str(self.post.id)]) Why am I getting this error? I tried to change the lines in the tamplates <p>Average rating: {{ post_ratings.get(post=post.id).avg_rating }}</p> - 
        
Downloading the 'attachment' from the 'content-disposition'
Here are the items from the FileResponse object that was returned when I called the API to download the file. sample = c.get(<URL>) print(sample.items()) ('Content-Type', 'application/json') ('Content-Length', '2') ('Content-Disposition', 'attachment; filename="Example File.json"') ('X-Frame-Options', 'DENY') ('Vary', 'Cookie') ('X-Content-Type-Options', 'nosniff') ('Referrer-Policy', 'same-origin') ('Cross-Origin-Opener-Policy', 'same-origin') - 
        
How can i limit results of a For Tag link array?
I have a DB query that pulls users order details and lists them as "Transactions" On our main user content dashboard i want to limit these query to only show 5 results. `{% for order in user.userordertokens %} <tr> <td>Order Description</td> <td>{{ order.createdat|date('m/d/Y')}}</td> <td>{{ order.tokenamount|number_format(0, '.', ',')}} GLN</td> <td><span class="fw-bold text-success">{{ order.status}}</span></td> <td> <a href="{{path('dashboard_purchase_details', { transactionId: order.idencoded })}}" class='btn btn-primary'>View Details</a> </td> </tr> {% endfor %}` This is the code im using to pull the data. Can i use a limit [5] type code to limit how many results are shown? `[:5] 0, 5` I have tried the following but both are not working, What am i doing wrong? - 
        
Media images not displaying from AWS S3 in django app
It seems that I've configured all right, and in the dev tools or terminal no errors. Even the file crash icon disappeared. settings.py (i removed the name and other data that shouldn't be public STATIC_URL = "staticfiles/" STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" # amazon s3 MEDIAFILES_LOCATION = 'media' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % os.environ.get('') AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' AWS_STORAGE_BUCKET_NAME = '' AWS_DEFAULT_ACL = 'public-read' AWS_S3_REGION_NAME = '' AWS_S3_VERIFY = True # config/settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media/images/') MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) models.py index.html {% for auction in allAuctions %} <div class="col"> <div class="card shadow-sm"> <img src="{{ auction.image.url }}" class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false" style="object-fit: cover;"> {% endfor %} my s3 policy also the s3 bucket and how it looks like - 
        
Django - cannot pass error message to context
I have a view responsible for inviting users to note: def invite_user(request, pk): note = get_object_or_404(Note, pk=pk) form = InviteUser() err = False if request.method == 'POST': form = InviteUser(request.POST) if form.is_valid(): username = form.cleaned_data['username'] if User.objects.filter(username=username).exists() and username != request.user.username and not Note.objects.filter(members__contains = [username], id=note.id): notification = Notification(message=f"Do you want to join to {User.objects.get(username=note.user)}'s note: {note.title}?", user=User.objects.get(username=username), note_id=note.id) notification.save() else: print('Error') err = True return redirect('show', pk=note.id) if err: context = { 'form': form, 'error': 'You cannot invite this user!' } return render(request, context) else: context = { 'form': form, } return render(request, context) Template: {% if error %} <h1>{{ error }}</h1> {% endif %} When I pass correct user invitation is sent, but when there is error I see print in console, but there is not h1 with error in templete. What I am doing wrong? - 
        
react-redux Place Order api/orders/add/ 500(internal server error)
I am building an ecommerce project with django and react. this is my django order views: from django.shortcuts import render from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated, IsAdminUser from rest_framework.response import Response from base.models import Product, Order, OrderItem, ShippingAddress from base.serializers import ProductSerializer, OrderSerializer from rest_framework import status @api_view(['POST']) @permission_classes([IsAuthenticated]) def addOrderItems(request): user = request.user data = request.data orderItems = data['orderItems'] if orderItems and len(orderItems) == 0: return Response({'detail': 'No Order Items'}, status=status.HTTP_400_BAD_REQUEST) else: order = Order.objects.create( user=user, paymentMethod=data['paymentMethod'], shippingPrice=data['shippingPrice'], taxPrice=data['taxPrice'], totalPrice=data['totalPrice'] ) shipping = ShippingAddress.objects.create( order=order, address=data['shippingAddress']['address'], city=data['shippingAddress']['city'], postalCode=data['shippingAddress']['postalCode'], country=data['shippingAddress']['country'], ) for i in orderItems: product = Product.objects.get(_id=i['product']) item = OrderItem.objects.create( product=product, order=order, name=product.name, qty=i['qty'], price=i['price'], image=product.image.url, ) product.countInStock -= item.qty product.save() serializer = OrderSerializer(order, many=False) return Response(serializer.data) order_urls.py: from django.urls import path from base.views import order_views as views urlpatterns = [ path('add/', views.addOrderItems, name='orders-add'), ] now, backend. orderReducers.js: import { ORDER_CREATE_REQUEST, ORDER_CREATE_SUCCESS, ORDER_CREATE_FAIL } from "../constants/orderConstants" export const orderCreateReducer = (state={}, action) =>{ switch(action.type){ case ORDER_CREATE_REQUEST: return{ loading: true, } case ORDER_CREATE_SUCCESS: return{ loading: false, success: true, order: action.payload, } case ORDER_CREATE_FAIL: return{ loading: false, error: action.payload, } default: return{ state } } } orderActions.js: import axios from 'axios' import { ORDER_CREATE_REQUEST, ORDER_CREATE_SUCCESS, ORDER_CREATE_FAIL } from … - 
        
Django - can login only as admin
i've lost possibility to login to page as non-admin user. For Admin credentials everything works. Can't figure out what happend. I was searching for the issue commenting out admin custom things, adding full permissions from admin site and nothing. Views: def login_user(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/home') else: messages.success(request, ("Invalid credentials")) return redirect('login') else: return render(request, 'authenticate/login.html', {}) HTML: <form action="" method=POST class="login"> {% csrf_token %} <input type="text" name="username" placeholder="login"> <br> <input type="text" name="password" placeholder="password"> <br> <button type="submit">Login</button> </form> Admin: class Supplier_Admin(admin.ModelAdmin): fields = ('id','company_name','currency', 'legal_form', 'accounting_standards', 'owner_structure', 'industry_sector', 'date_of_establishment', 'start_up', 'email_address', 'web') admin.site.register(Supplier, Supplier_Admin) class CustomUserAdmin(admin.ModelAdmin): list_display = ('username', 'email', 'user_id') def user_id(self, obj): return obj.id user_id.short_description = 'ID' admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) Model: class Supplier(models.Model): id = models.IntegerField(primary_key=True) company_name = models.OneToOneField(User, max_length=120, on_delete=models.CASCADE) currency = models.CharField('Currency', max_length=4, blank=True) legal_form = models.CharField('Legal form', max_length=100, choices=legal_form_options, default='Sole proprietorship', blank=True) accounting_standards = models.CharField('Accounting standards', max_length=100, blank=True) owner_structure = models.CharField('Owner structure', max_length=100, blank=True) industry_sector = models.CharField('Industry sector', max_length=100, choices=industry_sector_options, default='Advertising', blank=True) date_of_establishment = models.DateField('Date of establishment', default=date.today, blank=True) start_up = models.CharField('Start-up', choices=start_up_options, default='No', max_length=4, blank=True) email_address = models.EmailField('Email address', blank=True) web = models.URLField('Website address', … - 
        
Which must be html templates for that Django view?
I don't know how to create valid html templates for that Django views with forms, I don't understand how it works, please explain me it. view.py: from django.shortcuts import redirect, get_object_or_404 from .models import Test, Question, Answer from .forms import QuestionForm, AnswerForm, QuestionSetForm, QuestionFormset from django.views.generic import CreateView, UpdateView from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_lazy, reverse from django.forms.formsets import formset_factory class QuestionsAddView(LoginRequiredMixin, CreateView): question_form_class = QuestionForm answer_form_class = AnswerForm template_name = 'tests/questions_add.html' def get_object(self): id_test = self.kwargs['id_test'] test = Test.objects.filter(pk = self.kwargs['id_test']).first() question = Question.objects.all().last().id+1 return question def count(self): return Test.objects.filter(pk = self.kwargs['id_test']).first().questions_count def get_formset(self, form): return formset_factory(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['id_test'] = self.kwargs['id_test'] context['test'] = Test.objects.filter(pk = self.kwargs['id_test']).first() context['question_form'] = self.question_form_class context['answer_form'] = self.answer_form_class return context def form_question_valid(self, form_question, form_answer): num_q = 0 y = 0 z = 0 for f in form_question: num_q+=1 self.object = f.save(commit = False) self.object.test = Test.objects.filter(pk = self.kwargs['id_test']).first() self.object.num = num_q f.save() count = self.object.answer_count num_a = 0 for z in range(count): num_a += 1 print(count) self.object = form_answer[y].save(commit = False) self.object.question = Question.objects.all().last() self.object.num = num_a form_answer[y].save() y += 1 return form_question, form_answer def get(self, request, *args, **kwargs): self.object = None FormsetQuestion = self.get_formset(QuestionForm) FormsetAnswer = self.get_formset(AnswerForm) … - 
        
The carousel does not work, when I click the left or right button it does not do anything, assuming I'm not a Frontend engineer, what am I doing wrong
The carousel does not work, when I click the left or right button it does not do anything, assuming I'm not a Frontend engineer, what am I doing wrong here. The carousel does not work, when I click the left or right button it does not do anything, assuming I'm not a Frontend engineer, what am I doing wrong here. I used ChatGPT to fix it but it could not fix it, I hoped that the carousel moves and displayed the products - 
        
Unable to login to Django admin website after setting SESSION_COOKIE_NAME="__Host-Session"
I have a Django application running locally. I wanted to change the SESSION_COOKIE_NAME to something with the prefix "__Host", so cookies are only sent to the host that initially set the cookie. However, I am unable to login into the admin page or the application after I do that. Setting SESSION_COOKIE_NAME to any other name works well, just not with prefix "__Host ". Any idea what might be causing this? Could the fact that I am running it locally(so HTTP instead of HTTPS) have something to do with it? - 
        
How cam I count current active users on the site in Django or DRF
I have tried too many ways but still not found any solutions yet I have tried for current active user in my site. - 
        
Login function not working in Django Python project
Description: I am working on a Django project which is a virtual wallet with admin and multi user login with interchangeable amounts. I am having issues with the login functionality. I have cloned the repository from GitHub (https://github.com/btmstage3/virtual-wallet-with-admin-and-multi-user-login-with-interchangeble-amounts-in-python.git) and followed the installation instructions in the README file. However, when I try to login with the default superuser credentials (username: admin, password: password), I get an error message saying "Invalid login credentials". I have checked my code and compared it to the code in the repository, but I cannot figure out what is causing the issue. I am new to Django and would appreciate any help or advice on how to fix this issue. Here is the code for my login view function: python from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Invalid login credentials') return redirect('login') return render(request, 'login.html') I would appreciate any suggestions or guidance on what could be causing this issue. Thank you in advance for your help. I've also checked that the … - 
        
he server responded with a status of 404 (Not Found)
django template rendering i was try to inter the log into the web Failed to load resource: the server responded with a status of 404 (Not Found) what are the possible senarioes for thise problem ? django template rendering i try that if the problems is Missing file Incorrect file path - 
        
Display image in template based on ID of image in Django
I'm building a small page in Django. For this page I have a model that stores images for the webpage. These can be updated in the future. I'm struggling to display the images properly. My model looks like this: def image_upload_handler(instance, filename): fpath = pathlib.Path(filename) new_fname = str(uuid.uuid1()) return f"{instance.imgLocation}/{new_fname}{fpath.suffix}" #models class coreImage(models.Model): imageName = models.CharField(max_length=255, blank=False) image = models.ImageField(upload_to=image_upload_handler) imgLocation='headerImages' def __str__(self): return f"{self.imageName} in {self.imgLocation}" The view looks like this: def core_view(request): context = { 'image' : coreImage.objects.all(), 'drinks' : DrinkRecipe.objects.all(), 'ingredients' : Ingredient.objects.all() } return render(request,'rhumSite/home.html',context=context) How do i get image with id=1 to show up in my template? I've tried this: <img class='page-img' src={{image.image(id=1).url}}> As you have guessed, this doesnt work. What am I doing wrong? Thanks in advance. - 
        
how to pass dynamic url values into the context dictionary?
blog_confirm_delete.html <form method="POST" action=""> {% csrf_token %} <h2>Are you sure you would like to delete this post?</h2> <button type="submit" value="send" class="btn btn-danger">Yes, Delete</button> <button class="btn btn-info mb-8"> <a class="text-white" href="{% url 'blog-detail' post.id %}">Cancel</a> </button> </form> views.py class BlogDeleteView(SuccessMessageMixin,LoginRequiredMixin,TeacherOwnerPassesTestMixin,DeleteView): model = Post template_name = "postings/blog_confirm_delete.html" success_url = reverse_lazy('blog-list') success_message = "Your post has been deleted!" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['list_title'] = "Our Blog" context['list_url'] = "blog-list" context['detail_title'] = "Delete Post" context['cancel'] = ??? return context So currently I have to hard code the "Cancel" button's url for every "X_confirm_delete.html" template that I have. Now I would like to pass in a dynamic url value for each DeleteView so that I can reduce all DeleteView into using one simple template. How can I do this? Thank you for helping me in advance! - 
        
Affichage de données MYSQL sur une template django [closed]
Bonjour, je suis en train de réaliser une application avec le framework django pour créer un gestionnaire d'emploi du temps pour des techniciens. J'arrive à afficher mon calendrier en utilisant full calendar mais j'aimerai récupérer les données stockées dans ma BD (pour l'instant local) MySQL et les afficher directement dans mon calendrier. Voici ma template : {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Calendrier</title> <!-- Inclure les fichiers CSS et JS nécessaires --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.js"></script> <script> $(document).ready(function() { // Initialisation du calendrier $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,basicWeek,basicDay' }, defaultDate: moment(), editable: true, eventLimit: true, // Permet d'afficher "plus" lorsqu'il y a trop d'événements pour un jour events: [ {{ tache_list|safe }} ], }); }); </script> <style> body { margin-top: 40px; text-align: center; font-size: 14px; font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif; } #calendar { max-width: 900px; margin: 0 auto; } </style> </head> <body> <nav class="navMenu"> <ul> <li><a href="{% url 'home' %}" class="highlight">Calendrier</a></li> </ul> </nav> <div id="calendar"></div> </body> </html> Voici ma vue : def calendrier(request): events = [] for evenement in Tache.objects.all(): event = { 'id': evenement.id, 'title': evenement.pn, 'start': evenement.dateD.strftime('%Y-%m-%d'), 'end': evenement.dateF.strftime('%Y-%m-%d') } events.append(event) … - 
        
My django project down when the SSH session is closed (running in the supervisor, gunicorn and nginx)
I've running my jdango project (name:A below) in the AWS EC2 with the Gunicorn and Nginx. I also installed Supervisor as to keep the A running. All running status(supervisor, gunicorn, nginx) are "active (running)" But I found the supervisor does not achieve that. I will attaach the conf info below, plz help me to find out how to set the supervisor. THX EC-2 Linux version 5.10.167-147.601.amzn2.x86_64 PATH: 1 Virtual environment: `/home/myname/phpdao/bin` 2 Django project: `/home/myname/project/phpdao (where manage.py located)` 3 Supervisor: `/home/etc (where supervisor.conf & supervisord.conf located)` 4 Gunicorn: `/home/myname/phpdao/bin` `/home/ec2-user/conf (where gunicorn_config.py located)` 5 Nginx: `/etc/nginx (where nginx.conf located)` Configuration: 1 Supervisor [unix_http_server] file=/home/ec2-user/etc/supervisor/var/supervisor.sock port =127.0.0.1:9001 [program:A] command=/home/ec2-user/phpdao/bin/gunicorn phpdao.wsgi:application --bind 0.0.0.0:8000 directory=/home/ec2-user/project/phpdao user=myname autostart=true autorestart=true redirect_stderr=true stout_logfile=/home/ec2-user/supervisor/phpdao.stdout.log steer_logfile=/home/ec2-user/supervisor/phpdao.stderr.log 2 Gunicorn command = '/home/ec2-user/phpdao/bin/gunicorn' pythonpath = '/home/ec2-user/project/phpdao' bing = 'public IP:8000' workers = 3 raw_env = 'DJANGO_SETTINGS_MODULE=phpdao.settings' errorlog = '/var/log/gunicorn/error.log' accesslog = '/var/log/gunicorn/access.log' loglevel = 'debug' timeout = 60 keepalive = 2 worker_class = 'gevent' 3 Nginx server { listen 80; listen [::]:80; server_name www.A.com; access_log /home/ec2-user/nginx/phpdao.access.log; root /home/ec2-user/project/phpdao/phpdao1/templates; location /static/ { alias /home/ec2-user/project/phpdao/phpdao1/static; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_redirect off; } # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; error_page … - 
        
Override result_list templatetag in Django
I have custom change_list.html and change_list_results.html and would like to pass data from model admin. I can get the data on change_list.html but not in change_list_results.html. After researching on the internet the problem is in change_list_results.html, it's using templatetag result_list, by default take_context is set to False. Below is the code of my model admin: class HistoryAdmin(UpdateUserAdminMixin, admin.ModelAdmin): list_filter = ( ('created_date', DateRangeFilter), ) list_per_page = sys.maxsize actions = None list_display_links = None list_display = ('created_date', 'patient', 'price', 'payment') readonly_fields = ('created_date', 'updated_date') def get_rangefilter_created_date_default(self, request): return (datetime.date.today, datetime.date.today) def changelist_view(self, request, extra_context=None): start_date = datetime.datetime.strptime(request.GET.get('created_date__range__gte'), "%d-%m-%Y").date() end_date = datetime.datetime.strptime(request.GET.get('created_date__range__lte'), "%d-%m-%Y").date() default_start_date = History.objects.first().created_date.date default_end_date = History.objects.latest('created_date').created_date.date results = History.objects.filter(created_date__range=(start_date, end_date)) total_payment = str(results.aggregate(Sum('payment'))['payment__sum']) total_price = str(results.aggregate(Sum('price'))['price__sum']) extra_context = {'title': CONSTANTS.MODEL_SINGLE_HISTORY, 'total_payment': total_payment, 'total_price': total_price} print(f'{results.values} {total_payment} {total_price}') return super(HistoryAdmin, self).changelist_view(request, extra_context=extra_context) I can access total_payment and total_price in change_list.html like this: {{ total_payment }} {{ total_price }} Can anyone please help on how to access it in change_list_results.html? Thanks in advance. - 
        
'ordering' must be a tuple or list (even if you want to order by only one field)
class Product(models.Model): publishDate = models.DateTimeField(max_length=20,default=timezone.now,verbose_name='time') views = models.PositiveIntegerField('view', default=0) class Meta: verbose_name = 're' verbose_name_plural = 're' ordering = ('-publishDate',) it says: 'ordering' must be a tuple or list (even if you want to order by only one field). - 
        
How to redirect login to a home page whose template is inside app not at project level :python django
Normally using inbuilt login system in django the login page is set inside the projects setting.py LOGIN_REDIRECT_URL = "home" The above code works if the template is at a project level directory i.e 'django_project/templates'. What if the templates are inside app i.e 'django_project/app_name/templates' ? - 
        
sudo : The term 'sudo' is not recognized as the name of a cmdlet, function, script file, or operable program
docker-compose.yml version: '3' services: build: . command: python manage.py runserver 0.0.0.0.:8000 volumes: - .:/app ports: - "8000:8000" Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ requirements.txt Django>=2.2 I am getting the error on vs code. I don't know how to solve it.