Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot send message from Django to Telegram (telegram-send)
I want to send a message from Django to Telegram bot when a user submits a form. Following this short instruction (in Russian) I created a Telegram bot with a certain name, got an API token, installed telegram-send: pip install telegram-send then configured it: telegram-send --configure On request of the program I provided the API token and got a numerical password, which I entered in the Telegram bot channel and got a success message, which says that I can write to the channel with telegram_send. It really works! When I type directly in the terminal telegram-send "Hello!" I see my message popping in the bot channel. But then I stuck, trying to send message from one of my views. According to the instruction, I should import the package in my views.py module: import telegram_send and then use it somewhere in views and functions: telegram_send.send(messages=["Hello!"]) I tried to insert this code in different parts of my ListView, but cound't make it work. For example, I tried to add it to standard method get_context_data, which should be implemented each time the corresponding web page is requested class PropertyListView(ListView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ... telegram_send.send(messages=["Hello!"]) return context But the message does … -
Django Admin autocomplete field selector unidesirable behavior
I have an enterprise project based in Django which is stuck in version 3.1.7 due to unexpected behavior of autocomplete field admin selector. In former versions, when you click in the combobox, the text input editor is autoselected so once you click the first time, you can automatically start writing for searching in the list of fereign key values. I tried to update to newer version of Django, but certain users have complained that now they have to make the extra step of clicking in the text input editor, because it does no longer automatically write once you click the combobox. Ever if this is a minor nuance for computer versed users, workshop users (who lest's be honest, many of them are quite dumb with tech stuff) complain because it does not longer does the usual "easier" stuff and have to be more careful. Anyway, I do not understand why the change of this behavior in newer versions, it is a loss even if it is a small one. Is there any way to force the admin template component to work as it preivously did? -
Django tree of one to one relationships throwing errors
I have these models linked as shown. I created an instance of object 1 and then when i tried to create an instance of object 2 i got this error. django.db.utils.IntegrityError: duplicate key value violates unique constraint "App_Object2_group_id_key" DETAIL: Key (local_id)=(1) already exists. Is there a better way to link these models? class Group(models.Model): group_id = models.PositiveIntegerField() class Object1(models.Model): group= models.OneToOneField( Group, related_name="object_1", on_delete=models.CASCADE, ) class Object2(models.Model): group= models.OneToOneField( Group, related_name="object_2", on_delete=models.CASCADE, ) -
Why Django Count on M2M Field returns wrong value?
I have a manager that calculates all acquired skills by counting sessions related to educational materials attached to a specific skill. Here are my models and manager: class Trajectory(CommonSystemObjectModel): actives = models.ManyToManyField( 'actives.Active', verbose_name='Profile Goals', through='actives.TrajectoryActive', blank=True ) is_active = models.BooleanField( default=True, verbose_name='Is the profile currently active' ) class TrajectoryActive(CommonPriorityDataAbstractModel): trajectory = models.ForeignKey( to='trajectories.Trajectory', on_delete=models.CASCADE, verbose_name='Profile', related_name='trajectory_actives', db_index=True ) active: Active = models.ForeignKey( to=Active, on_delete=models.CASCADE, verbose_name='Goal', related_name='active_trajectories', db_index=True ) threats = models.ManyToManyField( to='threats.Threat', verbose_name='Skills', through='threats.ActiveThreat' ) class ActiveThreat(CommonPriorityDataAbstractModel): """Skill Model""" threat: Threat = models.ForeignKey( to=Threat, on_delete=models.CASCADE, verbose_name='Skill', db_index=True, related_name='threat_actives' ) trajectory_active = models.ForeignKey( to='actives.TrajectoryActive', on_delete=models.CASCADE, db_index=True, verbose_name='Goal attached to the profile', related_name='active_threats' ) content = models.ManyToManyField( CommonContentDataModel, verbose_name='Educational Materials attached to the skill', blank=True, db_index=True, related_name='content_threats' ) objects = ActiveThreatManager() class ActiveThreatManager(CommonObjectContentTypeManager): @staticmethod def _get_is_completed_case() -> Case: """A skill is considered acquired if the number of educational materials is greater than 0, the number of users is greater than 0, and the number of sessions on the skill's educational materials is greater than or equal to the number of users times the number of educational materials.""" return Case( When( Q(users_count__gt=0) & Q(content_count__gt=0) & Q(content__isnull=False) & Q(completed_sessions_count__gte=F('users_count') * F('content_count')), then=True, ), default=False, output_field=models.BooleanField() ) def default_metrics(self, is_completed: bool = None, **kwargs) … -
Django: Unknown command: 'loadcsv'
I get the error Unknown command: 'loadcsv' Type 'manage.py help' for usage. when trying: python manage.py loadcsv --csv reviews/managment/commands/WebDevWithDjangoData.csv why I am getting this error? I running this code in the correct folder seems like loadcsv is not working Do i need to install something to run loadcsv? -
Set a list of available times in jquery timepicker
I am trying to set a list of predefined times in a jQuery timepicker. It should run from 10am to 12 midnight. I am also trying to highlight certain times that there is no availability. I believe my code is mostly correct for this functionality. What I really need help with is getting the timepicker to show only the selected times. var times = ["6:00 PM", "5:00 PM"]; $('#timepicker').timepicker ({ timeFormat: 'h:mm p', interval: 60, minTime: '10:00am', maxTime: '12:00am', startTime: '10:00', dynamic: false, dropdown: true, scrollbar: true, beforeShowDay: function (time) { var string = jQuery.timepicker.formatTime('h:mm p', time); if ($.inArray(string, times) != -1) { return [true, 'highlighted-time']; } else { return [true, '']; } }, }); -
Integrating entities, services, selectors, and usecase into Django DRF architecture
I'm working on a Django DRF project and am considering adopting two different approaches compared to the standard Django architecture. I'd like to incorporate some concepts from other frameworks and would appreciate the community's feedback on these ideas. Primary Objective: My main goal is to achieve a modular and replicable system. First approach: Services, Selectors, Usecase Base: I'm using the standard Django DRF architecture with models, views, and serializers. Services: These are specialized boxes where I group all actions related to data creation and updating. The idea is to have a clear separation of CRUD operations. Selectors: Here, I include all actions related to data retrieval and filtering. The goal is to clearly separate responsibilities and have a singular place for all queries and data retrieval operations. Usecase: This is the core of the architecture. In this box, I encapsulate all the business logic. The idea is to have a central point where all complex logic and business rules are managed. So, the flow would be: the user calls the API, the view validates input and output data, and then calls the execute of the usecase. Within the usecase, I incorporate various actions taken from services and selectors. Second approach: … -
How can I save all the request/response in django
I have a project with multi tenancy functionality in Django. I have various apps doing different works. I have a requirement where i need to save all the request/response from any app to any url into a separate directory with each client code as different different directories inside. all the request/response can be saved as <REQ_NAME>_.json Do we have a way or some kind of middleware which can help me achieve this? -
Docker-compose ERROR [internal] booting buildkit, http: invalid Host header while deploy Django
I'm using docker compose to create a Django server, MySQL database and Django Q on a Ubuntu 22.04.3. But when I run docker-compose -f ./docker-compose.yml up, I have the following error: [+] Building 38.8s (1/1) FINISHED => ERROR [internal] booting buildkit 38.8s => => pulling image moby/buildkit:buildx-stable-1 20.4s => => creating container buildx_buildkit_default 18.5s ------ > [internal] booting buildkit: #0 38.84 time="2023-10-13T13:02:28Z" level=warning msg="using host network as the deftime="2023-10-13T13:02:28Z" level=warning msg="using host network as the default" #0 38.84 time="2023-10-13T13:02:28Z" level=warning msg="skipping containerd worker, as \"/run/containerd/containerd.sock\" does not exist" #0 38.84 dtime="2023-10-13T13:02:28Z" level=info msg="found 1 workers, default=\"abfxoy5dnaaz4694avydedw1g\"" #0 38.84 `time="2023-10-13T13:02:28Z" level=warning msg="currently, only the default worker can be used." #0 38.84 \time="2023-10-13T13:02:28Z" level=info msg="running server on /run/buildkit/buildkitd.sock" #0 38.84 time="2023-10-13T13:02:28Z" level=warning msg="skipping containerd worker, as \"/run/containerd/containerd.sock\" does not exist" #0 38.84 time="2023-10-13T13:02:28Z" level=warning msg="currently, only the default worker can be used." #0 38.84 time="2023-10-13T13:02:28Z" level=warning msg="currently, only the default worker can be used." #0 38.84 ------ http: invalid Host header My Docker info: Client: Context: default Debug Mode: false Plugins: buildx: Docker Buildx (Docker Inc., v0.10.4) compose: Docker Compose (Docker Inc., v2.17.2) Server: Containers: 1 Running: 1 Paused: 0 Stopped: 0 Images: 4 Server Version: 20.10.24 Storage Driver: zfs Zpool: rpool … -
TemplateDoesNotExist when rendering an email message with Celery in Django
I am developing an API for a forum website and have a classed-based view that sends an email message to a user in order to make his email confirmed. I have a celery task, that sends email and in the task I render data to string (email template). But when I call the task in my APIView, I get error that template does not exist. However, when I call it just as a regular function, without delay method it works as expected. Also it seems that there is no problem with Celery itself because I can run other tasks successfully. Here is the code of the view. class RequestEmailToConfirmAPIView(GenericAPIView): permission_classes = [IsAuthenticated, EmailIsNotConfirmed] success_message = 'The message has just been delivered.' serializer_class = DummySerializer def get(self, request): current_url = get_current_site(request, path='email-confirmation-result') user = request.user token = EmailConfirmationToken.objects.create(user=user) send_confirmation_email.delay( template_name='email/confirm_email.txt', current_url=current_url, email=user.email, token_id=token.id, user_id=user.id ) return Response(data={"message": self.success_message}, status=status.HTTP_201_CREATED) note: get_current_site function returns the current url including protocol (http) in order to create the url for a user to click and confirm his email the code of send_confirmation_email task: @shared_task def send_confirmation_email(template_name: str, current_url: str, email: str, token_id: int, user_id: int): """ Отправляет письмо для подтверждения определенных действий. """ data = … -
Django - AllAuth How to style the email.html template?
Quick question. I'm beefing up the authentication for my Django application. I would like to have users change and verify their emails with Allauth but I can't figure out how to style a template. Is there a way how we can style the email.html template? I tried to add {{ form.as_p }} but I only get an email field. I don't know how to add everything else. I tried looking at the Github for allauth as well for the email.html page and I don't understand it because there's a bunch of template code. I don't know what to strip out or keep. Below is what the page looks like without styling. Any help is gladly appreciated! Thanks! -
wagtail login page is endlessly looping into login page
I had a dockerised setup for a python web application with wagtail as cms which was deployed in EKS. Everything on the web page seems fine, every error seems fine but I'm unable to login to wagtail portal when I'm trying doman.com/admin. Stack I use Requirements.txt djangorestframework==3.11.0 Django>=2.1,<2.2 wagtail==2.5.1 # ***************************************************************************** django_compressor==2.2 django-libsass==0.7 django-multiselectfield django-csp django-storages[google] elasticsearch>=5.0.0,<6.0.0 # choose mariadb or postgresql (should also be set in Dockerfile).. mysqlclient==1.3.13 cssutils python-dateutil>=2.7.3,<2.8 untangle==1.1.1 puput==1.0.5 # = = = = = = = = = = = = = = = = = = = = = = = = ## puput requirements.. django-el-pagination>=3.2.4 django-social-share==1.4.0 django-colorful>=1.3 ## puput wp2pupt (WordPress importer) requirements.. lxml>=4.2.5,<4.3 # = = = = = = = = = = = = = = = = = = = = = = = = uWSGI==2.0.17 boto3==1.26.125 boto wagtailmenus==3.1.2 Please let me know if you need more info, THANKS IN ADVANCE Explained wagtail login issue and expecting some issue with code or versions i'm using -
Is it possible to save 2 or more related models in one view? in Django?
I don’t know how to save multiple linked models in django, I’m trying to override get_success_url but I’m at a dead end(. I'm trying to make sure that when saving a form, a model with basic information is saved, associated with the model with a phone number, and that is associated with the client's name. This is all so that you can save several numbers for one client; in the future, I also want to connect the client with the client’s address, because there can be several addresses. Here's the code: views.py from .models import Orders, Person, Phone from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .forms import OrdersForms, AuthUserForm, RegisterUserForm from django.urls import reverse, reverse_lazy from django.contrib import messages from django.contrib.auth.views import LoginView, LogoutView from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect class OrderCreateView(CustomSuccessMessageMixin, CreateView): model = Orders template_name = 'create.html' form_class = OrdersForms success_url = reverse_lazy('data_base') success_msg = 'Заявка дабавлена' def form_valid(self, form): self.object = form.save(commit=False) self.object.author = self.request.user self.object.save() return super().form_valid(form) def get_success_url(self): # phone_number = self.request.POST.get('phones') name = self.request.POST.get('client_name') phone_number = self.request.POST.get('phones') id = self.request.POST.get('id') # ?? Person.objects.create(client_name=name) Phone.objects.create(phone=phone_number, contact=id) # I don’t know what to … -
IntegrityError NOT caught during Unit Test but other DB errors are caught
I'm using Python 3.7 and Django 3.0.3 I have a unit test that looks like this: class MaintenenceEndpointTest(APITestCase): """Maintenence Endpoint tests """ def test_reset_cost_center_throws_error_if_sales_profile_is_not_in_database(self): """Ensure the database throws an error and the endpoint returns 500 if the sales_profile is not in database""" response = self.client.post('/maintenance/reset_cost_center/', data={"cost_center_code": "test_cost_center_code", "sales_profile": "Fronter SMIA NOT PRESENT"}, format='json', HTTP_ACCEPT='application/json') self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR) and inside the Django endpoint code that gets called by the test, I have this: try: # Call the Database with an Update using the field(s) chosen by the caller (in kwargs now) CostCenter.objects.filter(cost_center_code=cost_center_code).update(**kwargs) except Exception as e: logging.error( f' CostCenterUpdateProfileAndRole:post failed with errors. Failed in updating {cost_center_code} with {kwargs} ' f'Unexpected error! Error is: [ {e} ]') return Response( data={'Error': f'Unexpected error! Error is: [ {e} ]', }, status=500) logging.info( f' CostCenterUpdateProfileAndRole:post successfully called. Set the field(s) {kwargs} for cost_center_code {cost_center_code}') return Response(status=200, data={f'Success': f'Provided cost_center_code {cost_center_code} was changed to {kwargs}'}) When I run this code under normal circumstances and pass in a non-existing Sales Profile in the JSON, the IntegrityError is ALWAYS caught by the try/except and it passes back the 500. When I run the Unit Test the IntegrityError is NEVER caught by the try/except and the code under test returns … -
Problems configuring my Django project to upload static and media files to DigitalOcean Spaces
I have created a social media app using Django and Vue. My frontend is hosted on Vercel (which is working just fine) and my backend is hosted on DigitalOcean's App Platform (I am NOT using a droplet) and connected to my Github repo. Everything about my app is functioning perfectly well except for my user-uploaded media files. I am using django-storages (S3Boto3Storage) for this purpose and have followed all of the instructions in several tutorials (such as this one, this one, and the documentation). I have even gotten my static files up on DigitalOcean Spaces using this process (as in, when I check my bucket, the correct files appear to be there), but every time I try to deploy, it fails at python manage.py collectstatic. I've tried changing literally every single element of my settings.py file pertaining to static and media variables, creating a new Spaces bucket, messing with STATICFILES_DIRS and STATIC_ROOT, and updating/changing my App-level environment variables in the DigitalOcean App Platform UI. However, I keep getting a few different errors that I've been having trouble debugging. Sometimes I get this error: ?: (staticfiles.W004) The directory '/workspace/backend/static' in the STATICFILES_DIRS setting And other times I get this error: botocore.exceptions.ClientError: … -
Websocket message from Django backend to javascript frontend
So I have correctly setup the Django consumer and routing for my websocket communication with DJango channel. The consumers.py and routing.py are in the same app where I want to use the ws = create_connection("ws://127.0.0.1:8080/notifications") My issue is that, if I set a message from the backend with ws = create_connection("ws://127.0.0.1:8080/notifications") ws.send(json.dumps({"message": "Ricevuto"})) ws.close() The frontend which is correctly connected to the same websocket with var socket = new WebSocket("ws://127.0.0.1:8080/notifications") // Creating a new Web Socket Connection // Socket On receive message Functionality socket.onmessage = function(e){ console.log('message', e) console.log(e.data) // Access the notification data } // Socket Connet Functionality socket.onopen = function(e){ console.log('open', e) } seems to no receive the message even if the consumer on DJango correctly receive it consumer.py import json from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() self.send(text_data=json.dumps({"message": "Benvenuto"})) def disconnect(self, close_code): pass def receive(self, text_data): print(text_data) text_data_json = json.loads(text_data) message = text_data_json["message"] self.send(text_data=json.dumps({"message": message})) routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r"notifications", consumers.ChatConsumer.as_asgi()), ] asgi.py application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(websocket_urlpatterns)) ), } ) -
Can't upload image Django REST
I am trying to upload image through django rest framework api but I am not getting the form properly. models.py in my 'core' app: def office_image_file_path(instance, filename): ext = filename.split('.')[-1] filename = f'{uuid.uuid4()}.{ext}' return os.path.join('uploads/office/', filename) class Office(models.Model): # Other fields... image = models.ImageField(null=True, upload_to=office_image_file_path) serializer.py in 'office' app: class OfficeSerializer(serializers.ModelSerializer): class Meta: """Meta class for OfficeSerializer.""" model = Office fields = "__all__" views.py in 'office' app: class OfficeViewSet(viewsets.ModelViewSet): """ API endpoint that allows offices to be viewed or edited if authenticated. """ queryset = Office.objects.all() serializer_class = OfficeSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def get_queryset(self): """ Retrive offices for authenticated users. """ return self.queryset.filter(user=self.request.user) def get_serializer_class(self): if self.action == 'upload_image': return OfficeImageSerializer return OfficeSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) @action(methods=['POST'], detail=True, url_path='upload-image') def upload_image(self, request, pk=None): office = self.get_object() print(request.data) # Debug: Print the request data serializer = self.get_serializer( office, data=request.data ) if serializer.is_valid(): serializer.save() return Response( serializer.data, status=status.HTTP_200_OK ) return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) In Swagger when I try to upload the image via /office/office/{id}/upload-image/, I do not get the "Choose file" button. Instead I get a string($uri) field and I can't execute the file upload. I have already set MEDIA_URL and MEDIA_ROOT in my setting.py file. -
How to create single log file in uwsgi?
I’m using below uwsgi logging config file for Django application. Its creating two log files: access_log-2023-10-13.log app_log-2023-10-13.log Now I want to create one more log file named all_logs-2023-10-13.log which will have both access + app log file data. Is there any way to create this? [uwsgi] master = true http-socket = xyz_port memory-report = true module = demo_app.wsgi ... ... ... log-date = %%d/%%m/%%Y %%H:%%M:%%S %%Z logformat-strftime = true logger = stdio log-format = %(addr) - %(user) [%(ftime)] "%(method) %(uri) %(proto)" %(status) %(size) %(referer) %(uagent) %(pid) req-logger = file:/var/log/demo_app/access_log-@(exec://date +%%Y-%%m-%%d).log logger = file:/var/log/demo_app/app_log-@(exec://date +%%Y-%%m-%%d).log log-reopen = true -
How to configure Django and Nginx to allow access of static files with docker?
I'm trying to run a docker-compose container with Django and nginx but I can't access any static html or css even if lookin at the containers' app log all seems fine. I'm probably messing up with paths and permissions and I don't know where is the issue. Here is my settings.py file splitted in images because stackoverflow flagged the post as spam: InstalledApps Middleware_templates database_auth staticurl_staticroot Here is my docker compose.yml: `# Specifies Docker compose version version: "3.9" services: djangoapp: build: context: . restart: always volumes: - static-data:/vol/web environment: - DB_HOST=db - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} - SECRET_KEY=${DJANGO_SECRET_KEY} - ALLOWED_HOSTS=${DJANGO_ALLOWED_HOSTS} - OPENAI_KEY=${OPENAI_KEY} depends_on: - db db: image: postgres:13-alpine restart: always volumes: - postgres-data:/var/lib/postgresql/data environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASS} proxy: build: # project folder name context: ./proxy restart: always depends_on: - djangoapp ports: - 80:8000 volumes: - static-data:/vol/static volumes: postgres-data: static-data:` My proxy dockerfile: `FROM nginxinc/nginx-unprivileged:latest LABEL maintainer="londonappdeveloper.com" COPY ./default.conf.tpl /etc/nginx/default.conf.tpl COPY ./uwsgi_params /etc/nginx/uwsgi_params COPY ./run.sh /run.sh ENV LISTEN_PORT=8000 ENV APP_HOST=djangoapp ENV APP_PORT=9000 USER root RUN mkdir -p /vol/static && \ chmod 755 /vol/static && \ touch /etc/nginx/conf.d/default.conf && \ chown nginx:nginx /etc/nginx/conf.d/default.conf && \ chmod +x /run.sh VOLUME /vol/static USER nginx CMD ["/run.sh"]` My default.conf.tpl file : … -
ModuleNotFoundError: No module named 'kafka.vendor.six.moves' in Dockerized Django Application
I am facing an issue with my Dockerized Django application. I am using the following Dockerfile to build my application: FROM python:alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV DJANGO_SUPERUSER_PASSWORD datahub RUN mkdir app WORKDIR /app COPY ./app . RUN mkdir -p volumes RUN apk update RUN apk add --no-cache gcc python3-dev musl-dev mariadb-dev RUN pip3 install --upgrade pip RUN pip3 install -r requirements.txt RUN apk del gcc python3-dev musl-dev CMD python3 manage.py makemigrations --noinput &&\ while ! python3 manage.py migrate --noinput; do sleep 1; done && \ python3 manage.py collectstatic --noinput &&\ python3 manage.py createsuperuser --user datahub --email admin@localhost --noinput;\ python manage.py runserver 0.0.0.0:8000 In my requirements.txt file: kafka-python==2.0.2 When I run my application inside the Docker container, I encounter the following error: ModuleNotFoundError: No module named 'kafka.vendor.six.moves' I have already tried updating the Kafka package, checking dependencies, and installing the six package manually. However, the issue still persists. Can anyone provide insights on how to resolve this error? Thank you in advance for your help! -
Django ORM group by on primary key mysql
In the django ORM it's easy to group by when using an aggregate function like this: from django.contrib.auth.models import User User.objects.values('id').annotate(Count('id')) However if I want to group by without an aggregation function (in case of a join for example) User.objects.filter(groups__name='foo') You can use distinct function, but it will distinct on all columns. Which is painfully slow. In some other DB you can do DISTINCT ON but not on mariadb/mysql. Is there a way to group by a specific column with the django ORM or do I have to write RawSQL ? -
LOGIN FORM: I need Login for from the blow User Mode
user_type=[(1, "manager"), (2, "registeror"), (3, "Engineer"),] class Users(AbstractBaseUser): user_id=models.CharField(max_length=50,primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) user_name = models.EmailField(max_length=50,unique=1) pass_word= models.CharField(max_length=15) user_type = models.IntegerField(choices=user_type,default=3) is_active=models.BooleanField(auto_created=True,default=True) is_staff = models.BooleanField(default=False,null=True,auto_created=True,blank=True) is_superuser = models.BooleanField(default=False,auto_created=True,null=True,blank=True) USERNAME_FIELD = "user_name" def __str__(self) -> str: return f"{self.first_name.upper()} {self.last_name.upper()}" user_type=[(1, "manager"), (2, "registeror"), (3, "Engineer"),] class Users(AbstractBaseUser): user_id=models.CharField(max_length=50,primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) user_name = models.EmailField(max_length=50,unique=1) pass_word= models.CharField(max_length=15) user_type = models.IntegerField(choices=user_type,default=3) is_active=models.BooleanField(auto_created=True,default=True) is_staff = models.BooleanField(default=False,null=True,auto_created=True,blank=True) is_superuser = models.BooleanField(default=False,auto_created=True,null=True,blank=True) USERNAME_FIELD = "user_name" def __str__(self) -> str: return f"{self.first_name.upper()} {self.last_name.upper()}" LOGIN FORM: I need Login for from the blow User Mode Login Functionality Is not work .I need some guide to Implement Login and Authantication LOGIN FORM: I need Login for from the blow User Mode LOGIN FORM: I need Login for from the blow User Mode LOGIN FORM: I need Login for from the blow User Mode LOGIN FORM: I need Login for from the blow User Mode -
How to use celery with django duration field
I have model Banner with duration field. I wanna update value of status field of banner after end of duration. For example, I'm creating object with hour duration, and I need to create task which will change value of status field after hour. How can I do this celery? # models.py class AdvertisementModelMixin(models.Model): class Statuses(models.TextChoices): ACTIVE = "active", _("Active") HIDDEN = "hidden", _("Hidden") DELETED = "deleted", _("Deleted") TEST = "test", _("Test") link = models.URLField() view_count = models.PositiveIntegerField(default=0) age_from = models.PositiveSmallIntegerField( blank=True, null=True, validators=[MaxValueValidator(80)]) age_to = models.PositiveSmallIntegerField( blank=True, null=True, validators=[MaxValueValidator(80)]) devices = models.ManyToManyField(Device, verbose_name="platforms",) duration = models.DurationField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status = models.CharField(max_length=30, choices=Statuses.choices, default=Statuses.ACTIVE) -
Life Cycle of Daemon thread and Non Daemon Thread in Django
I'm trying to execute a long-running process (sending mail to around 600 people) using threading module. My Django view and email processing function goes like this: def daily_wap(request): context = { } if request.method == 'POST': file = request.FILES.get('dailywap', None) if file: try: wap = pd.read_excel(file, header = [0,1], engine='openpyxl').dropna(how = 'all') t = threading.Thread(target= daily_wap_automailer, kwargs={'wap': wap}, daemon = True) t.start() messages.success(request , "Task Scheduled") return HttpResponseRedirect(reverse('usermanagement:daily_wap_automailer')) except Exception as e: messages.error(request, 'Error occured: {0}'.format(e)) return HttpResponseRedirect(reverse('usermanagement:daily_wap_automailer')) else: messages.error(request, 'File not provided') return HttpResponseRedirect(reverse('usermanagement:daily_wap_automailer')) return render(request, "wap_automailer.html", context) def daily_wap_automailer(wap): ### In send_mail, im iterating over each mail ids and sending the mail, ### which then returns total mail successfully sent(count) and total no users (total) count , total = send_mail(wap=wap) return (count , total) I'm executing the function daily_wap_automailer using the daemon thread. As per the online documenation and resources, daemon thread gets terminated as soon as the main/parent thread gets terminated provided it does not have any non-daemon thread to execute. The main thread (HTTP request response cycle) typically takes less than a sec to complete(sending the message "Task Scheduled" to Client), does it mean that the daemon thread which executes func daily_wap_automailer won't have sufficient time … -
How can I add a telegram bot in Django application
I have a Django application (store) and I want to receive notifications about new users who have registered in the store. I also want to receive messages via telegram bot if any user has logged in. I've never written telegram bots before. I will be glad of any information and support. The most important thing I want to know is how to connect bot and django. Does the bot need private server? Any links or tutorials will be helpful.