Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having trouble configuring ssl for django apache2
I have two errors: 'AH00112: Warning: DocumentRoot [/etc/apache2/var/www/html] does not exist' while i runed this cmd: >>>> grep -r "DocumentRoot" /etc/apache2/ >>> /etc/apache2/sites-available/000-default.conf: DocumentRoot > var/www/html > >>> /etc/apache2/sites-available/amicom_com_vn.conf: DocumentRoot > /var/www/html > >>> /etc/apache2/sites-available/default-ssl.conf: DocumentRoot > /var/www/html when i run 'https://example.com' i see 'Apache2 Default Page' how can i fix this error, this is my config ssl <VirtualHost *:443> ServerAdmin webmaster@localhost ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/html SSLEngine on SSLCertificateFile /etc/ssl/certs/ca-certificates.crt SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key </VirtualHost> -
python exclude non accessible image with requests
i've written a really simple function with requests, wich with a giver url checks if it gets a response and if this response is an image. It actually works, but is crazy slow at times. i'm too inexperienced to understand why is that. How can i improve it or achieve the same thing in a better and faster way? def is_image_url(url): try: response = requests.get(url) status = response.status_code print(status) if response.status_code == 200: content_type = response.headers.get('content-type') print(content_type) if content_type.startswith('image'): return True return False except Exception as e: print(e) return False i'm using that function to exclude images who are not acessible, like images from instagram, facebook etc. i thoughtit could work fine because i actually need to check only 10 images that i get from google custom search api. for now i've excluded the function from the application, and tried do a similar thing with checking the image height or width to assure that it existed and was accessible without much success. -
Python Django dj-rest-auth AttributeError
I was trying the demo project ( https://dj-rest-auth.readthedocs.io/en/latest/demo.html ) and when I tried to login I got the error: Django 4.2.5 django-allauth 0.61.1 dj-rest-auth 5.0.2 PyJWT 2.8.0 Internal Server Error: /api/v1/social/google/login/finish/ Traceback (most recent call last): File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/django/views/decorators/debug.py", line 92, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/dj_rest_auth/views.py", line 48, in dispatch return super().dispatch(*args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/dj_rest_auth/views.py", line 125, in post self.serializer.is_valid(raise_exception=True) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/serializers.py", line 227, in is_valid self._validated_data = self.run_validation(self.initial_data) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/rest_framework/serializers.py", line 429, in run_validation value = self.validate(value) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/dj_rest_auth/registration/serializers.py", line 160, in validate login = self.get_social_login(adapter, app, social_token, token) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/dj_rest_auth/registration/serializers.py", line 62, in get_social_login social_login = adapter.complete_login(request, app, token, response=response) File "/Users/junu/Documents/venv/ratatouille_web/lib/python3.9/site-packages/allauth/socialaccount/providers/google/views.py", line 82, in complete_login id_token = response.get("id_token") AttributeError: 'str' object has … -
I am running elastic search on 0.5-1 vCPU (1 shared core) GCP but the server is not able to handle how to fix this?
I am running Elasticsearch on 0.5-1 vCPU (1 shared core) with 1.7 GB of memory (GCP). When I start the elastic search service the server is crashed. How do we fix this issue? I am running Django with Postgres and Elasticsearch. -
Django NameError: name 'include' is not defined in urls.py
I'm encountering a NameError in my Django project's urls.py file. When I try to use the include () function to include URLs from another app, I get the following error: NameError: name 'include' is not defined Here's the relevant portion of my urls.py file: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('hello/', include('hello.urls')) ] I've already imported include from django.urls, so I'm not sure why this error is occurring. Any insights on what might be causing this issue and how to resolve it would be greatly appreciated. Thank you! I attempted to include URLs from another Django app in my project's urls.py file using the include() function. I expected the include() function to work as intended and include the URLs from the specified app. However, when I tried to use the include() function, I encountered a NameError stating that 'include' is not defined, even though I had imported it from django.urls. -
WebSocket connection to 'ws://127.0.0.1:8000/ws/work/' failed:
I can't access the WebSocket while I follow this project : https://www.youtube.com/watch?v=SF1k_Twr9cg&t=2498s&ab_channel=CodeWithStein From 47:23 consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept async def disconnect(self): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) routing.py from django.urls import path from . import consumers websocket_urlpatterns = [ path('ws/<str:room_name>/', consumers.ChatConsumer.as_asgi()), ] asgi.py import os from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import room.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangochat.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( room.routing.websocket_urlpatterns ) ) }) room.html {% block scripts %} {{ room.slug|json_script:"json-roomname" }} <script> const roomName = JSON.parse(document.getElementById("json-roomname").textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/' + roomName + '/' ); chatSocket.onmessage = function (e) { console.log("onmessage"); } chatSocket.onclose = function (e) { console.log("onclose"); } </script> {% endblock %} -
type object ...... has no attribute 'replace'
I'm using Django 4.2 application this is my model: from django.db import models from django.utils.translation import gettext_lazy as _ class Category(models.Model): parent = models.ForeignKey('self', verbose_name=_('parent'), blank=True, null = True, on_delete=models.CASCADE) title = models.CharField(_('title'), max_length = 50) description = models.TextField(_('description'), blank=True) avatar = models.ImageField(_('avatar'), upload_to='categories/') enable = models.BooleanField(_('enable'), default = True) created_time = models.DateTimeField(_('created time'), auto_now_add = True) updated_time = models.DateTimeField(_('updated time'), auto_now=True) class Meta: db_table = 'categories' verbose_name = _('Category') verbose_name_plural = _('categories') when I run the server I get this error: type object 'Category' has no attribute 'replace' I think that it's because of the translation cause when I checked where 'replace' was I found this: def gettext(message): """ Translate the 'message' string. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object. """ global _default eol_message = message.replace("\r\n", "\n").replace("\r", "\n") if eol_message: _default = _default or translation(settings.LANGUAGE_CODE) translation_object = getattr(_active, "value", _default) result = translation_object.gettext(eol_message) else: # Return an empty value of the corresponding type if an empty message # is given, instead of metadata, which is the default gettext behavior. result = type(message)("") if isinstance(message, SafeData): return mark_safe(result) return … -
Django models field not getting generated in database
I am creating a basic Django project. I am using the default db sqlite3. I have created an app product inside my main folder. So, my folder structure is like this: -project -djangoproject -products -models.py -manage.py I am adding my new product model in models.py but when I am running python3 manage.py makemigrations I am checking my migration file. The model is getting created and there is an id field also in it but no other field of my product is coming in my migrations file. I also ran the command python3 manage.py migrations and checked my database. Only id field is present in the product table. I am not able to understand the cause of this problem. Here is the look at my migration file and models.py file: from django.db import models class Product(models.Model): name: models.CharField(max_length=200) price: models.FloatField() stock: models.IntegerField() image_url: models.CharField(max_length=2083) # Generated by Django 5.0.3 on 2024-03-21 04:46 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('products', '0004_delete_offer_delete_product'), ] operations = [ migrations.CreateModel( name='Product', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), ] Django version: 5 If anyone knows the reason then please comment or post your answer. It will be really … -
Configuring Alembic in Django Rest Framework with SQLAlchemy
I have a DRF project where I am using SQLAlchemy along with Django's built-in ORM. For configuring Alembic into my project I did this. Installed Alembic with pip install alembic Then I've run this command on my root project directory. alembic init alembic This command generated a folder called alembic and a file named alembic.ini in my root project directory. Inside that folder there are some files like (env.py, README, script.py.mako) and a folder named versions. Now, inside the alembic.ini file, I've added this line, sqlalchemy.url = sqlite3://db.sqlite3 This is how I configured. This is my models.py: from sqlalchemy import create_engine, Column, String, Integer, Float, ForeignKey from sqlalchemy.orm import declarative_base, sessionmaker, relationship from django.contrib.auth import models engine = create_engine('sqlite:///db.sqlite3') Base = declarative_base() class PlaceInfoModel(Base): __tablename__ = 'place_info' id = Column(Integer, primary_key=True, autoincrement=True) owner_id = Column(Integer,nullable=False) name = Column(String(60)) address = Column(String(300)) rating = Column(Float) type = Column(String(20)) image = Column(String) Base.metadata.create_all(engine) In my alembic/env.py I added these lines: from review.models import Base, PlaceInfoModel target_metadata = Base.metadata But, whenever I run this alembic revision --autogenerate -m "Created SQLAlchemy Model" I am getting this error. File "D:\SQLAlchemy Practice\env\Lib\site-packages\django\conf\__init__.py", line 69, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not … -
Stripe doesn't work after deploying on Heroku by Django
*English is not my mother language,so if my English is not correct,please ignore. At Local, Stripe has worked well on Django. But after deploying Heroku, Stripe(subscription Service) doesn't work. When I click "Pay",everytime showed " Internet Error 500".I checked Heroku logs,but connect and service looks like okay. I've tried deployed again and again, but everytime the results are same. Showing "Internet Error 500". This is logs by Heroku logs --tail 2024-03-19T08:03:27.576123+00:00 heroku[router]: at=info method=POST path="/checkout/" host=nagoyameshi-marina-32890ff7fdd2.herokuapp.com request_id=40d9d9e5-8ebf-436f-9254-2e862dcada7e fwd="126.15.11.7" dyno=web.1 connect=2ms service=19ms status=500 bytes=459 protocol=https 2024-03-19T08:03:27.576163+00:00 app[web.1]: 10.1.20.255 - - [19/Mar/2024:17:03:27 +0900] "POST /checkout/ HTTP/1.1" 500 145 "https://nagoyameshi-marina-32890ff7fdd2.herokuapp.com/terms_of_service/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36" These are my settings.py and CheckoutView from views.py I deployed on Heroku. if "STRIPE_PUBLISHABLE_KEY" in os.environ and "STRIPE_API_KEY" in os.environ and "STRIPE_PRICE_ID" in os.environ: STRIPE_PUBLISHABLE_KEY = os.environ["STRIPE_PUBLISHABLE_KEY"] STRIPE_API_KEY = os.environ["STRIPE_API_KEY"] STRIPE_PRICE_ID = os.environ["STRIPE_PRICE_ID"] - CheckoutView stripe.api_key = settings.STRIPE_API_KEY class CheckoutView(LoginRequiredMixin,View): def post(self, request, *args, **kwargs): checkout_session =stripe.checkout.Session.create( line_items=[ { 'price':settings.STRIPE_PRICE_ID, 'quantity':1, }, ], payment_method_types=['card'], mode='subscription', success_url=request.build_absolute_uri(reverse_lazy("nagoyameshi:success")) + '?session_id={CHECKOUT_SESSION_ID}', cancel_url=request.build_absolute_uri(reverse_lazy("nagoyameshi:index")), ) print( checkout_session["id"] ) return redirect(checkout_session.url) checkout = CheckoutView.as_view() DB is " Heroku Postgres". -
Django and Keystrokes dynamics as authentication
How do i capture and use keystrokes dynamics as my second factor authentication in Django web application project? I have implemented the normal username and password authentication in Django and fails to know how i can use keystrokes to add it for authentication. -
Django ConnectionRefusedError [Errno 111] Connection refused facing issue how to solve it
I'm facing issue when send mail on django [Errno 111] Connection refused my setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Replace with your preferred backend EMAIL_HOSTS = 'smtp.gmail.com' # Replace with your email host EMAIL_PORT = 587 # Replace with your email port EMAIL_USE_TLS = config('EMAIL_USE_TLS', cast=bool) # Set to False if your email server doesn't use TLS EMAIL_HOST_USER = config('EMAIL_HOST_USER') # Replace with your email username EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD') # Replace with your email password view.py current_url = get_current_site(request) mail_subject = "Please activate your account." message = render_to_string('base/pass/account_verify.html',{ 'user':user, 'domain':current_url, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':default_token_generator.make_token(user), }) to_email = email send_mail = EmailMessage(mail_subject, message, to=[to_email]) send_mail.send() i have check all mail setting.py but can't solve this error on local it's work but when i am production and host while it's not working and get this error -
Total counts not displaying in template:
the app im building requires asset management section which would display the total assets, total fixed, total onsite and total booked, however the blocks shows but the amounts does not. while debugging the print statement within the views prints to console and if i attempt to load the asset management html it displays but when including it into my base html the amounts does not display. My views: def asset_dashboard(request): total_assets_count = Asset.objects.count() onsite_assets_count = Asset.objects.filter(status='onsite').count() fixed_assets_count = Asset.objects.filter(status='fixed').count() booked_assets_count = Asset.objects.filter(status='booked').count() print("Total Assets Count:", total_assets_count) print("Onsite Assets Count:", onsite_assets_count) print("Fixed Assets Count:", fixed_assets_count) print("Booked Assets Count:", booked_assets_count) context = { 'total_assets_count': total_assets_count, 'onsite_assets_count': onsite_assets_count, 'fixed_assets_count': fixed_assets_count, 'booked_assets_count': booked_assets_count, } return render(request, 'asset_dashboard.html', context) My base.HTML: <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> {% load static %} <link rel="stylesheet" href="{% static './css/main.css' %}"> <style> /* CSS to style the container */ .container { height: 200px; background-image: url('static/images/VOClogo.jpg'); background-size: contain; background-repeat: no-repeat; background-position: center; opacity: 0.2; color: white; font-size: 24px; text-align: center; padding-top: 10px; } </style> </head> <body> {% include 'navbar.html' %} <form class="d-flex" method="GET" action="{% url 'asset_search' %}"> <input class="form-control … -
Can I build a dynamic Web3 site using IPFS?
This is more of a general question. I would like to connect a dynamic site to a Web3 domain (.x) I have read that only static builds are possible using the IPFS protocol and Web3 platforms (such as Pinata, Fleek etc.). Just digging into Web3 development further. Appreciate any clarity, thoughts or pointers. And when I say dynamic, I mean full backend and frontend stack capabilities using frameworks such as Django. -
Redirect URI error with Google social login in dj-rest-auth
I try to add a google login button to my website, that runs django as the server. For social authentication I want use dj-rest-auth and tried to go according to it's guides to authenticate with google auth-code flow. On the client side I use the @react-oauth/google package. The setup on my django server is this: views.py class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter callback_url = "http://127.0.0.1:8000/accounts/google/login/callback/" client_class = OAuth2Client urls.py path("auth/google/", GoogleLogin.as_view(), name="google_login"), The google credentials screen settings: Whenever I try to login with google I get an 400 error from the dj-rest-auth view, and when I debugged the code I looked at the response from google(https://oauth2.googleapis.com/token): I get the following error in the response text(also 400) { "error": "redirect_uri_mismatch", "error_description": "Bad Request" } It looks like my server send the correct redirect uri in the payload Any help or tips with this issue and social auth in general would be very appreciated, thank you. -
How to solve the image not displayed on Production using Django on Heroku
So the images are displayed on test or debug side but when I deployed into production it does not show the image , in fact it shows something else, like in the imagethe image is not fully displayed.I am using pillows and Whitenoise for the images . How can I solve this issue? I tried to make some changes on the script and settings.py -
DjangoJobStore Randomly Deletes Jobs
I have apscheduler running with a DjangoJobStore from a management command in django, but every so often some (not all) of the jobs will be deleted from the database. The scheduler still runs, still gets other jobs, but doesnt find the specific one in the code below. When i check the admin, its deleted. Restarting the command fixes it as it adds the job back for a random amount of time before deleting again. I added a listener for EVENT_JOB_REMOVED and it is never fired, and i added breakpoints in all the delete methods for DjangoJob and none of them ever hit. the function must_reply simply checks an email inbox and sends a reply back over smtp, nothing in there accesses the DjangoJob table, nor does anything in the rest of the code. must_reply is decorated with @close_old_connections removing DjangoJobStore as a job store fixes the problem, but obviously I would like to use it haha Has anyone experienced this? And what are some solutions or ideas to try for fixing this. It is truly strange. class Command(BaseCommand): help = "Runs APScheduler." def handle(self, *args, **options): executors = { 'default': ThreadPoolExecutor(max_workers=10) } job_defaults = { 'coalesce': True, 'misfire_grace_time': 10 } … -
Dockerized Django + Nginx startup & mounting issue
I want to create a enviroment for my personal project hovewer I'm strugling and can't resolve the issue. I had it working, made some reorganization in the project structure to structure it like i want (or think is best) and broke it trying to fix it :/ And to be honest i had simmilar issue in the past, I strugled with it ... i guess I did not learn anything and forgot how i fixed it (wasnt dockerized). The project is just basic default configuration to have it running as i want, so I have the comfort of the CI/CD jenkins deployement and can run and play across docker containers. I will share the relevant parts as well as the project structure. Project file structure: RaC/ ├── django/ │ ├── Dockerfile │ ├── .env │ ├── manage.py │ ├── files/ │ │ ├── media/ │ │ └── static/ │ └── rac_backend/ │ ├── __init__.py │ ├── asgi.py │ ├── requirements.txt │ ├── settings.py │ ├── urls.py │ ├── wsgi.py ├── jenkins/ ├── nginx/ ├── postgres/ ├── redis/ ├── templates/ ├── venv/ ├── manage.py └── docker-compose.yml docker-compose.yml version: '3.8' services: jenkins: build: context: ./jenkins ports: - "8080:8080" - "50000:50000" volumes: - … -
Issues with sending emails through Outlook using the Win32 library in Django
I'm using Win32 for sending emails on my website. In general, the emails are sent and reach the recipient, but the problem is that the recipient does not change. Initially, when I started this project, I used a single test email to use in different scenarios. This email was "email1@outlook.com". Later, I added another email for another user named User 2 with their own email "email2@outlook.com". The problem is that the recipient does not change. I specifically select that my recipient is "email2@outlook.com", but I always receive all emails at "email1@outlook.com". outlook = win32.Dispatch('Outlook.Application') mail = outlook.CreateItem(0) mail.SentOnBehalfOfName = 'xxxxxxxx@outlook.com' mail.To = email mail.Subject = 'NUEVA SOLICITUD DE PRUEBAS DE LABORATORIO' mail.BodyFormat = 2 html_body = f""" <html> <body style="font-family: 'Arial', sans-serif; background-color: #f4f4f4; margin: 0; padding: 0;"> <div style="max-width: 600px; margin: 20px auto; background-color: #ffffff; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);"> <h1 style="color: #333; margin-bottom: 10px;">Nueva solicitud de pruebas de laboratorio de {full_name}</h1> <p style="color: #555; margin-bottom: 20px;">El usuario {full_name} ha creado una nueva solicitud de pruebas de laboratorio para el cliente {customer} con una fecha requerida para el {require_date}. A continuación, se detallan más información y enlaces:</p> <ul style="list-style-type: none; padding: 0;"> … -
How do i prevent djagno from deleting leading zeros in a CharField?
I need to store strings like "0000", "0001" in my model fields, but fields like CharField, TextField and SlugField are deleting leading zeros and i end up with "0" and "1". How do I prevent this behaviour? I tried using all types of string containers in djagno Models and adding self.code.zfill(4) to save method of the model, but nothing helped. That's what my field looks like: `class User(django.contrib.auth.models.AbstractUser): objects = UserManager() code = django.db.models.UUIDField( "код", unique=True, null=True, blank=True, max_length=4, validators=[], ) def save(self, *args, **kwargs): self.code = str(self.code.zfill(4)) super().save(*args, **kwargs)` -
Creating groups
I want to create groups but i am unsure how, is this the correct way? whats the next step after creating this from django.core.management.base import BaseCommand from django.contrib.auth.models import Group, Permission class Command(BaseCommand): help = 'Creates initial groups for the application' def handle(self, *args, **options): # Define the list of group names and descriptions along with associated permissions groups_data = [ { 'name': 'Students', 'description': 'Group 1: Students', 'permissions': ['create_portfolio', 'view_own_portfolio', 'change_own_portfolio', 'delete_own_portfolio'] }, { 'name': 'Lecturers', 'description': 'Group 2: Lecturers', 'permissions': ['view_all_portfolios'] }, { 'name': 'Local admin', 'description': 'Group 3: Local admin', 'permissions': ['view_all_portfolios'] }, { 'name': 'Organisation admin', 'description': 'Group 4: Organisation admin', 'permissions': ['view_all_portfolios'] }, # Add more groups as needed ] # Create groups with associated permissions for data in groups_data: group, created = Group.objects.get_or_create(name=data['name']) if created: group.description = data['description'] group.save() # Add permissions to the group for perm_codename in data['permissions']: permission = Permission.objects.get(codename=perm_codename) group.permissions.add(permission) self.stdout.write(self.style.SUCCESS(f'Group "{group}" created successfully')) else: self.stdout.write(self.style.WARNING(f'Group "{group}" already exists')) -
Publish messages to MQTT using Celery-Beat scheduled tasks
I am developing a Django+Vue web application along with an MQTT server. I want to implement Celery Beat to execute scheduled tasks, which I define in the "calendarios" models where I input the tasks according to the date, interval, repetition, and others. In "eventosCalendarios," I save each task with the time and date to execute. What I aim for is that upon executing each task, I can publish to a specific topic on the MQTT server. Models.py class calendarios(models.Model): nombre=models.CharField(max_length= 100, verbose_name='Nombre', unique=True) acciones=models.ForeignKey(acciones, null=True,blank=True,on_delete=models.CASCADE,verbose_name='Acciones') fecha_inicio = models.DateField(null=True, blank=True) fecha_fin = models.DateField(null=True, blank=True) repeticion= models.CharField(max_length=1, choices=repeticionChoices, default='D') # Ej: 'diaria', 'semanal', 'mensual' intervalo = models.IntegerField(null=True, blank=True) # Número de días, semanas o meses dependiendo de la repeticion todoCultivo= models.CharField(max_length=1, choices=SioNO, default='S') hora_repeticion_1 = models.TimeField(null=True, blank=True) # Hora de la primera repetición diaria hora_repeticion_2 = models.TimeField(null=True, blank=True) # Hora de la segunda repetición diaria hora_repeticion_3 = models.TimeField(null=True, blank=True) cultivo=models.ManyToManyField(cultivo, verbose_name="Cultivos",blank=True) plantas=models.ManyToManyField(plantas, verbose_name="Plantas",blank=True) def __str__(self): return self.nombre class Meta: verbose_name = 'Calendario' verbose_name_plural = 'Calendarios' db_table = 'calendarios' ordering = ['id'] class eventosCalendarios(models.Model): title = models.CharField(max_length=100) start = models.DateTimeField() calendario = models.ForeignKey(calendarios, on_delete=models.CASCADE) allDay = models.BooleanField(default=False) def __str__(self): return self.title class Meta: verbose_name = 'Evento calendario' verbose_name_plural = 'Eventos calendarios' db_table = … -
docker-compose: how to connect two projects so they could send requests to each other
Let's say, I have two projects: spam-service and eggs-service. Here is the spam's YAML-file: version: '3' services: spam-db: image: postgres:11.4 restart: unless-stopped environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: spam volumes: - postgres_data:/var/lib/postgresql/data/ spam-service: build: context: . dockerfile: ./config/local/Dockerfile container_name: spam-service restart: unless-stopped depends_on: - spam-db environment: DEBUG: True APP_ENV: 'LOCAL_DOCKER' BROKER_HOST_NAME: redis-spam POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: spam POSTGRES_HOST: spam-db POSTGRES_PORT: 5432 ports: - '127.0.0.1:8877:8000' The Egg's service is absolutely identical, just replace 'spam' to 'eggs' and ports are also different. How can I connect these two containerized projects so the could send api requests to each other? And what precisely URL I have to use to send such requests. I tried something like this but no success: version: '3' services: ... spam-service: build: context: . dockerfile: ./config/local/Dockerfile container_name: spam-service restart: unless-stopped depends_on: - spam-db environment: ... ports: - '127.0.0.1:8877:8000' networks: &networks - local-network networks: local-network: external: true POST http://spam-service:8877/api/v1/cache/ [2024-03-20 22:04:32,730: ERROR/ForkPoolWorker-4] Error on send data to spam_cachenotok: HTTPConnectionPool(host='spam-service', port=8000): Max retries exceeded with url: /api/v1/cache/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x760d642e54c0>: Failed to establish a new connection: [Errno 111] Connection refused')), url: http://spam-service:8001/api/v1/cache/, data: {'blah': 'blah'} What am I doing wrong? -
Django Sessions not saving between different views/api's
the session data isnt saving from one view to another: in one view I have this: try: df = pd.read_excel(excel_file) request.session['dataframe'] = df.to_json() Then in another view: if 'dataframe' not in request.session: print("Session is Currently Empty") df_json = request.session.get('dataframe') # Access file from session cache if not df_json: print('not df_json') return JsonResponse({'error': 'No data available'}, status=404) The settings/Middleware should be right. and I added additional lines like .save and modify = true and still nothing. this is my first time using django, if anyone has tips or advice pls lmk -
Hosting a django-rest api on hostinger
I have a project which uses django as a backend, I wish to deploy it on hostinger, anyone has already done this before? I searched alot and didn't find much help, if someone already knows, please write me the steps to successfully deploy the django backend app to hostinger I searched alot and didn't find someone who did this before