Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Do I need to use a Transactional Email Service Provider to send emails with Django?
Context I would like to send transactional Email through Django. I understand that there are Transactional Email Service Provider (ESP) that faciliatates this endeavour. The obvious issue I see with this is the cost associated with it. (I know there ESP with tier plans for small amounts of emails) Questions So, I have a few questions regarding this topic: Do I need a Transactional Email Service Provider to send emails through Django? What are the pros and cons of using an ESP for transactional emails in Django? If I decide to do it on my own (without using a ESP), does it scale well? What other issues can you see, that I'm not aware of, and you think they might be relevant? Final question If my conclusion would be not to use an ESP, what steps should I take to send emails through Django? I've looked at a Reddit thread where they discuss this topic. But almost everyone keeps recommending using an ESP. -
How do I solve 'The view didn't return an HttpResponse object. It returned None instead.' error in Django?
The view didn't return an Httpresponse object. It returned None instead. enter image description here I am getting "The view didn't return an HttpResponse object. It returned None instead." When I clicked on edit button its giving me error url.py: urlpatterns=[ path("client",views.client,name="client"), path("show_client/<str:pk>",views.show_client,name="show_client"), path("client_edit",views.client_edit,name="edit_client"), ] views.py: def show_client(request,pk): a_url = "" payload = json.dumps({ "grant_type": "client_credentials" }) elastic_api_key="" headers = { 'Authorization': 'Apikey ' + elastic_api_key, 'Content-Type': 'application/json' } auth_response = requests.request("POST", a_url, headers=headers, data=payload) auth_response_json = auth_response.json() # print(auth_response_json) access_token = auth_response_json['access_token'] print(access_token) url = "" payload = "" headers = { 'Authorization': "Bearer " + access_token, 'Content-Type': 'application/json' } response = requests.request("GET", url, headers=headers) res_data = response.json() dt = res_data['hits']['hits'] html: client.html: <table id="order-listing" class="table"> <thead> <tr> <th>Customer Name</th> <th>Jira Id</th> <th>Time zone</th> <th>Signed Date</th> <th>Action</th> </tr> </thead> <tbody> {% for i in data_lst %} <!-- {{i.organization_name}} --> <tr> <td>{{i.organization_name}}</td> <td>{{i.organization_id}}</td> <td>{{i.timezone}}</td> <td>{{i.signed_date}}</td> <td> <a href="{% url 'show_client' i.organization_name %}" style="border: 1px solid gray;padding:10px;color:#4bda2f;outline-style:none"><i class="fa fa-eye"> View</i></a>&nbsp; <a href="" style="border: 1px solid gray;padding:10px;color:#eb2805;">Delete</a> </td> </tr> {%endfor%} </tbody> </table> for i in dt: customer_dt =i customer = customer_dt['_source']['customer'] if pk == customer['organization']['organization_name']: # print("---^^organization^^----",customer['organization']) org = customer['organization'] poc=customer['contacts'][0]['port53'] client = customer['contacts'][1]['customer'] services = customer['services'][0]['socaas'] crtical_assets = customer['criticalAssets'][0]['VMs'] print(crtical_assets) context={'org':org,'poc':poc,'client':client,'services':services,'vm':crtical_assets} … -
Create SQL function using Django
I am working on a project that allowed single user in a database. Now say, particular user with name Jazz logs in and either edit or create blog and save. Each blog has incremental unique id , for example, jazz_1, jazz_2 and so on. When Jazz creates the new blog, new id will be jazz_3. Now I want to allow multiple user in a single database. So I have to handle the counter for each user. Say, new user with name Joy logged in and created the new blog then id will set as joy_1 for the new blog. To implement this, I was planning to create a function in database which will check the last counter for the user, increment the counter and return the id CREATE FUNCTION `get_id`(user_id int, invoice_prefix varchar(15)) RETURNS int BEGIN DECLARE suffix INT; INSERT INTO id_counter (user_id, invoice_prefix, counter) VALUES(user_id, invoice_prefix, 1) ON DUPLICATE KEY UPDATE counter = counter + 1; SELECT counter INTO suffix FROM id_counter WHERE user_id = user_id; RETURN(suffix); END So I have 2 queries: How should I create function in the database using Django? So that anytime if I scrap the old database and run the migrations from Django, tables … -
ValueError No handler Django Channels Chat app
I'm creating a chat application that some people can chat to each other in some rooms and now I got this errors while sending messages: raise ValueError("No handler for message type %s" message["type"]") ValueError: No handler for message type chat_message Consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self,text_data): data=json.loads(text_data) message = data['message'] username = data['username'] room = data['room'] await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message':message, 'username' : username, 'room': room , } ) async def chat_message(self,event): message=event['message'] username=event['username'] room=event['room'] await self.send(text_data=json.dumps({ 'message':message, 'username' : username, 'room': room , })) HTML TEMPLATE {% extends 'core/base.html' %} {% load static %} {% block cont %} <div class='rooms'> <p class='bolder'>Username</p> <p>The messages ......</p> </div> <form method="post" action="." > <div> <input type="text" name="content" class="input" placeholder="write here..." id="chat-message-input"> <button class="bluebot" id="chat-message-submit">Submit</button> </div> </form></div></div> {% endblock %} {% block scripts %} {{ room.slug|json_script:"json-roomname" }} {{ request.user.username|json_script:"json-username" }} <script> const userName = JSON.parse(document.getElementById('json-username').textContent); const roomName = JSON.parse(document.getElementById('json-roomname').textContent); const chatSocket = new WebSocket( 'ws://'+window.location.host+'/ws/'+ roomName+ '/' ); chatSocket.onmessage=function(e){ console.log('onmessage') const data = JSON.parse(e.data); if(data.message) … -
Access Foreign Key's Queryset
I have these models: class Source(models.Model): name = models.CharField(max_length=255, blank=True, null=True) feed_url = models.CharField(max_length=512) .... class Post(models.Model): source = models.ForeignKey(Source, on_delete=models.CASCADE, related_name='posts') title = models.TextField(blank=True) body = models.TextField() .... class FeedCategory(models.Model): feed_category = models.CharField(max_length=128, choices=FEED_CATEGORIES, blank=True) source = models.ForeignKey(Source, on_delete=models.CASCADE) And I want to make a Queryset where I get all FeedCategories but I'd like to also include in there their related posts. So If I use: feeds = FeedCategory.objects.select_related('source').all() my queryset does not return the posts. I tried using: feeds = FeedCategory.objects.select_related('source').all() posts = Post.objects.filter(source_id__in=feeds.values_list('source_id', flat=True)) which works but its on two different queries. What I basically want to do is have a single query which shows the category and the related source's posts in order to bring them up on frontend so I could use something like: {% for feed in feeds %} {{feed.category}} {% for post in feed.source_set %} {{post.body}} {% endfor %} {% endfor %} My thinking was something with annotate but how exactly do I do that? -
Django os module is frozen
Upon changing my env variable from hardcoded ones to the ones in .env file, I encountered an issue with my os import Simplified: import os DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('AWS_RDS_NAME'), 'USER': os.environ.get('AWS_RDS_USER'), 'HOST': os.environ.get('AWS_RDS_HOST'), 'PASSWORD': os.environ.get('AWS_RDS_PASSWORD'), 'PORT': os.environ.get('AWS_RDS_PORT'), } } When starting the server I get an error, as if my env file did not exist. When I print os (print(os)) I get an error I never got : <module 'os' (frozen)> I don't record doing something different than usual. Does anyone know what is this? Thanks a lot -
Add a select field on Django form without saving on database
I have a form that refers to a model into the database so, each time is filled and a user click SUBMIT, the form is saved on the database. The form has a series of fields took directly from the Django Model. See below. My problem is that, I want to add a new field, a select field, that have as option inside data I've processed from the backend via the home view and, when the form is submitted, it passes the data selected to the same view so I can elaborate from there. I don't want this field to be saved on the database with the form.save() Is there a way to have this kind of "hybrid" form where part of the data/field are taken from the database and others are just added by me? models.py class Test(models.Model): testTitle = models.CharField(max_length=50, blank=False, null=False) testDescription = models.TextField() sequenzaTest = models.ForeignKey("SequenzaMovimento", null=True, on_delete=models.SET_NULL) numeroCicli = models.IntegerField(blank=False, null=False) dataInizio = models.DateTimeField(auto_now_add=True) dataFine = models.DateTimeField(blank=False, null=True) testFinito = models.BooleanField(default=False) testInPausa = models.BooleanField(default=False) dataUltimaPausa = models.DateTimeField(null=True, blank=True) workerID = models.CharField(max_length=200, blank=True, null=True) def __str__(self): return self.testTitle class StartWorker(ModelForm): class Meta: model = Test fields = ('testTitle', 'testDescription', 'sequenzaTest', 'numeroCicli') widgets = { 'testTitle': forms.TextInput(attrs={'class':'form-control'}), … -
I need a simple python Django login example using database credentials
Could you please help me find an example of a simple login page where the users can be authenticated using user/password from a database postgres or mysql(I can change that afterwards from mysql to PG )? I googled for almost 1 week but wasn't able to find a django python example. I actually found a Flask example - and: that is exactly what I need - but not using Flask - I need Django. Here the flask example I found: Flask_Example In this Flask example is - most important : login window on the first place after starting of the web application, no TABs, no Navbar, no sidebar, no first click on a button "Login" and then login, nothing really nothing except a white blank page with a little login window in the middle of the screen where you can put your user and password and if the credentials are correct in the database, then you will be redirected to a simple page containing whatever inside. All that what I wrote here is exactly in that Flask example, but... I need a Django and no Flask. There are so many professional people who are writing Django code examples... but there … -
Automatic creation of third-level domain names
I'm developing a kind of small social website for a scientific working group (studying birds of prey) on Python/Djando, the server works on Ubuntu + Nginx + Gunicorn. There are personal sections for the members of the group. To make the URLs more beautiful, I'd like to make them visible as third-level domains. For example, a member creates his/her page mysite.net/persons/member-name/, and it is accessible as member-name.mysite.net. Is it possible to make the 3-level domains automatically, on user section create? If so, how to do it? If not (or too complicated), how it is possible to do it manually? As I think, the simple redirect is not what I want, since I want all internal or incoming links to be to this 3-level domain, not sub-directory. I found only one answer to this question, but it is pretty old (10 years ago) and is missing exact details, so I don´t know how to implement it. It suggests to create NS records for the subdomain in the mysite.com zone file, but I don´t know where exactly this zone is (at my hosting provider?), and not sure that I have access to it. Thanks for any advice, and especially for detailed ones! -
Django ajax listview editing objects one by one
Hi I have a django project where im rendering a listview with ajax and i wana update one object in this list view with a modal and ajax. I am struggling to understand because i think im not familiar enough with ajax and webdevelopment. What i want to be beable to do is basically edit any of those single objects being rendered with a modal form. i get some random objects data when i click edit button. I am not sure what other information i can provide but please let me know if more clarity needed. -
Django template language 2023 alternative stacks
I've been playing around with Django where I come from PHP(Bootstrap 4) background with a few projects under my belt. As I'm trying things around using Djnago default template language, I was looking for alternatives of the default template language. I found some people saying that the default template is outdated and others claiming to use Jinja2. As per ChatGTP, it listed the following template engines: Jinja2: Mako: Handlebars: Mustache: Liquid: I will be using bootstarp, but I wanted to have a comprehensive overview regarding the way forward and best options used in 2023 out there from experienced dev community. Thank you for your understanding. -
Heroku Error R14 (Memory quota exceeded) when I use ML models (python, django)
I have deployed django app with ML models on heroku. But when I use the next code in django view function for make prediction with open(model_path, "rb") as f: model = pickle.load(f) pred_proba = model.predict_proba(mwp)[0] del model I receive the next message: Process running mem=726M(141.8%) 2023-05-31T09:23:53.646613+00:00 heroku[web.1]: Error R14 (Memory quota exceeded) And if I load my ML model again the process memory increase and in the final my app crashes. I can't understand why the memory increasing occurs, because I delete my model after prediction using del model? What can I do to solve this problem? Thank you. -
NewsAPI not able to fetch news of a given city
So, I'm basically trying to make a website that brings information about cities when you input a city name. Right now all I'm able to, successfully, display is the weather report of a city. I'm trying to bring some news headlines as well. I tried this code. And this, as far as I know about the language, should have worked. views.py from django.shortcuts import render import requests import json from datetime import datetime def index(request): try: if request.method == 'POST': API_KEY = '#################################' city_name = request.POST.get('city') url = f'https://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={API_KEY}&units=metric' response = requests.get(url).json() current_time = datetime.now() directives, it will take this format Day, Month Date Year, Current Time formatted_time = current_time.strftime("%A, %B %d %Y, %H:%M:%S %p") information in one dictionary city_weather_update = { 'city': city_name, 'description': response['weather'][0]['description'], 'icon': response['weather'][0]['icon'], 'temperature': 'Temperature: ' + str(response['main']['temp']) + ' °C', 'country_code': response['sys']['country'], 'wind': 'Wind: ' + str(response['wind']['speed']) + 'km/h', 'humidity': 'Humidity: ' + str(response['main']['humidity']) + '%', 'time': formatted_time } else: city_weather_update = {} context = {'city_weather_update': city_weather_update} return render(request, 'index.html', context) except: return render(request, 'error.html') def news(request): try: if request.method == 'POST': API_KEY = '#################################' city = request.POST.get('city') url = f'https://newsapi.org/v2/top-headlines?q={city}&apiKey={API_KEY}' response = requests.get(url) data = response.json() articles = data['articles'] else: articles = {} … -
Vagrant was unable to connect to the virtual machine VirtualBox
I can't connect to the virtual machine. Could you help me with my problem? Here is the log from GitBash: py@cpython MINGW64 ~/courses/profiles-rest-api (master) $ vagrant up Bringing machine 'default' up with 'virtualbox' provider... ==> default: Box 'ubuntu/bionic64' could not be found. Attempting to find and install... default: Box Provider: virtualbox default: Box Version: ~> 20200304.0.0 ==> default: Loading metadata for box 'ubuntu/bionic64' default: URL: https://vagrantcloud.com/ubuntu/bionic64 ==> default: Adding box 'ubuntu/bionic64' (v20200304.0.0) for provider: virtualbox default: Downloading: https://vagrantcloud.com/ubuntu/boxes/bionic64/versions/20200304.0.0/providers/virtualbox.box Download redirected to host: cloud-images.ubuntu.com default: ==> default: Successfully added box 'ubuntu/bionic64' (v20200304.0.0) for 'virtualbox'! ==> default: Importing base box 'ubuntu/bionic64'... ==> default: Matching MAC address for NAT networking... ==> default: Checking if box 'ubuntu/bionic64' version '20200304.0.0' is up to date... ==> default: Setting the name of the VM: profiles-rest-api_default_1685446821258_41886 Vagrant is currently configured to create VirtualBox synced folders with the SharedFoldersEnableSymlinksCreate option enabled. If the Vagrant guest is not trusted, you may want to disable this option. For more information on this option, please refer to the VirtualBox manual: https://www.virtualbox.org/manual/ch04.html#sharedfolders This option can be disabled globally with an environment variable: VAGRANT_DISABLE_VBOXSYMLINKCREATE=1 or on a per folder basis within the Vagrantfile: config.vm.synced_folder '/host/path', '/guest/path', SharedFoldersEnableSymlinksCreate: false ==> default: Clearing any previously set … -
Is there a way to fetch and serialize only a portion of data on demand/onclick in Django to improve performance?
I want to fetch a portion of the data and display it on demand/onclick when a user requests for it from django and serialize it. At the moment, I fetch all data to the client which could cause performance issues as the application scales. How can I achieve that using my get code snippet below. It would be great if anybody could help me out with what I am trying to solve. Thank you so much in advance. def get(self, request, hashid=None, lang=None): try: if hashid: pk_id = settings.LKC_HASH.decode(hashid)[0] disease = Disease.objects.get(pk=pk_id) serializer = CategoriesSerializer(disease) else: diseases = Disease.objects.values('id', 'translations__subcategory', 'translations__name').all() serializer = CategoriesSerializer(diseases, many=True) return Response(serializer.data, status=status.HTTP_200_OK) except Disease.DoesNotExist: return Response({'error': 'Disease Does Not Exist!'}, status=status.HTTP_404_NOT_FOUND) except Exception as e: capture_exception(e) return Response({'error': 'There was an error while fetching the diseases!'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) -
How to Properly Use "Sign In With Google" Button on Django Web App using Django all-auth
In my Django web app(Currently not in production), i want to use all-auth for signing in users with their Google account and that is working by using the below form for social account. //templates/socialaccount/login.html {% extends "socialaccount/base.html" %} {% load i18n %} <h1 class="display-4">{% blocktranslate with provider.name as provider %}Sign In Via {{ provider }}{% endblocktranslate %}</h1> <p>{% blocktranslate with provider.name as provider %}You are about to sign in from {{ provider }}.{% endblocktranslate %}</p> {% endif %} <form method="post"> {% csrf_token %} <button class="btn btn-outline-info" type="submit">{% translate "Sign In" %}</button> </form> after clicking on sign in button it is opening the new url like - https://accounts.google.com/o/oauth2/v2/auth/oauthchooseaccount?client_id=5649........apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Faccounts%2Fgoogle%2Flogin%2Fcallback%2F&scope=profile&response_type=code&state=ch...kO&access_type=online&service=lso&o2v=2&flowName=GeneralOAuthFlow that's asking me to choose the Google account, after i select my account it signs me in and redirect to the django app's homepage. which is working as expected, But after reading the Google Brand Guidelines, i came to know we should use the sign in with google button that comply their guidelines like in their documentation - https://developers.google.com/identity/gsi/web/guides/personalized-button So how can i use that button that will comply Google's guidelines for signing in and does not disturb the login and authentication flow. i create the button with Google button generator for sign … -
Django static files not loading, all settings seemingly correct
I've setup several django sites in the past, I'm not new to django by any means. I just setup a new site a few hours ago, and frustratingly I can not get any static files to load when accessing the site through a browser. It's a default django install, almost nothing has been changed except a new app made and a few core changes to settings.py relevant settings are: STATIC_ROOT = "/home/jake/apps/mysite-static/" STATIC_URL = '/static/' I've also tried STATIC_URL = 'https://example.com/static/' In my static dir, I have a file test.txt, so the path is /home/jake/apps/mysite-static/test.txt, which means I should be able to access that file in a browser via https://example.com/static/test.txt Error log reports Not Found: /static/test.txt, and error page in browser with Debug=True shows django going through my urls.py and failing to find a match. I have other django sites already running with basically the exact same settings (just different paths because of different project names), so I'm very confused why this simple setup isn't woring here. What am I missing? -
Common method for DRF model Viewset
I have multiple model viewsets that overrides perform_create as below. def perform_create(self, serializer): user=self.request.user instance = serializer.save(user=self.request.user) I am inserting this codes for every modelviewsets I am creating. Is there any way to make this more structured instead of inserting codes everytime? -
Getting '502 Bad Gateway nginx/1.18.0 (Ubuntu)' error on AWS EC2 instance while deploying Django app
My Django App deploy on AWS EC2 instance There I install nginx server this in nginx.conf file` user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; types_hash_max_size 2048; # server_tokens of proxy_read_timeout 300; proxy_connect_timeout 300; proxy_send_timeout 300; proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } #mail { # # See sample authentication script at: # # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript # # # auth_http localhost/auth.php; # # pop3_capabilities "TOP" "USER"; # # imap_capabilities "IMAP4rev1" "UIDPLUS"; # # server { # listen localhost:110; # protocol pop3; # proxy on; # } # # server { # listen localhost:143; # protocol imap; # proxy on; # … -
Can I input any character value to form which is defined as ForeignkeyField?
First, This is my first question in stack overflow, please bear with me. Using Django. I want to input a character value to form defined as Foreignkey field (in this case, it's category form). I appreciate giving me a solution for this, also telling me which is best idea to input a character value as someone want to input to category form or only input value> to category form. models.py class Category(models.Model): # id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=15) def __str__(self): return f"{self.name}" class Listing(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=15) description = models.CharField(max_length=100) starting_bid = models.IntegerField() image = models.ImageField(upload_to='images', null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, related_name="category_name") def __str__(self): return f"{self.id}: {self.title}: {self.description}: {self.starting_bid}: {self.image}: {self.category}" forms.py class ListingForm(forms.ModelForm): class Meta: model = Listing fields = ["title", "description", "starting_bid", "image", "category"] views.py def create_listing_view(request): if request.method == "POST": form = ListingForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('listings')) else: form = ListingForm() return render(request, 'auctions/create.html', {'form': form}) create.html {% block body %} <h1>create</h1> <form action="{% url 'create' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <br><br> <button type="submit" value="Submit">Create</button> </form> {% endblock %} this image is present condition I tried to do this myself, but I couldn't do as I … -
Overriding LoginView has no effect in the registration template
I tried to add some classes to my projects login template via overriding the LoginView as described here, but I seem to miss something obvious: views.py: class CustomLoginView(LoginView): # template_name = "registration/login.html" # standard form = UserLoginForm forms.py: class UserLoginForm(AuthenticationForm): username = forms.CharField(label = "", widget = forms.TextInput(attrs = {"class": "test", "placeholder": "username or email",})) password = forms.CharField(label = "", widget = forms.PasswordInput(attrs = {"placeholder": "",})) project.urls.py: from myapp.views import CustomLoginView urlpatterns = [ path("home/", RedirectView.as_view(url = "/")), path("admin/", admin.site.urls), path("", include("myapp.urls")), # path("", include("django.contrib.auth.urls")), path("login/", CustomLoginView.as_view(), name = "login"), ] login.html: <form action="" method="post" novalidate> {% csrf_token %} {{ form }} <button type="submit" value="login">login</button> </form> But when I open the login/ url I can't see the placeholder or the class I added, which makes me think, that my customized form is not being used at all - I just don't understand why. I tried excluding path("", include("django.contrib.auth.urls")) in the urls.py but that had no effect. Login works fine by the way. -
How Django runs tests parallelly?
I'm curious how django runs test parallelly with python manage.py test --parallel. Would someone please explain the what happens under the hood and and the the life cycle of test with an example. -
Django translation - PO file is missing the msgstr, it is appearing as an empty in PO file
Here, we are trying to translate the text, however, the PO file is appearing msgstr as "" #: frontend/languages/management/commands/translate.txt:302 msgid "Available Actions" msgstr "" Is there any solution to get the translated msgstr? -
Tips for making Django project responsive with Bootstrap and Sass?
I have 2 question about incorporating bootstrap, sass and django together. (1) I just completed a django course and the project we built along the line is not responsive enough. How can I incorporate bootstrap and sass into the project, and i prefer npm installation with bootstrap and sass. I don't want to use CDN in my projects (2) As an upcoming Backend developer with django, how should I start my web projects with: Pip virtualenv Pip django Npm Bootstrap 5 Npm Sass etc Pls i need details explanation I don't mind a YouTube video link or an article. Thanks Bootstrap Sass Django -
Why does clicking on a brand checkbox in Django and Ajax result in displaying another HTML page?
I am trying to filter products by brand name through checkboxes using django, ajax jquery, but while clicking on the checkbox I am having another products html page within the running html page including all the products. But while printing in console, i can see that unique brand name is being selected while checking a checkbox field. Views.py `def list_products(request): ordering = request.GET.get('ordering', "") search = request.GET.get('search', "") brands = set(Product.objects.values_list('brand', flat=True)) colors = Product.objects.values_list('color', flat=True).distinct() selected_brands = request.GET.getlist('brand') selected_colors = request.GET.getlist('color') filtered_products = Product.objects.all() if selected_brands: filtered_products = filtered_products.filter(brand__in=selected_brands) if search: filtered_products = filtered_products.filter(Q(title__icontains=search) | Q(brand__icontains=search)) if ordering: filtered_products = filtered_products.order_by(ordering) context = { 'brands': brands, 'colors': colors, 'selected_brands': selected_brands, 'selected_colors': selected_colors, 'products': filtered_products, } return render(request, "products/listproducts.html", context)``` ` HTML Code block ` All Brands {% for brand in brands %} <input class="custom-control-input brand-checkbox" type="checkbox" id="brand-{{ brand }}" name="brand" value="{{ brand }}" {% if brand in selected_brands %}checked{% endif %}> {{ brand }} {% endfor %} ` JavaScript Code block: `$(document).ready(function() { console.log("Document ready!"); // Handle checkbox change event $(document).on('change', '.brand-checkbox', function() { // Get the selected checkbox values var selectedBrands = $('input[name="brand"]:checked').map(function() { return this.value; }).get(); // AJAX request to update filtered products $.ajax({ type: "GET", url: …