Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get all relations for items in database model in Django
I'm trying to make an online business canvas. In this app, we have a database containing Project, User and 9 other models. All models are connected to one specific project. In the app, when user click on on of the items (which is stored previously in the database, I want to retrive all the related items to it. For example, when user click on a cost-structure, I have to bring everything which is related to that cost-structure or if user click on one value-proposition, I have to bring everything which is connected to that value-proposition. below is the database model: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass class Project(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) def __str__(self): return self.name def get_all_relationships(self): relationships = { 'value_propositions': self.value_propositions.all(), 'customer_segments': self.customer_segments.all(), 'channels': self.channel.all(), 'customer_relationships': self.customer_relationship.all(), 'revenue_streams': self.revenue_stream.all(), 'key_resources': self.key_resources.all(), 'key_activities': self.key_activity.all(), 'key_partners': self.key_partner.all(), 'cost_structures': self.cost_structure.all(), } return relationships class ValueProposition(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="value_propositions") value = models.CharField(max_length=255) description = models.CharField(max_length=1023) def __str__(self): return self.value class CustomerSegment(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="customer_segments") value_propositions = models.ManyToManyField(ValueProposition, related_name="customer_segments") customer_segment = models.CharField(max_length=255) def __str__(self): return self.customer_segment class Channel(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="channel") customer_segment = models.ManyToManyField(CustomerSegment, related_name="channel") channels = models.CharField(max_length=255) def … -
Forbidden (CSRF cookie not set.) Django and Angular
I am gettig error CSRF cookie not set here is my angular coponent.ts file sendMessage(nick:string){ const formData = new FormData(); this.nickname = nick; formData.append('nickname',this.nickname); const headers = new HttpHeaders({ 'X-CSRFToken':this.getCookies('csrftoken') }); this.http.post('http://127.0.0.1:8000/api/send/', formData, {headers:headers, withCredentials:true }).subscribe( (response:any) => { if(response.success){ this.messageStatus = 'Message sent succesfully'; } else{ this.messageStatus = 'Failed to send message'; } }, error => { this.messageStatus = 'Failed to message' console.log('erorr is ',error) console.log(this.getCookies('csrftoken')) console.log(headers) } ) } method getCookies in component.ts private getCookies(name:string):any{ const cookieValue = document.cookie.match('(^|;)\s*' + name + '\s*=\s*([^;]+)'); return cookieValue ? cookieValue.pop() : ''; } Here is views.py django def send_message_to_telegram(request): if request.method == 'POST': telegram_nickname = request.POST.get('nickname') # Replace 'YOUR_BOT_TOKEN' with your actual Telegram bot token bot_token = 'My _ token' bot_chat_id = '789829434' # Replace with your bot's chat ID message = f"Hello, @{telegram_nickname}! This is a message from our bot." # Sending message via Telegram Bot API url = f"https://api.telegram.org/bot{bot_token}/sendMessage" payload = { 'chat_id': bot_chat_id, 'text': message } response = requests.post(url, json=payload) if response.ok: return JsonResponse({'success': True, 'message': 'Message sent successfully'}) else: return JsonResponse({'success': False, 'message': 'Failed to send message'}) else: return JsonResponse({'success': False, 'message': 'Method not allowed'}, status=405) here is my settings.py CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ALLOWED_HOSTS … -
Django async - OperationalError: the connection is closed - does not recover after db restart
I have something like the following coroutine, running by an async task: from django.db import OperationalError from my_app.models import User async def update_user_name(user: User): while True: try: user.name = coolname.generate_slug() await user.asave(update_fields=["name"]) except OperationalError: logging.exception( "DB operational error occurred, Wait 2 seconds and try again." ) await asyncio.sleep(10) when the db is inaccessible I'm getting OperationalError which makes sense. But then after fixing the db I keep getting those OperationalErrors and the connection does not really recovers I wonder why? I would expect a new connection to be opened and to be able to save to db since the issue was fixed. Im using Django 5.0.4 I noticed that my CONN_MAX_AGE db setting was 5 minutes. I changed it to 0 (close connection after each request) and it didn't help. -
I cant implement AJAX in my django forum app to post a question
I have a forum app in which users can post their questions. I want to prevent page reloading each time a user post a comment for a question. I've tried implementing ajax but it didn't work. I've done this: this is forms.py: class CommentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CommentForm, self).__init__(*args, **kwargs) # add a "form-control" class to each form input # for enabling bootstrap for name in self.fields.keys(): self.fields[name].widget.attrs.update({ 'class': 'form-control', }) class Meta: model = Comment fields = ('question', 'reply_to', 'text') this is views.py: def post_comment(request): # request should be ajax and method should be POST. if request.is_ajax and request.method == "POST": # get the form data form = CommentForm(request.POST) # save the data and after fetch the object in instance if form.is_valid(): instance = form.save() # serialize in new friend object in json ser_instance = serializers.serialize('json', [instance, ]) # send to client side. return JsonResponse({"instance": ser_instance}, status=200) else: # some form errors occured. return JsonResponse({"error": form.errors}, status=400) # some error occured return JsonResponse({"error": ""}, status=400) this is urls.py: urlpatterns = [ path('comment/', post_comment, name='post-comment'), ] this is base.html: {% block content %} {% endblock content %} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> {% block javascript %} {% endblock … -
create entire project on django admin user frontend also view in django admin
I want to create a project in django that admin can add traders user login means do CRUD operation but i want to show all the front end data also in admin panel of django user also login in django with less permission set by admin is it possible ? -
Django Project Depolyment in Windows Server using Apache
I have installed python 3.12 , Installed Django and Installed Apache and tested all without pasting my project inside htdocs and that run.Now in htdocs i have kept my project two folder core and myenv. Inside core main project files C:\Apache24\htdocs\core\core\wsgi.py httpd.conf LoadFile "C:/Program Files/Python312/python312.dll" LoadModule wsgi_module "C:/Program Files/Python312/site-packages/mod_wsgi/server/mod_wsgi.cp312-win_amd64.pyd" WSGIPythonHome "C:/Program Files/Python312" WSGIScriptAlias / "C:/Apache24/htdocs/core/core/wsgi.py" WSGIPythonPath "C:/Program Files/Python312/Lib/site-packages" <Directory "C:/Apache24/htdocs/core/core/"> Require all granted Alias /static "C:/Apache24/htdocs/core/static/" <Directory "C:/Apache24/htdocs/core/static/"> Require all granted ////// Listen 3080 ServerName example.com:80 But when i start apache and run its shows error Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at admin@example.com to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. and in logs>error: mod_wsgi (pid=1648): Failed to exec Python script file 'C:/Apache24/htdocs/core/core/wsgi.py'. Traceback (most recent call last):\rFile "C:/Apache24/htdocs/core/core/wsgi.py", line 16, in \r line 16, in \r File "C:\Program Files\Python312\lib\site-packages\django\init.py", line 19, in setup\r [Thu May 02 16:40:44.634611 2024] [wsgi:error] [pid 1648:tid 1228] [client ::1:50356] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)\r ModuleNotFoundError: No module named 'core'\r mod_wsgi (pid=1648): Failed to exec Python script … -
Django hidden field obligatory field error
I'm developing a Django page where a user fills out a lottery form. This data is stored in a MySQL database. Part of the functionality of the page is that the user can retrieve the form with the lottery data already entered to add more, modify some, or rerun the lottery without needing to re-enter all the data. Now, for this purpose, I have these forms that I am using to retrieve the lottery, add participants, add lottery data, etc... class SorteoForm(forms.ModelForm): class Meta: model = Sorteo fields = ['organizer', 'celebration_date', 'budget'] class ExclusionForm(forms.Form): participants_to_exclude = forms.CharField(label='Participants to exclude', max_length=100) class SorteoRecuperadorForm(forms.Form): recuperator_lottery = forms.CharField(label='Lottery code', max_length=50, required=False) class ParticipanteExclusionForm(forms.Form): name = forms.CharField(label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Name'})) email = forms.EmailField(label='', max_length=100, widget=forms.EmailInput(attrs={'placeholder': 'Email'})) exclusions = forms.CharField(label='', max_length=100, required=False, widget=forms.TextInput(attrs={'placeholder': 'Exclusions'})) ParticipanteExclusionFormSet = formset_factory(ParticipanteExclusionForm) ParticipanteFormSet = formset_factory(ParticipanteForm) ExclusionFormSet = formset_factory(ExclusionForm) The data control for these forms, both to rerun the lottery and to retrieve the data, is done through this method: def recover_lottery(request): lottery_form = SorteoForm(request.POST or None) ParticipanteExclusionFormSet = formset_factory(ParticipanteExclusionForm, extra=0) participant_formset = ParticipanteExclusionFormSet(request.POST or None, prefix='participant') recuperator_form = SorteoRecuperadorForm(request.POST or None) lottery = None participants = None if request.method == 'POST': if recuperator_form.is_valid(): # Retrieve the lottery and participants lottery … -
Comments asigned correctly to answer objects but display in one answer objects
I'm building a question-and-answer platform to help companies understand their customers' needs. As you can see in the view_question views, I'm displaying an answer based on the question, and it is working perfectly. However, when displaying comments on the answer using this method: answers = Answer.objects.filter(post=question) answers_comment = CommentA.objects.filter(post=answers) This method return an error in the template saying: The QuerySet value for an exact lookup must be limited to one result using slicing. then i try to display it using this method: answers = Answer.objects.filter(post=question) answers_comment = CommentA.objects.filter(post__id__in=answers) It seems like the problem is solved, but it is not. The answers_comment display all comment objects to a single answer object, even though they were not assigned to that answer. {% for answer in answers %} <div class="row border-bottom"> <div class="col col-answer"> <div class="answer-icons"> <a style="text-decoration: none;" href=""> <span><i class="fas fa-arrow-up"></i></span> <span>{{ answer.up_vote }}</span> </a> <a style="text-decoration: none;" href=""> <span><i class="fas fa-arrow-down"></i></span> <span>{{ answer.down_vote }}</span> </a> </div> <div class="answer-text"> <p>{{answer.your_answer|convert_markdown|safe}}</p> </div> </div> </div> {% endfor %} <div class="comment-container m-2"> {% for answer_comment in answers_comment %} <div class="row"> <small>{{ answer_comment.comment }}</small> {% with answer_comment.user.account as account %} <a style="text-decoration: none;" class="user-avatar" href="{% url 'Public-Profile' slug=account.slug %}"> <span>{{ answer_comment.user.username }} </span> </a> <small>{{ … -
how to tokenize a filed in elk?
I want to tokenize a field(text) in all documents(60k) of index(post) what is the best approach? GET /_analyze { "analyzer" : "standard", "text" : ["this is a test"] } need tokenized text for tag cloud in my Django app -
Why can't I deploy project (passenger wsgi)
When I change the passenger_wsgi.py to import <project_name>.wsgi application = <project_name>.wsgi.application I encounter with below error: Web application could not be started by the Phusion Passenger(R) application server. Please read the Passenger log file (search for the Error ID) to find the details of the error. I change wsgi.py in project to: os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings" -
Django : Locally save an instance of a Model
Using signals, I try to track the difference between the old instance of an object and the new instance when the Model is saved. I tried this : But logically in the model_post_init_handler method, it's a reference of the object that is stored in __original_instance. So, instance.__original_instance.is_used and instance.is_used will always be the same. How could I store a "snapshot" of the object when he is initiated, so that I will be able to track what is edited ? -
Integrating Microsoft Forms Authentication in Python Django: Troubleshooting Terminal Error
To integrate the Microsoft Forms authentication flow into my Python Django project for accessing various forms URLs and storing form details and responses, I'm employing the provided MS Forms authentication code within my project's backend. Additionally, I've configured my project to run within a Docker container. The MS Forms authentication code snippet, enclosed below, outlines the process: import json import os import django.core.management.base import requests from azure.identity import DefaultAzureCredential, InteractiveBrowserCredential, AzureCliCredential # Custom Django command definition class Command(django.core.management.base.BaseCommand): def handle(self, *args, **options): # Select one of the credential objects to obtain an access token # cred = AzureCliCredential() # e.g., via `az login` cred = InteractiveBrowserCredential() # cred = DefaultAzureCredential() # Request an access token with the specified scope scope = "https://forms.office.com/.default" token = cred.get_token(scope) print("===============================") print(f"{token.expires_on = }") print("===============================") tenantId = "tenant id" groupId = "group id" formId = "form id" # Provide the access token in the request header headers = {"Authorization": f"Bearer {token.token}"} # Retrieve all Forms for a Microsoft 365 Group url = f"https://forms.office.com/formapi/api/{tenantId}/groups/{groupId}/forms" list_response = requests.get(url, headers=headers) print(f"All Forms: {list_response.json()}") # Retrieve details for a specific group form url = f"https://forms.office.com/formapi/api/{tenantId}/groups/{groupId}/forms('{formId}')" list_response = requests.get(url, headers=headers) print(f"Form Detail: {list_response.json()}") # Retrieve questions from a group form … -
How do I write tests for my django-extensions cron job?
I have a cron job in my Django app that's defined as a MinutelyJob (from django-extensions). How do I write tests for the job? The module documentation is quite sparse, and doesn't tell me how to call the job from code as opposed to the command line. I don't want to write test code that depends on undocumented interfaces. Alternatively, should I reimplement the job using a different module? I only have the one job so Celery is a bit heavyweight for my use case. -
How can I customize Django Rest Framework documentation without using decorators?
I'm currently working on a Django project and utilizing Django Rest Framework (DRF) for building APIs. I've integrated drf-pectacular for automatic API documentation generation, but I'm finding that using decorators to customize the documentation is making my codebase messy. I'm interested in exploring alternative approaches to customize my DRF documentation without relying heavily on decorators. Could someone provide guidance on how to achieve this? I'm specifically looking for methods or techniques that allow me to customize the documentation while keeping my code clean and maintainable. Any suggestions, examples, or best practices would be greatly appreciated. Thank you! -
How to Handle and Send Various File Types (Images, Videos, Audios, PDFs, Documents) in a Django Chat App Using WebSockets and Django REST Framework
I'm working on a chat application where I need to handle and store various types of files such as images, videos, audios, PDFs, and documents using Django and Django REST framework. I have a WebSocket consumer with events like connect, disconnect, and receive. In the receive event, I'm trying to handle video files. Here's a simplified version of my code: # consumers.py async def video(self, event): stream = File(BytesIO(event['file']), name=event['file_name']) data = JSONParser().parse(stream) event['file'] = data await self.send(text_data=json.dumps(event)) # serializers.py class MessageSerializer(serializers.ModelSerializer): image = Base64ImageField(required=False) file = MyBase64FileField(required=False) class Meta: model = ChannelMessages fields = '__all__' I'm facing issues with sending video files over the WebSocket. What changes do I need to make in my code to handle video files properly and send them over the WebSocket? Additionally, I'm looking for a solution that allows me to handle and send other file types like images, audios, PDFs, and documents as well. -
How to serve images from backend to frontend
I have an application with following three different docker containers:- Frontend(react) Back-end(django) Nginx for serving static files from frontend, I am trying to access nginx website in Kubernetes (minikube). all other data is being served from backend container but only image is not being sent Can someone please help. debug is true and MEDIA_URL = ‘/media/’ MEDIA_ROOT = os.path.join(BASE_DIR ,“/app/media”) I have kept the name of django app as django-service, should I change the following lines in setttings.py file to django-service as well ? ROOT_URLCONF = 'backend.urls' WSGI_APPLICATION = 'backend.wsgi.application' here is entrypoint.sh file with same name #!/bin/sh gunicorn backend.wsgi:application --bind 0.0.0.0:8000 and following is deploment resources # Django Deployment apiVersion: apps/v1 kind: Deployment metadata: name: django-app spec: replicas: 1 selector: matchLabels: app: django-app template: metadata: labels: app: django-app spec: containers: - name: django-container image: ash414/e-cart-backend:v1.0 ports: - containerPort: 8000 # Django Service apiVersion: v1 kind: Service metadata: name: django-service labels: app: django-app spec: selector: app: django-app ports: - protocol: TCP port: 8000 targetPort: 8000 # Nginx Deployment apiVersion: apps/v1 kind: Deployment metadata: name: nginx-app labels: app: nginx-app spec: replicas: 1 selector: matchLabels: app: nginx-app template: metadata: labels: app: nginx-app spec: containers: - name: nginx-container # Not working images # … -
How to implement preview page with files Django?
I have my News model: class News(models.Model): subject = models.CharField(max_length=30) text = models.TextField() created = models.DateTimeField(auto_now_add=True) I also have File model to store files and NewsFile model to connect models to each other: class File(models.Model): file = models.FileField( 'файл' ) class NewsFile(models.Model): file = models.ForeignKey( File, on_delete=models.CASCADE, verbose_name='файл', related_name='news_files' ) news = models.ForeignKey( News, on_delete=models.CASCADE, verbose_name='новость', related_name='files' ) Here is my news form: class MultipleFileInput(forms.ClearableFileInput): allow_multiple_selected = True class MultipleFileField(forms.FileField): def __init__(self, *args, **kwargs): kwargs.setdefault("widget", MultipleFileInput()) super().__init__(*args, **kwargs) def clean(self, data, initial=None): single_file_clean = super().clean if isinstance(data, (list, tuple)): result = [single_file_clean(d, initial) for d in data] else: result = single_file_clean(data, initial) return result class NewsForm(forms.ModelForm): files = MultipleFileField(required=False) class Meta: model = News fields = ('subject', 'text') I want to make a page with a preview of the news and buttons to publish or edit the news. I have started implementing publish button, I can't pass files with form. My view: def form_valid(self, form): files = form.cleaned_data.get('files') if self.request.GET.get('save') == 'true': res = super().form_valid(form) for file in files: file_obj = File.objects.create(file=file) NewsFile.objects.create(news=self.object, file=file_obj) return res img_files = [] non_img_files = [] for file in files: if file.name.split('.')[-1] in settings.IMAGE_FORMATS: img_files.append(file) else: non_img_files.append(file) images = [] for file in img_files: … -
Google Authentication Not Appearing in Django Project
Body: I am trying to set up Google authentication in my Django project using django-allauth, but the Google login option is not appearing on my login page. I suspect I might be missing a configuration step or setting. I have confirmed the site ID is correct by checking the link: http://127.0.0.1:8000/admin/sites/site/3/change/ Could someone help me identify what I might be missing or doing wrong? Here are the relevant parts of my settings.py: SOCIALACCOUNT_PROVIDERS = { "google": { "app": [ { "client_id": "myid", "secret": "mysecret", }, ], "SCOPE": [ "profile", "email", ], "AUTH_PARAMS": { "access_type": "online", }, } } SITE_ID = 3 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'allauth.account.middleware.AccountMiddleware', 'livereload.middleware.LiveReloadScript', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'core.views.site_settings', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LOGIN_REDIRECT_URL = 'login' # Redirect after login LOGOUT_REDIRECT_URL = 'home' # Redirect after logout -
Speeding up Django's total record count calculation for a site with 20 million records MySQL
I've encountered a problem with my Django website. Given that my database contains more than 20 million records, the operation of counting the total number of data (count) becomes extremely slow. I am using the following queries: company_count_query = f"SELECT COUNT(DISTINCT cs.OGRN) AS total_companies {company_from_clause} WHERE {company_match_condition} {email_condition} {capital_condition} {date_condition} {company_okved_condition}" ip_count_query = f"SELECT COUNT(DISTINCT ip.OGRNIP) AS total_ips {ip_from_clause} WHERE {ip_match_condition} {imail_condition} {ip_okved_condition}" How can I optimize these queries or use other methods to speed up the calculation of the total number of records? Thank you for your help! I tried to optimize the query structure by adding indexes to the columns on which filtering is performed, hoping to improve the performance of the counting operation. I expected that this would reduce the query execution time and speed up the data processing. However, in practice, the query execution time remained high and the counting operation still takes too long. -
How do I retrieve more than 10k document in elasticsearch?
I'm completely new to ELK and trying to retrieve 40k documents. the search_after depends on the previous batch of results and wasn't useful for me. GET twitter/_search { "query": { "match": { "title": "elasticsearch" } }, "search_after": [1463538857, "654323"], "sort": [ {"date": "asc"}, {"tie_breaker_id": "asc"} ] } how to retrieve more than 10k documents? -
Django reverse ForeignKey returns None
I have Student and Mark models in different apps of one project. # project/study # models.py class Mark(models.Model): ... student = models.ForeignKey( "students.Student", on_delete=models.PROTECT, related_name="marks", related_query_name="mark", ) # project/students # models.py class Student(models.Model): ... # views.py class StudentDetailView(DetailView): queryset = Student.objects.prefetch_related("marks") template_name = "students/one_student.html" context_object_name = "student" # one_student.html ... <p>{{ student.marks }}</p> ... Output of html is "study.Mark.None" That is my problem. I tried making ManyToOneRel field on student, select_related, making custom view func, but that does not help. Reverse ForeignKey brings None. I watched related questions - can't understand answers, because they are unrelated directly to my situation. I'm expecting to get all Student's marks. What am I doing wrong? -
Django admin inlines that has multilanguage field , TabbedTranslationAdmin does not work correctly
i have a django project, i use django-modeltranslation for translation fields. it have two model with one-to-many relation and i use django admin with inline for @admin.register(News) class NewsAdmin(nested_admin.NestedModelAdmin, TabbedTranslationAdmin): inlines = (NewsImageInline,) and image inline is: class NewsImageInline(nested_admin.NestedTabularInline,TranslationTabularInline ): model = NewsImage extra = 1 but in admin, tabularinline not work and show all of fields in one row -
Nginx is active but I don't see static files
I have a django project. Settings.py: STATIC_URL = 'static/' STATIC_ROOT = 'static' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' I've made collectstatic and everything worked fine. Now static folder on my server with all the files. Nginx: enter image description here I had porblems with nginx, cause I changes name in sites_available and it started to give errors, so I reinstalled it and now everything is fine: nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset:> Active: active (running) since Wed 2024-05-01 14:47:13 UTC; 11min ago Docs: man:nginx(8) Process: 6843 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_proce> Process: 6844 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (c> Main PID: 6845 (nginx) Tasks: 2 (limit: 1026) Memory: 3.1M CPU: 60ms CGroup: /system.slice/nginx.service ├─6845 "nginx: master process /usr/sbin/nginx -g daemon on; master> └─6846 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" ""> May 01 14:47:13 23210 systemd[1]: nginx.service: Deactivated successfully. May 01 14:47:13 23210 systemd[1]: Stopped A high performance web server and a r> May 01 14:47:13 23210 systemd[1]: Starting A high performance web server and a > May 01 14:47:13 23210 systemd[1]: Started A high performance … -
403 Error when renewing Let's Encrypt Certbot using Django and Apache. I have 6 days to renew
When running the certbot renew command I first change my firewall permissions to allow connections on port 80, I put Cloudflare into Development Mode, then I run the renewal command. However this time I received a 403 Forbidden error trying to access the url example.com/.well-known/acme-challenge/funnylettersandstuff. I don't remember certbot needing this url but I only do this once a year for just one of my websites because for whatever reason I never got this configuration to auto renew. So here I am now trying to figure out what is causing this error. I have reviewed my virtual host configuration file and I cannot see any reasons this could be occuring. I also have modsecurity enabled but I doubt that's the issue since I cannot find any related errors in the modsecurity logs. Do I need to do something to Django to make this work? Certbot failed to authenticate some domains (authenticator: apache). The Certificate Authority reported these problems: Domain: example.com Type: unauthorized Detail: During secondary validation: 2a06:98c1:3120::1: Invalid response from http:// example.com/.well-known/acme-challenge/funkylettersandnumbers: 403 sudo iptables -P INPUT ACCEPT sudo iptables -P FORWARD ACCEPT sudo iptables -P OUTPUT ACCEPT sudo iptables -t nat -F sudo iptables -t mangle -F sudo iptables … -
Python Celery route task using hostname
I'm currently utilizing Celery for task management within my application, and I'm facing a challenge regarding task distribution to specific workers based on their unique hostnames. In my use case, I'm deploying multiple worker containers for a particular application. These containers are required to connect to various VPNs for specific requests or processing tasks. The challenge arises from the dynamic nature of container deployment, where each container's hostname is unique and dynamically assigned and it is stored on database with metadata information to be used by the application to select which worker should run a particular task. Given this scenario, I'm seeking a solution to send tasks directly to a specific worker based on it's hostname. This would ensure efficient task distribution, even in dynamic deployment environments where workers may connect to different VPNs dynamically and have different hostname each time. The logic to select the worker is already in place. The logic to create container/worker is already in place. The logic to requeue a task that is sorted to an invalid queue is already in place. Scenario Workers Worker01 (hostname=a333) connected to VPN 1 Worker02 (hostname=b999) connected to VPN 2 Worker03 (hostname=c777) connected to VPN 3 Worker04 (hostname=c444) connected …