Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error response from daemon: failed to create task for container
I have a django app. That also has redis, celery and flower. Everything is working on my local machine. But When I am trying to dockerize it The redis and django app is starting. But celery and flower is failing to start. It is giving me this error while starting celery: Error response from daemon: failed to create task for container: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "celery -A core worker -P eventlet --autoscale=10,1 -l INFO": executable file not found in $PATH: unknown Dockerfile # For more information, please refer to https://aka.ms/vscode-docker-python FROM python:bullseye EXPOSE 8000 RUN apt update && apt upgrade -y # && apk install cron iputils-ping sudo nano -y # Install pip requirements COPY requirements.txt . RUN python -m pip install -r requirements.txt RUN rm requirements.txt WORKDIR /app COPY ./src /app RUN mkdir "log" # Set the environment variables ENV PYTHONUNBUFFERED=1 ENV DJANGO_SETTINGS_MODULE=core.settings # Creates a non-root user with an explicit UID and adds permission to access the /app folder # For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app # RUN echo 'appuser … -
Direct assignment to the reverse side of a related set is prohibited. Use associated_startups.set() instead
I am trying to create nested relationship but it not working as expected **Models.py ** class Meetings(models.Model): spoc = models.ForeignKey(User, on_delete=models.CASCADE,limit_choices_to={'groups__name': 'SPOC'},related_name='spoc_meetings') mentors = models.ForeignKey(User,on_delete=models.CASCADE,limit_choices_to={'groups__name':'MENTORS'},related_name='mentor_meetings') startups = models.ManyToManyField(Startup_info,through='MeetingStartup') meeting_agenda = models.TextField() meeting_name = models.CharField(max_length=500) duration = models.IntegerField() meeting_link = models.URLField(max_length=500,null=True,blank=True) meeting_type = models.CharField(max_length=500,null=True,blank=True) class MeetingStartup(models.Model): meeting = models.ForeignKey(Meetings, on_delete=models.CASCADE,related_name='associated_startups') startup = models.ForeignKey(Startup_info, on_delete=models.CASCADE) starting_time = models.DateTimeField() duration = models.DurationField() Serializers.py class MeetingStartupSerializer(serializers.ModelSerializer): class Meta: model = MeetingStartup fields = ['meeting', 'starting_time', 'duration', 'startup'] read_only_fields = ['meeting'] class MeetingSerializer(serializers.ModelSerializer): startups = MeetingStartupSerializer(source='associated_startups',many=True, required=True) class Meta: model = Meetings fields = ['id', 'spoc', 'mentors', 'meeting_agenda', 'meeting_name', 'duration', 'meeting_link', 'meeting_type', 'startups'] def create(self, validated_data): startups_data = validated_data.pop('startups',[]) meeting_instance = Meetings.objects.create(**validated_data) for startup_data in startups_data: # print(startup_data.pop('startup')) startup_instance = Startup_info.objects.get(startup_id=startup_data.pop('startup')) MeetingStartup.objects.create(meeting=meeting_instance, starting_time=startup_data['starting_time'],duration=startup_data['duration'],startup=startup_instance) return meeting_instance Views.py class MeetingViewSet(viewsets.ModelViewSet): queryset = Meetings.objects.all() serializer_class = MeetingSerializer permission_classes = [AllowAny] authentication_classes =[] It is working well while doing GET request but on Post I m getting this error -
Python full stack
What are the skills required for a full stack python developer in 2023? I just need some assistance from seniors about mandatory skills required for a full stack developer in python to develop my career and learn new technologies and build new websites. -
Uploading Python Django Project to GitHub
I am new in Django. My friend and I are starting to create projects to add them to our portfolio for job hunting purposes. I have a few questions for you - the professionals. Exactly which folders should be present on GitHub when uploading Django projects? Should folders like django_env, .idea, or files like .DS_Store and .gitignore be present there? Where exactly should the requirements.txt and README.md files be located? [enter image description here](https://i.stack.imgur.com/OnhPg.png) In general, how and what exactly should be uploaded to GitHub to present a project professionally? -
Django rest framework use router with pk in URL
I use DRF on my project and have some routes like: router.register(r'user', views.UserView, basename='user') router.register(r'user/{pk}/note', views.NoteView, basename='user') So I want to have an opportinuty to do GET,POST,PUT etc. actions with a note. Some part of NoteView: class NoteView(ModelViewSet, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin): filter_backends = [DjangoFilterBackend] def get_queryset(self): return Note.objects.all() def list(self, request, *args, **kwargs): ... def create(self, request, *args, **kwargs): ... def update(self, request, *args, **kwargs): ... def destroy(self, request, *args, **kwargs): ... def get_serializer_class(self): if self.action == 'list': return NoteListSerializer return NoteSerializer But it doesn't work with this route, how should I define it? -
Proper use of prefetch_related() and select_related() in Django
I have a scenario which I believe is a good candidate to use prefetch_related() and select_related() in. As the documentation states that these should be used with care, I want to confirm that I am in fact improving performance rather than inadvertently hurting it. Here is the query: foo_items1 = Foo.objects.filter(bar=True) prefetch1 = Prefetch('baz__foo_set', queryset=foo_items1, to_attr='foo_bar1') foo_items2 = Foo.objects.filter(bar=False) prefetch2 = Prefetch('baz__foo_set', queryset=foo_items2, to_attr='foo_bar2') for item in queryset.select_related('baz').prefetch_related(prefetch1, prefetch2): print(item.baz.foo_bar1) print(item.baz.foo_bar2) Essentially, each item has a relation baz, which in turn has a reverse relation foo_set. I would like to optimally iterate over each item, and filter the foo_set on baz depending on whether bar is True or False. Am I doing this right? Or am I overengineering this? -
Issue of database connection lost getting error 2013, 'Lost connection to MySQL server during query'
We are facing the database connection error 2013, ‘Lost connection to MySQL server during query’ in the UAT server(LAMBDA). This error is coming randomly like once or twice a week, for the solution I use to push any kind of code (no matter what it can be a comment also) or I restart the database then the problem instantly resolves. But I’m looking for a permanent solution, please help me to get over of it Thank you # SSH TUNNEL try: tunnel = SSHTunnelForwarder((config('ssh_address'), 22), ssh_pkey = config('tunnel'), ssh_username = config('ssh_username'), remote_bind_address=(config('remote_address'), 3306),local_bind_address=('127.0.0.1',4280)) tunnel.start() print("SSH Started....") except Exception as e: print("==============================================================\nSSH error: \n",e,"\n==============================================================") host = '127.0.0.1' dbSchema = config("schema") user = config('user') passwd = config('password') port = 4280 # port = tunnel.local_bind_port DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': dbSchema, 'USER': user, 'PASSWORD': passwd, 'HOST': host, 'PORT': port, 'OPTIONS': { 'init_command': 'SET max_execution_time=10000000' # In milliseconds } }, 'oldDB': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'eff_eb', 'USER': user, 'PASSWORD': passwd, 'HOST': host, 'PORT': port, 'OPTIONS': { 'init_command': 'SET max_execution_time=10000000' # In milliseconds } } } -
LIKE operation in CHARACTER_VARYING[] field with django postgresql
I have an ArrayField in django model. I wants to do substring search on ArrayField(or charactervarying[]). I am not able to figure out how to do this. I am trying to write a custom lookup as: @ArrayField.register_lookup class ArrayLike(Lookup): lookup_name = "like" def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) rhs_params[0] = [f'%{rhs_params[0]}%'] params = lhs_params + rhs_params return '%s like %s::%s' % (lhs, rhs, 'character varying[]'), params Querying as objects = Model.objects.filter(ArrayField__like=value) I am expecting this behaviour Ex: obj1 < type=['django', 'postgres', 'python'] Model.objects.filter(ArrayField__like='djan') should result in [<obj1>] Can anyone help me on this. I am not able to figure this out even after a day of googling Thanks. I am trying to use icontains as a last resort -
Python / DJANGO / Venv
I want to run a django application that already exists in virtual enviremont.Someone can share me a youtube video that help ? Beacouse I just find out.how to create a django app and after run, but I have django app to test in my windows. run my app in virtual environment -
How to resolve in django AttributeError: module 'learning_logs.views' has no attribute 'new_entry'
This is my views.py: from django.shortcuts import render, redirect # Create your views here. from .models import Topic from .forms import TopicForm, EntryForm def index(request): """The home page for learning Log.""" return render(request, 'learning_logs/index.html') def topics(request): """Show all topics.""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): """Show a single topic and all its entries.""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) def new_topic(request): """Add a new topic""" if request.method != 'POST': # No data submitted; create a blank form. form = TopicForm() else: # POST data submitted; process data. form = TopicForm(data=request.POST) if form.is_valid(): form.save() return redirect('learning_logs:topics') # Display a blank or invalid form. context = {'form: form'} return render(request, 'learning_logs/new_topic.html', context) def new_entry(request, topic_id): """Add a new entry for a particular topic.""" topic = Topic.objects.get(id=topic_id) if request.method != 'POST': # No data submitted; create a blank form. form = EntryForm() else: # POST data submitted; process data. form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return redirect('learning_logs:topic', topic_id=topic_id) # Display a blank or invalic form. context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) Here is my urls.py: … -
Django Decorator that refreshes on current page of request if condition is failed
So, I am trying to write a decorator that restricts access to some pages. But instead of redirecting to a new page, which I have done and I am okay with for some instances, in this case I simply want it to show an error on the current page. I am okay with it refreshing the current path but I keep running into errors regarding paths. Here is my current working code with redirect. How do I modify this? def member_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME, message=default_message): def decorator(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): member = ProfileMember.objects.get(user=request.user) print(member.first_name) if not test_func(member): print("failed the test") messages.add_message(request, messages.ERROR, message) print(messages) if test_func(member): print("pass the test") return view_func(request, *args, **kwargs) path = request.build_absolute_uri() resolved_login_url = resolve_url(login_url) login_scheme, login_netloc = urlparse(resolved_login_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() return redirect_to_login( path, resolved_login_url, redirect_field_name) return _wrapped_view return decorator def user_preapproved(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME, home_url='/', message=default_message): """ Decorator for views that checks that the user is an approved member, displaying a message if provided. """ actual_decorator = member_passes_test( lambda m: m.preapproved, login_url=home_url, redirect_field_name=redirect_field_name, message=message ) if view_func: return actual_decorator(view_func) return actual_decorator My attempt at simplify it works … -
How to manage dependencies in a shared git subtree?
Lets say I have four git repos named A,B,C, & D A,B, & C (customer repos): Each repo contains a Django project for customers 1, 2, & 3 respectively Each customer exists in an air gapped environment From a user perspective, each of the Django projects are, more or less, functionally the same The repos have similar dependencies, although, they may vary in their versions (Django 2.x vs Django 4.x, PostgreSQL 13 vs 14, PostgreSQL vs SQLite, python package versions, etc.) D (common repo): This repo contains the code (Django apps & utilities) that is common across the customer repos This repo has been added as a git subtree to each of the customer repos The problem occurs when their is a dependency clash between the code in the customer repos and the common repo. For instance, if there was a line of code in the common repo that relies on Django 4.x and repo A depends on Django 2.x, then there will be errors. This same type of problem may occur with other dependencies. I've thought of two "solutions": Converge towards a single set of dependencies for all repos. In order to get this to work, however, each customer … -
How to solve the problem django.db.utils.OperationalError: no such column
enter image description here I just wanna add other attribute to model class BookCardsModel(models.Model): class Meta: verbose_name = 'Card Books' verbose_name_plural = 'Card Books' book_cover = models.ImageField() book_name = models.CharField(max_length=100) book_subtitle = models.CharField(max_length=100) book_description = models.TextField(max_length=300) full_description = models.TextField(max_length=700) book_quantity = models.IntegerField(default=0) book_color = models.CharField(max_length=100, blank=True) book_size = models.CharField(max_length=100, blank=True) digital = models.BooleanField(default=False,null=True,blank=False) -
My dropdown menu that I created with django-mptt and bootstrap 5.3 is not showed up on my template , how can I fix it?
My dropdown menu that I created with django-mptt and bootstrap 5.3 is not showed up on my template , how can I fix it??? I tried a lot to fix this but I can't, can anyone help please ? This is my template code : div class="dropdown"> <ul class="dropdown-menu"> {% recursetree categories %} <button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"> {{ node.name }} </button> <li {% if not node.is_leaf_node %}class="dropdown-submenu"{% endif %}> <a class="dropdown-item {% if not node.is_leaf_node %}dropdown-toggle{% endif %}" href="{% if node.is_leaf_node %}{{ node.get_absolute_url }}{% endif %}" {% if not node.is_leaf_node %}role="button" data-bs-toggle="dropdown" aria-expanded="false"{% endif %}> {{ node.name }} {% if not node.is_leaf_node %}<span class="dropdown-caret"></span>{% endif %} </a> {% if not node.is_leaf_node %} <ul class="dropdown-menu"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> And this is my views.py class HomePage(View): def get(self, request, ): postss = Post.objects.all() categories = Category.objects.all() form = CategoryForm() return render(request, 'home/index.html', {'postss': postss, 'categories': categories, 'form': form}) And this is a js code for this dropdown document.addEventListener('DOMContentLoaded', function() { var dropdownSubmenus = [].slice.call(document.querySelectorAll('.dropdown-submenu')); dropdownSubmenus.forEach(function(submenu) { submenu.addEventListener('mouseenter', function() { this.querySelector('.dropdown-menu').classList.add('show'); }); submenu.addEventListener('mouseleave', function() { this.querySelector('.dropdown-menu').classList.remove('show'); }); }); }); It's just not work idk why It's showing up the dropdown codes … -
Cannot make a connection from django in docker container to other services in docker compose
I am trying to send a post request from my Django server in a docker container to another service in a container initiated by docker-compose which are both in the same network. The API I am trying to connect and the Django API are working fine in the development environment locally(not in Docker). The API service that I am trying to connect from the Django server is working fine in the docker container too when I try to access it separately through url. But when I try to call that API through my Django server I am getting this error. aipbpk_server_container | http://localhost/rapi/predkmaxcsv aipbpk_server_container | Internal Server Error: /v1/api/aipbpk/predKmaxRserver aipbpk_server_container | Traceback (most recent call last): aipbpk_server_container | File "/usr/local/lib/python3.9/site-packages/urllib3/connection.py", line 174, in _new_conn aipbpk_server_container | conn = connection.create_connection( aipbpk-nginx-1 | 172.28.0.1 - - [21/Aug/2023:21:19:28 +0000] "POST /api/v1/api/aipbpk/predKmaxRserver HTTP/1.1" 500 193790 "-" "PostmanRuntime/7.32.3" "-" aipbpk_server_container | File "/usr/local/lib/python3.9/site-packages/urllib3/util/connection.py", line 95, in create_connection aipbpk_server_container | raise err aipbpk_server_container | File "/usr/local/lib/python3.9/site-packages/urllib3/util/connection.py", line 85, in create_connection aipbpk_server_container | sock.connect(sa) aipbpk_server_container | ConnectionRefusedError: [Errno 111] Connection refused aipbpk_server_container | aipbpk_server_container | During handling of the above exception, another exception occurred: aipbpk_server_container | aipbpk_server_container | Traceback (most recent call last): aipbpk_server_container | File "/usr/local/lib/python3.9/site-packages/urllib3/connectionpool.py", … -
Display Derived Value in Django Form
Suppose I have a model: class MyModel(models): A = models.DecimalField() B = models.DecimalField() And a form in which I want to display A, B and the sum C=A+B: class MyForm(): C = forms.DecimalField() class Meta: model = MyModel fields = ['A', 'B'] How do I do this? I tried to do this using an init method but doesn't quite work. -
OpenCV opens camera at the first load, but if I refresh the page, it doesn't bring camera (can't open camera by index)
I have this Django project for Video-Streaming. So everything works perfectly fine on my system (MacOS). But here's what happens in Ubuntu 20.04: Works fine for the first loading If I refresh the page or go to other pages and come back again, the camera is not being opened by my app. This is the error: [ WARN:0] global /tmp/pip-req-build-ms668fyv/opencv/modules/videoio/src/cap_v4l.cpp (893) open VIDEOIO(V4L2:/dev/video0): can't open camera by index This is Views.py import cv2 from django.http import HttpResponse, StreamingHttpResponse from django.shortcuts import render from django.views import View import threading class VideoStream(View): def __init__(self): cv2.destroyallwindows() self.camera = cv2.VideoCapture(0, cv2.CAP_V4L2) def __del__(self): self.camera.release() def get_frame(self): ret, frame = self.camera.read() if ret: _, jpeg = cv2.imencode(".jpg", frame) return jpeg.tobytes() else: # print('frame',frame) return None def generate(self): while True: frame = self.get_frame() if frame is not None: yield ( b"--frame\r\n" b"Content-Type: image/jpeg\r\n\r\n" + frame + b"\r\n\r\n" ) def get(self, request, *args, **kwargs): return StreamingHttpResponse( self.generate(), content_type="multipart/x-mixed-replace; boundary=frame" ) class StreamView(View): template_name = "stream.html" def get(self, request, *args, **kwargs): return render(request, self.template_name) This is video-stream.html <!DOCTYPE html> <html> <head> <title>Video</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <h1>Real-Time Video Stream</h1> <p>This is Paragraph</p> <img id="video-frame" src="" alt="Video Stream" /> <script> function updateFrame() { console.log("in update frame"); $('#video-frame').attr('src', '{% url … -
How to modify back button functionality in chrome in a website?
I have created a quiz website. So after submitting a quiz, it redirects me to the results page. But if i click back button it goes back to the last question. But I want it to take me back to the home page where all the list of available quizzes is seen. I am not getting any idea how to do it, so I could use some help. My project is a django project so I wanna know how can it be done using djnago? Anyways I am open to all answers -
KeyError in constance package used in Django
I am getting the following error when I try to run my debugger configuration on a Django project through a Docker container using Docker Compose. I can't find AUTO_END_TIMEDELTA_MINS anywhere on the web. Any idea what that might be? Traceback (most recent call last): 2023-08-21T18:03:17.443221106Z File "/usr/local/lib/python3.8/site-packages/constance/base.py", line 14, in __getattr__ 2023-08-21T18:03:17.443224978Z if not len(settings.CONFIG[key]) in (2, 3): 2023-08-21T18:03:17.443227740Z KeyError: 'AUTO_END_TIMEDELTA_MINS' -
Need to know if it is possible to develop log users in django?
I am developping a web application with django and want that admin should see all operations done by differents users in a log. Is it possible to do that please? i am trying to know the possibility if someone did that with django -
"ValueError: not enough image data" from Pillow when saving to a Django ImageField
I have a Django model like: class Website(models.Model): favicon = models.ImageField( null=False, blank=True, default="", width_field="favicon_width", height_field="favicon_height", ) favicon_width = models.PositiveSmallIntegerField(null=True, blank=True) favicon_height = models.PositiveSmallIntegerField(null=True, blank=True) I'm fetching a .ico file and saving it to the favicon field as a .png like this: import io import requests from django.core import files from .models import Website website = Website.objects.get(pk=1) response = requests.get("https://www.blogger.com/favicon.ico", stream=True) image_data = io.BytesIO(response.content) website.favicon.save("favicon.png", files.File(image_data)) Behind the scenes, Pillow successfully converts the ICO file to a PNG, and saves the file. But I then get an error. The traceback includes: # More here File /usr/local/lib/python3.10/site-packages/django/db/models/fields/files.py:491, in ImageField.update_dimension_fields(self, instance, force, *args, **kwargs) 489 # file should be an instance of ImageFieldFile or should be None. 490 if file: --> 491 width = file.width 492 height = file.height 493 else: 494 # No file, so clear dimensions fields. # Lots more here File /usr/local/lib/python3.10/site-packages/PIL/Image.py:804, in Image.frombytes(self, data, decoder_name, *args) 802 if s[0] >= 0: 803 msg = "not enough image data" --> 804 raise ValueError(msg) 805 if s[1] != 0: 806 msg = "cannot decode image data" ValueError: not enough image data So it can save the image but, I'm guessing, not get the width/height from the image to save. BUT, … -
Django "unable to open database file" after cleaning some stuff from my laptop
recently I've been cleaning up my laptop and I believe I have deletedsmth related to my database file in django, whenever I try to login/signup there is an error: OperationalError at /admin/login/ unable to open database file Request Method: POST Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 4.2.2 Exception Type: OperationalError Exception Value: unable to open database file Exception Location: C:\Users\Mechta\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\backends\sqlite3\base.py, line 328, in execute Raised during: django.contrib.admin.sites.login Python Executable: C:\Users\Mechta\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.4 Python Path: ['C:\Users\Mechta\Documents\rasengan', 'C:\Users\Mechta\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\Mechta\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\Mechta\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\Mechta\AppData\Local\Programs\Python\Python311', 'C:\Users\Mechta\AppData\Local\Programs\Python\Python311\Lib\site-packages'] I can provide info if u need more details I've read some other posts in here and watched some yt videos but nothing rly helped so I'm stuck -
Download file using DRF
I had written code to download file file_path = file_url FilePointer = open(file_path,"r") response = HttpResponse(FilePointer,content_type='application/msword') response['Content-Disposition'] = 'attachment; filename=NameOfFile' return response. How can I test this code using postman if actually a file gets download when i use this api While React JS code on the frontend is suitable for verifying file downloads, I'm interested in confirming the same using Postman. -
how to save data as null in database in Django forms
here is my problem "Do something in the input form so that the subject value does not need to be filled when sending and it is saved in the database without any input." it is an important task for me I'll be so grateful if you help me models.py from django.db import models # Create your models here. class Contact(models.Model): name = models.CharField(max_length=255) email = models.EmailField() subject = models.CharField(max_length=255) message = models.TextField() created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) class Meta: ordering = ['created_date'] def __srt__(self): return self.name forms.py from django import forms from website.models import Contact class ContactForm(forms.ModelForm): subject = forms.CharField(required=False) class Meta: model = Contact fields = "__all__" views.py from django.shortcuts import render from django.http import HttpResponse from website.forms import ContactForm from django.contrib import messages def index_view(request): return render(request, "website/index.html") def about_view(request): return render(request, "website/about.html") def contact_view(request): if request.method == "POST": form = ContactForm(request.POST) request.POST._mutable = True request.POST['name'] = 'Anonymous' if form.is_valid(): form.save() messages.add_message(request, messages.SUCCESS, "your ticket submited") else: messages.add_message(request, messages.ERROR, "your ticket did not submited") form = ContactForm() return render(request, "website/contact.html", {"form:form}) i try somethings in model but it didn't work -
Why am I getting a Bad Gateway Error sending bulk emails with Django
I have a need to send bulk emails, as much as 60 at a time, using an action in the Admin module. I do this by selecting certain cases and then running an admin action. Sometimes when I do this, not all 60 emails send. Sometimes they seem to go in batches of 20/30 and there could be a delay of a few hours between batches. This time I got an incomplete batch being sent and a 'Bad Gateway' error, with 8 emails not being sent. Those that what sent were sent twice. I can't see anything wrong with my code that would cause this. Any ideas would be greatly appreciated. I have the following Admin Action in my admin.py file: emailset=queryset.all().order_by('customer') for q in emailset: customer=q.customer email_to = q.customer.email html_content = render_to_string("accounts/email_template_staff_registration.html", {'q':q}) text_content = strip_tags(html_content) email = EmailMultiAlternatives( #subject "Staff Registration Email", #content text_content, #from settings.EMAIL_HOST_USER, # rec list [email_to], ['INSERT EMAIL ADDRESS FOR CC'] ) email.attach_alternative(html_content, "text/html") email.send() updated=len(queryset) self.message_user(request, ngettext( '%d Staff Registration Email was successfully sent.', '%d Staff Registration Emails were successfully sent.', updated, ) % updated, messages.SUCCESS) send_staff_reg_email.short_description="Send staff registration email" ```