Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Model indexing on Choice field in django
i have a model which has a status field of choice field which are pending,approved,cancel,rejected. And i index the field status in my model and the makemigrations but the index only works for other values but not approved value. if i filter by other status like, pending,cancel it will shows that it get it from the index but if i filter by approved it won't work and it will load slowly. Though the dataset of the model is much which is around 7million. I get the details from a django debug tools this will show if i filter by other values if i filter by other values if i filter by approved value this is my view which i use to test the filter def testing(request): context['response'] = Task_Submitted.objects.filter(status='approved') return render(request, 'testing.html', context) is there any way to fixed this so approved too will be in index so if i filter by approved value too it will load faster -
How to prepare a Django web app for deployment?
I am a novice developer, I have recently started my journey with developing full web app projects with Django, and have just finished my first one. It's a simple full-stack web app written with Django, and I have come across an impasse. How can I prepare my Django Project for deployment? -In essence, the question is, how can I remove any personal local machine information from any files within my project directory, it seems that there are cases when the PATH of my local machine python files is mentioned within the venv and in other directories. Should I just remove the venv as a whole before deploying it and manually delete all local machine references? The second question is, how can I deploy my project via VPS? -Previously I have used shared hosting and it was fairly straightforward to have everything deployed, however now I am tasked with deploying it on a VPS with an Easy-Panel set up. This is less of a priority for a question, I believe I'll be able to figure it out on my own, but if you have any advice, I would be very grateful for it! I haven't attempted to resolve this as of … -
PyJWT installed but keey getting: ModuleNotFoundError: No module named 'jwt'
My Django project was working fine. Then followed the steps to implement Auth0 into my project, which I have setup on my frontend successfully. I followed all of these steps: https://auth0.com/docs/quickstart/backend/django/01-authorization Running in Python 3.9.6 ('.venv': Pipenv) ./.venv/bin/python Trying installing requirements in all environments as well I even updated requirements.txt to the most modern versions to see if it was a compatibility issue. When I run python manage.py runserver I get File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/chasesheaff/teachr-backend/teachr/urls.py", line 23, in <module> path('', include('auth0authorization.urls')), File "/Users/chasesheaff/Library/Python/3.9/lib/python/site-packages/django/urls/conf.py", line 38, in include urlconf_module = import_module(urlconf_module) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/chasesheaff/teachr-backend/auth0authorization/urls.py", line 3, in <module> from . import views File "/Users/chasesheaff/teachr-backend/auth0authorization/views.py", line 5, in <module> import jwt ModuleNotFoundError: No module named 'jwt' pip freeze … -
Gunicorn local port 8000 with Apache reverse proxy port 443
I am trying to deploy my django project on a linux ubuntu virtual machine (from linode) using an Apache2 server. I was following the tutorial by CoreySchafer on youtube, but my out put wasn't the same as him. His django project was directly hosted to port 80 of his vm. The only way I was able to make it work was by first running the django project locally using either the dev server (runserver) or gunicorn. Both were running on 127.0.0.1:8000 of the vm. Then in the apache site .conf file, I setup reverse proxy from local port 8000 to https 443. I have 2 issues now. A) The site works with runserver, but it is not a production level server. B) The site also works with gunicorn but doesn't serve static files (I did collect static). What am I doing wrong? Is it fine to reverse proxy to local? How to make gunicorn serve static. <IfModule mod_ssl.c> <VirtualHost *:443> ServerAdmin webmaster@localhost ServerName (# hiding my website name) # Proxy settings ProxyPreserveHost On ProxyPass / http://127.0.0.1:8000/ ProxyPassReverse / http://127.0.0.1:8000/ DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SSLCertificateFile /etc/letsencrypt/live/www.website.co.in/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/www.website.co.in/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> </IfModule> This is how my apache site … -
Delete div and label for that div without label id
Using Crispy forms in Django app, I have a html code like this: <div id="div_id_pripadnost" class="form-group"> <label for="id_pripadnost_0" class=""> Pripadnost </label> <div class=""> <div class="form-check"> <input type="radio" class="form-check-input" name="pripadnost" id="id_pripadnost_1" value=""> <label for="id_pripadnost_1" class="form-check-label"> --------- </label> </div> <div class="form-check"> <input type="radio" class="form-check-input" checked="checked" name="pripadnost" id="id_pripadnost_2" value="CRS"> <label for="id_pripadnost_2" class="form-check-label"> CRS </label> </div> <div class="form-check"> <input type="radio" class="form-check-input" name="pripadnost" id="id_pripadnost_3" value="SCM"> <label for="id_pripadnost_3" class="form-check-label"> SCM </label> </div> </div> </div> I would like to remove div with id="id_pripadnost_1". I have removed radio button/div "form-check", but I can't remove label '---------', since it doesn't have id. How to remove that label? I have tried: const radioBtn = document.getElementById('id_pripadnost_1'); radioBtn.style.display = 'none'; radioBtn.previousElementSibling.style.display = 'none'; document.getElementById('id_pripadnost_1').remove(); -
How can I send a batch email using postmark in Anymail for Django?
I would like am trying to use the Anymail API for postmark in my django application. This is not the same as putting a list of emails in the cc, but I am trying to send a separate email to each individual email address (the email content is the same though). Right now, I have the following to send transactional (one-time) emails. from anymail.message import AnymailMessage email = AnymailMessage( subject=subject, body=body, from_email=from_email, # from email (uses DEFAULT_FROM_EMAIL if None) to=to, # recipient list ) email.esp_extra = { 'MessageStream': message_stream, # Specify the message stream } I initially tried using a for loop to send a separate email to each email address, but that consumed too much time and the page couldn't load long enough. How can I then achieve this batch email send in django using Anymail? Thank you, and please leave a comment if you have any questions. -
Many to many post request DRF
Currently I am trying to figure how the post request needs to be structured to create an object in watchlist. My models.py contains two models that are linked together via stock. class Stock(models.Model): model_number = models.CharField(max_length=100, unique=True, default="") model = models.CharField(max_length=100) brand = models.CharField(max_length=100) msrp = models.IntegerField(default=0) class Watchlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) stock = models.ManyToManyField(Stock) This created two tables in my database one called watchlist and another called watchlist_stock. The former contains an id and a user id. The later contains id, watchlist_id, and stock_id. Here is my serializer for the relevant view class WatchlistAddSerializer(serializers.ModelSerializer): class Meta: model = Watchlist fields = ['stock'] And here is the relevant view for the post method. @api_view(['POST']) def watchlist_create(request): serializer = WatchlistAddSerializer(data=request.data) if serializer.is_valid(): serializer.save(user=request.user) return JsonResponse(serializer.data, status=status.HTTP_201_CREATED) else: return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I am using axios to post on the react frontend but I am currently at a loss for how the data needs to be structured to post. react api.post(`/api/watchlist-create/`, { // Some data goes here }) -
How to use logrotate cut uwsgi log files
My uwsgi.log path: /root/code/script/uWSGI.log My logrotate about uwsgi configuration: in /etc/logrotate.d/uwsgi /root/code/script/uWSGI.log { daily missingok rotate 7 compress delaycompress notifempty create 640 root root sharedscripts postrotate touch /root/code/script/.touchforlogrotate endscript } My uwsgi.ini [uwsgi] http = 0.0.0.0:8050 socket=/root/code/script/uwsgi.sock master=true chdir=/root/code/ wsgi-file=/root/code/data_analysis/wsgi.py home = /root/anaconda3/envs/data-analysis worker=6 threads=2 max-requests=5000 thunder-lock=true enable-threads=true pidfile=/root/code/script/uwsgi.pid touch-logreopen = /root/code/script/.touchforlogrotate when i use logrotate -d /etc/logrotate.d/uwsgi command, the following error occurs reading config file uwsgi error: uwsgi:2 lines must begin with a keyword or a filename (possibly in double quotes) error: uwsgi:3 lines must begin with a keyword or a filename (possibly in double quotes) error: uwsgi:4 lines must begin with a keyword or a filename (possibly in double quotes) error: uwsgi:5 lines must begin with a keyword or a filename (possibly in double quotes) error: uwsgi:6 lines must begin with a keyword or a filename (possibly in double quotes) error: uwsgi:7 lines must begin with a keyword or a filename (possibly in double quotes) error: uwsgi:8 lines must begin with a keyword or a filename (possibly in double quotes) error: uwsgi:9 lines must begin with a keyword or a filename (possibly in double quotes) error: uwsgi:10 lines must begin with a keyword or a filename (possibly in … -
How i save. Canvas in db. With background. Which comes from user uploaded in Django field img
I successfully save if static path How pass field image of customer to java There many trial but src for field from model i cant save both i f i add url in style background not saved your text type h window.onload = function(){ //var dataImage = localStorage.getItem('imgData'); //var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); var imageObj = new Image(); var dataURL = canvas.toDataURL("image/png"); imageObj.onload = function(){ context.globalCompositeOperation="destination-over"; context.drawImage(imageObj,250, 50,700,400);// i edit it was context.drawImage(imageObj,50, 50); context.font = "40pt Comic Sans MS"; context.fillText("draw here",20,80); context.fill(); context.globalAlpha = 0.5; }; //function getBase64Image(img) { //var dataURL = canvas.toDataURL("image/png"); //return dataURL.replace(/^data:image\/(png|jpg);base64,/, ""); //} //here source imge for back ground if you want make it dynamic from upload by user use url of media <canvas style="background: url('{{ user.profile.profile_pic.url }}')" <canvas style="background: url({% static 'images/aes.png'%})" imageObj.src = dataURL;//"data:image/png;base64," + dataImage;//'/media/imggg/gggg.png';//"{{ img }}"//'/media/imggg/gggg.png'; //cnanvas.innerHTML = `<img src="${url}" width="50%">`;//`media/${object.img.url}`//("<img src="{{ MEDIA_URL}}{{field.img.url}}">"); //<img src="{{ MEDIA_URL}}{{ City.image.url }}">"url '(${field.img.url})' ";//=("<img src='${{field.img.url}}'>"); }; ere </main> </body> <script type="text/javascript"> </script> </html> Can pass variable from Django models and view to java Ok any other help i needs Edited code how make dynamic uploaded pic background drawing on it then save -
how to upload django project on hestiacp
how to upload django project on hestiacp I installed python in terminal and uploaded the project but don't know what I can do to run on my domain I asked shat GPT but it doesn't be useful. if some one face this problem before or has knowledge please help me -
Django i18n translations work locally but not when deployed in a CI/CD pipeline
I'm trying to add translations to my django project, and for some reason it never worked. When I deploy it in ci/cd pipeline not only does it not translate, but I get csrf errors, even though I got {% csrf token %} in my template and use render in my view. But all these problems disappear when I run it locally. Here's my code: views.py from django.shortcuts import render def test_page(request): return render(request, "translatetest.html") urls.py(app level) from . import views from django.urls import path urlpatterns = [ path('test_page/', views.test_page, name='test_page'), ] urls.py(project level) from django.contrib import admin from django.urls import include, path from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path("admin/", admin.site.urls), path("i18n/", include("django.conf.urls.i18n")), ] urlpatterns += i18n_patterns ( path("", include("help_pages.urls"), name="help_pages"), #test_page is here ) settings.py LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('en', ('English')), ('fr', ('French')), ] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) I don't think it's a problem with my python bc it worked locally but I'll put it too just in case. Also, curious enough when I deploy it in the ci/cd pipeline, only one word is translated(in another view, not the test_page one), it's not … -
django instance.add() is not working on new m2m field added
Difference between Code 1 and Code 2 given below is that industry and dindustry fields are interchanged. While Code 1 works fine Code 2 doesn't update the database. Can someone please help..... Note: Table was altered and dindustry was newly created. No migration issues, I am able to add records to both industry and dindustry through django Admin Code 1: @receiver(m2m_changed, sender=Company.dindustry.through) def video_category_changed(sender, instance, action, pk_set, **kwargs): if action == "post_add": sectors = Sectors.objects.filter(id__in=pk_set) roots = set() for sector in sectors: root = sector.get_root() if not instance.industry.filter(id=root.id).exists(): instance.industry.add(root) print('data added') Code 2: @receiver(m2m_changed, sender=Company.industry.through) def video_category_changed(sender, instance, action, pk_set, **kwargs): if action == "post_add": sectors = Sectors.objects.filter(id__in=pk_set) roots = set() for sector in sectors: root = sector.get_root() if not instance.dindustry.filter(id=root.id).exists(): instance.dindustry.add(root) print('data added') My model is as below: class Company(MPTTModel): industry = models.ManyToManyField(Sectors, related_name='relatedname_industry', blank=True) dindustry = models.ManyToManyField(Sectors, related_name='relatedname_dindustry', blank=True) class Sectors(MPTTModel): sector = models.CharField(max_length=100) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') It works well on one m2m field but doesn't work on another m2m field in the same table -
html file have something wrong Registration Form not submitting in Django
My html file have some issues but I can't figure it out what the problem actually is. Can anyone Identify what really the problem is. Here is Html I'm using: signup.html {% include "user/layout.html" %} {% block content %} <h1>Sign Up</h1> <form method="POST"> {% csrf_token %} {{form}} <input class="btn login_btn" type="submit" value="Register Account"> </form> {% endblock %} **views.py ** from django.shortcuts import render, redirect from . forms import create_user # Create your views here. def sign_up(request): form = create_user() if request.method == "POST": if form.is_valid(): form.save() return redirect("test-home") context = {"form":form} return render(request, "user/signup.html", context) **urls.py ** from django.urls import path from . import views urlpatterns = [ path("create/", views.sign_up, name="sign_up"), ] I have tried some other html sign up templates from other videos. Only copying them works. I can't figure out where the real problem is. -
KeyError: 'pick-number' when accessing custom headers in Django Rest Framework view
I'm working on a Django Rest Framework API and encountered a KeyError when trying to access custom headers in my view. The error occurs when I try to access the "pick_number" header in my confirmingPick1View. The traceback is as follows: Internal Server Error: /api/wager/pick1/confirm/ Traceback (most recent call last): File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper return view_func(request, *args, **kwargs) File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/gutsthakur/Projects/Betting App/wager/views.py", line 76, in post "pick_number": request.headers["pick_number"], File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/django/http/request.py", line 448, in __getitem__ return super().__getitem__(key.replace("_", "-")) File "/home/gutsthakur/Projects/Betting App/.env/lib/python3.10/site-packages/django/utils/datastructures.py", line 308, in __getitem__ return self._store[key.lower()][1] KeyError: 'pick-number' In my view, I'm trying to access custom headers like "Draw", "pick_number", and "bet_amount" for processing a user's bet. I expected these headers to be accessed directly without any issues, but instead, I'm receiving a KeyError for "pick_number" … -
Getting page not found error on my website build in Django & React in netlify after deployment
Page Not Found Looks like you've followed a broken link or entered a URL that doesn't exist on this site. Back to our site If this is your site, and you weren't expecting a 404 for this path, please visit Netlify's "page not found" support guide for troubleshooting tips. and also did alowed host to * but still i am not able to host please help This is my github repo. this is the error i am getting i have added netlify.toml file too in my package.json directory please refer to my repo -
Django_ CreateView class showing class availability
I have a Gym Project in django, with booking_create (CreateView) to create bookings for a gym class. I am using a Model and Form, with user and class types. The HTML template has a Form for class booking. I want to make this Form unavailable when the class is full booked, showing instead a warning message. My thoughts: I should have a booking count for created bookings (e.g., booking_count), rest this value to the class capacity and save this in a variable (like, av_places= class_capacity-booking_count) and if av_places is greater than zero, show the Form for registration, otherwise show a warning message. Not sure how to add this functionality to the class view Below are the class model, view and template. models.py: class Class_Book (models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) class = models.ForeignKey(Class, on_delete=models.CASCADE,default= '') def __str__(self): return f'{self.class}' views.py class booking_create (LoginRequiredMixin,CreateView): form_class= Booking_Form template_name= ‘booking_create.html' success_url=reverse_lazy('home') template: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-success" type="submit">SAVE</button> </form> -
Django:: ImproperlyConfigured: Pooling doesn't support persistent connections
I've recently upgraded to Django 5.1 and configured the database pooling option with the following settings: DATABASES["default"]["OPTIONS"] = { "pool": {"min_size": 2, "max_size": 4, "timeout": 10} } DATABASES["default"]["CONN_MAX_AGE"] = None However, I encountered the following error: ImproperlyConfigured: Pooling doesn't support persistent connections. I understand that removing CONN_MAX_AGE = None will resolve this issue, but I would like to gain a deeper understanding of this limitation. Specifically, is the restriction on using persistent connections with pooling a constraint unique to Django's implementation, or does it extend to PostgreSQL (or other databases) in general? Additionally, what are the underlying reasons for this incompatibility? -
Guidance Needed for Building a Django Project with Custom User Management and JWT Authentication
Hi StackOverflow Community, I'm working on a Django project with specific requirements and technical constraints, and I'm looking for guidance on how to approach it. Here are the details: Business Requirements: Login Users should be able to log in, and the system should handle successful and failed logins, account lockouts, and password recovery. Logout with Session Store Implement secure logout, handle session timeouts, and ensure session persistence across browser tabs. User Management Admins should be able to create, edit, deactivate user accounts, and view user activity logs. Roles and Permissions Admins should manage roles and permissions, assign roles to users, and modify role permissions. Technical Specifications: APIs: Must follow RESTful standards. Authentication: JWT is the preferred token type. Database: MongoDB. ORM: Official Django ORM should not be used. Model Management: Prefer using Pydantic. Coding Standards: Follow PEP8 for Python. APIs Framework: Use django-rest-framework. Class-Based Design: The implementation should be class-based and object-oriented (no functional programming). Current Knowledge and Setup: I am familiar with Django and REST frameworks but need guidance on integrating MongoDB without using Django ORM, managing models with Pydantic, and implementing JWT authentication. Questions: Setup Guidance: What are the best practices for integrating Django with MongoDB using Djongo … -
User Discord Avatar Not Displaying in Django Template
Django Python OAuth Discord getting an avatar from the Discord API, please help me how to do this. On the index.html page, the user's avatar is not displaying in the <div class="auth"> block. I have tried several methods, but none worked. I can't find information on how to properly load the user's avatar. Here is the relevant code: index.html: <div class="auth"> {% if user.is_authenticated %} <div class="user-info"> <img style="z-index: 9099;" src="{{ user.avatar }}" alt="User Avatar"> <p>{{ user.avatar }}</p> <p>{{ user.username }}</p> <a href="{% url 'account_logout' %}" class="logout-button">Logout</a> </div> {% else %} <div class="auth-buttons"> <a href="{% url 'account_login' %}" class="login-button">Login</a> <a href="{% url 'account_signup' %}" class="register-button">Register</a> <a href="{% provider_login_url 'discord' method='GET' process='connect' %}" class="discord-button">Login with Discord</a> </div> {% endif %} </div> models.py: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): discord_user_id = models.CharField(max_length=50, blank=True, null=True) discord_avatar_hash = models.CharField(max_length=100, blank=True, null=True) def get_discord_avatar_url(self): if self.discord_user_id and self.discord_avatar_hash: return f"https://cdn.discordapp.com/avatars/{self.discord_user_id}/{self.discord_avatar_hash}.png" return None views.py: def index(request): return render(request, "html/index.html") urls.py: from django.contrib import admin from django.urls import path, include from meow_app import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('about/', views.about, name='about'), path('terms/', views.terms, name='terms'), path('politika/', views.politika, name='politika'), path('events/', views.events, name='events'), path('accounts/', include('allauth.urls')), path('logout/', TemplateView.as_view(template_name='logout.html'), name='logout'), path('', include('meow_app.urls')), ] Django … -
Managing Multiple OAuth Providers in Django/DRF
Let's say I have two OAuth providers, Google and GitHub with which user can create an account in my Django application. I wrote a custom user model and a custom model for storing OAuth details (provider and user ID from provider etc.). Let's say the user logs-in with GitHub first and creates an account. He logs out, signs-up again, but this time with Google. Now what happens? How can I know that the user already has an account linked with GitHub? I cannot check the email because their email can be different for different platforms. I cannot use the ID of the user from OAuth provider too. Please do not ask me to use libraries, I'm willing to learn how to implement it on my own. -
How to delete Goods in Qoo10 by API in Django
I am using Qoo10.jp api to publish the goods on Qoo10 store. It working well but when I trying to delete a good it does not work. I tried likes this in Django. params = { 'key': user.qoo10_sak, 'v': '1.0', 'returnType': 'json', 'method': 'ItemsBasic.DeleteGoods', 'ItemCode': m_product.code, } response = requests.get('https://api.qoo10.jp/GMKT.INC.Front.QAPIService/ebayjapan.qapi', params) print(response.status_code) When I print the response status_code it 200 but the response body is Can't find method Info Delete How to solve this issue. -
Custom Widget for Search Bar
I wanted to define a custom widget SearchBar, which when associated with a CharField, would automatically render a text input box for search, followed by a search button. I created a template html and put it at a custom location. I tried to create a new widget by inheriting from django.forms.widgets.Input, but when I give template_name=, it tries to locate the path in django/forms/templates only, not my custom location myapp/forms/templates. It looks like this path is baked into django.template.backends.django.DjangoTemplates. Is there a simpler way than inheriting from DjangoTemplates then adding template paths to achieve what I want? BTW, I use Bootstrap5, and so also use django-bootstrap5, so I suppose I need to write a renderer for this too. Would I be better off manually rendering the field and button in every form by hand rather than define a custom widget? -
Send notifications with pyfcm to multiple tokens
I'm using the latest version of pyfcm and I did saw a function called async_notify_multiple to send multiple tokens. But it is not working. How to send multiple notifications. Thanks -
Jinja Template Render
i have a jinga template like below: <span>Holiday Quote Includes</span> {% set rendered_bits = [] %} <div class="flex fontWeight400 tour_includes-items"> {% for bit in bits %} {% if bit == 'hotel' and 'hotel' not in rendered_bits %} <div class="flex fontWeight400 tour_includes-item"> <img src="https://Hotel.svg" alt=""> Hotel </div> {% set rendered_bits = rendered_bits + ['hotel'] %} {% elif (bit == 'drive' or bit =='transfer' or bit == 'intercity' or bit == 'multicity' or bit == 'rental') and 'transport' not in rendered_bits %} <div class="flex fontWeight400 tour_includes-item"> <img src="https://Transport.svg" alt=""> Transport </div> {% set rendered_bits = rendered_bits + ['transport'] %} {% elif (bit == 'flight') %} <div class="flex fontWeight400 tour_includes-item"> <img src="https://Airplane_VW.svg" alt=""> Flight </div> {% set rendered_bits = rendered_bits + ['transport'] %} {% elif bit == 'paid_activity' and 'sightseeing' not in rendered_bits %} <div class="flex fontWeight400 tour_includes-item"> <img src="https://Sightseeing.svg" alt=""> Sightseeing </div> {% set rendered_bits = rendered_bits + ['sightseeing'] %} {% endif %} {% endfor %} </div> </div> here i am rendering this template with: bits = {'flight', 'hotel', 'intercity', 'paid_activity', 'transfer'}} the Problem here is for bits 'intercity' and 'transfer' the corresponding div should only be rendered once. But its getting rendered twice. below is the rendered data: <div class="row text-center" … -
CORS Error with Angular 13 Frontend and Django Backend [duplicate]
I’m currently working on a project using Angular 13 for the frontend and Django for the backend. I’ve developed a login page that fetches a background image via a GET API call from the Django backend. However, I’m encountering a CORS (Cross-Origin Resource Sharing) error when making the request. Here’s a summary of the issue: Frontend: Angular 13 application Backend: Django application Feature: Login page fetching background image through a GET request Issue: I’ve attempted to resolve the CORS error by adding the Access-Control-Allow-Origin header in the backend response, but the error persists. I'm unsure whether this issue should be resolved on the frontend side or the backend side. Steps Taken: Added 'Access-Control-Allow-Origin' header in request header. installed cors extension in browser. Code and Images: I have attached relevant code snippets and images for better understanding. login.service.ts [![enter image description here][1]][1] import { Injectable } from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import { environment } from '../environments/environment'; @Injectable({ providedIn: 'root' }) export class LoginService { rootURL:any; constructor(public http:HttpClient) { this.rootURL = environment.apiUrl; } getBackGroundImage(){ let header = { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } return this.http.get(`${this.rootURL}/login/cors/img/backgrounds/login/28.jpg?1907c5373b7`,{headers: header}); } } login.component.ts import { Component, OnInit } from '@angular/core'; import {FormControl, FormGroup, …