Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
multiply in aggregation of django
Our View get a JSON like this : { "cart":{ "pizza": 2, "burger": 3 } } In cart is the foods name, and count of the food . My food model: class Food(models.Model): name = models.CharField(verbose_name=_('name'), max_length=100, unique=True, blank=False, editable=True) price = models.IntegerField(verbose_name=_("maximum price"), null=False, blank=False, editable=True) discount = models.PositiveIntegerField(validators=[MaxValueValidator(100)], null=False, blank=False, default=0) created_at = models.DateTimeField(verbose_name=_("created time"), auto_now_add=True, editable=False) I want to calculate the total price how I can do that with aggregation and annotate in Django ? NOTE: every food has a price that should be multiplied on count of that food. i have done this in a for loop : class OrderView(APIView): def post(self, request): srz_data = CartSerializer(data=request.data) if srz_data.is_valid(): cart_order = srz_data.data['cart'] foods = Food.objects.filter(name__in=cart_order) total_price = 0 for i,n in cart_order.items(): total_price += foods.get(name=i).price * n and done some experiment on aggregation : class OrderView(APIView): def post(self, request): srz_data = CartSerializer(data=request.data) if srz_data.is_valid(): order = srz_data.data['cart'] f = Food.objects.filter(name__in=order).aggregate(Sum('max_price')) But after a day i couldn't find a answer for this, if someone can help i will very appreciate it. thanks -
Create view that shows all objects relating to current user's department
I have the following Django model: from django.conf import settings from django.db import models class Appeal(models.Model): DEPARTMENTS = [ ("a", "DeptA"), ("b", "DeptB"), ("c", "DeptC"), # long list of departments here ] title = models.CharField(max_length=400) department = models.CharField(choices=DEPARTMENTS) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="appeals" ) And a view like this: from django.shortcuts import get_list_or_404, render def appeal_list_view(request): visible_appeals = get_list_or_404(Appeal, author=request.user) return render(request, "appeals/index.html", {"appeals": visible_appeals}) This shows only the appeals by the current user. I would like to change this code so that: each user is associated with a department, a user is shown all appeals from their own department (regardless of whether or not they or another user from the same department submitted it). What would be the best way to achieve this? I considered creating a group per department, which would solve the first requirement but then I'm not sure how to approach the second one. -
DJango WOPI server error when submit iframe
I'm implementing a custom wopi server to communicate a custom documenty library with office 365. The implementation is based on a django server which implements all wopi endpoints. That server communicates a cloud document library server with wopi. The problem is that when I submit the iframe to open a document with the office 365 I get the following error in javascript: [![enter image description here][1]][1] I searched for that error on the web, but all the solutions implies modify office 365 code. The index.html that I'm using is the following: <!DOCTYPE html> <html lang="en"> <head> <title>vvwopi</title> <link rel="stylesheet" href="../static/css/bootstrap.min.css"> <script src="../static/js/jquery-3.6.1.min.js"></script> <script src="../static/js/bootstrap.min.js"></script> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"> <link rel="shortcut icon" href="https://c1-word-view-15.cdn.office.net/wv/resources/1033/FavIcon_Word.ico" /> <style> body { margin: 0; padding: 0; overflow: hidden; -ms-content-zooming: none; } #office_frame { width: 80%; height: 80%; position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: 0; border: none; display: block; } </style> </head> <body> <div id="wopiTest"> <h1>VisualVault WOPI Test</h1> <p> Use this page to demo the WOPI host implementation </p> <p> Discovery file: https://ffc-onenote.officeapps.live.com/hosting/discovery </p> <button class="wopi_editDoc_button" id="vwWopiTest" onclick="formSubmit('office_wopiTest_form')">Wopi Test Document</button> <form id="office_form" name="office_form" target="office_frame" action="" method="post"> <input name="access_token" value="" type="hidden" /> <input name="access_token_ttl" value="" type="hidden" /> … -
How do I run two different webservers from my django project with gunicorn?
My django project has a webserver, which I run with gunicorn. Now, I have also developed a gRPC-server, which I also need to deploy, preferrably also with gunicorn. The gRPC server has a different entrypoint, e.g. within myapp.management.grpc_downloader there's the class GRPCDownloader and that has a method run_server()`. I somehow need to hand this method to gunicorn, in such a way that I can run this as a separate service in systemd, or in Docker once I containerize this. How do I achieve this? Do I just write a second wsgi.py file, e.g. wsgi_grpc.py? And what should I write in there? The current one was automatically generated. -
im facing problem with rendering the profile picture in django
TemplateSyntaxError at /profile/1 Invalid block tag on line 14: 'static', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/profile/1 Django Version: 4.1.13 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 14: 'static', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? Exception Location: C:\Users\hrush\anaconda3\envs\djangopython\Lib\site-packages\django\template\base.py, line 558, in invalid_block_tag Raised during: main.views.user_page Python Executable: C:\Users\hrush\anaconda3\envs\djangopython\python.exe Python Version: 3.11.5 Python Path: ['C:\Users\hrush\OneDrive\Desktop\eventapp\core', 'C:\Users\hrush\anaconda3\envs\djangopython\python311.zip', 'C:\Users\hrush\anaconda3\envs\djangopython\DLLs', 'C:\Users\hrush\anaconda3\envs\djangopython\Lib', 'C:\Users\hrush\anaconda3\envs\djangopython', 'C:\Users\hrush\anaconda3\envs\djangopython\Lib\site-packages'] Server time: Mon, 20 Nov 2023 23:30:41 +0530 Error during template rendering In template C:\Users\hrush\OneDrive\Desktop\eventapp\core\templates\profile.html, error at line 14 -
Problem with event listening on Select2 element - Django
Initializes the Select2 element by creating a widget and plugging it into the form. [forms.py] class S2SelectWidget(s2forms.Select2Widget): search_fields = ( 'name__icontains', ) class MyForm(forms.ModelForm): class Meta: model = MyModel fields = ('field1', 'field2', 'field') widgets = { 'field1': S2SelectWidget(), } [html] $(document).ready(function() { myField = $('#id_field1'); console.log(myField); myField.on('change', function() { console.log('ok') }) }); I don't receive a message in the console that an item has changed. When I use the click method and click on the label, the message is displayed. What technique do I need to use to listen to my element using the change method? Thanks. -
How to share the django app in the Network?
We can share the Flask app in network by passing host='0.0.0.0' as argument in app.run(). Example: app.run(host='0.0.0.0') And the flask gives links for both localhost (127.0.0.1:5000) and for the network (ip_address:5000). How can I achieve same for the Django? I've tried passing '0.0.0.0' and the 'ip_address' in ALLOWED_HOST list in settings.py but did'nt worked. I know about command: python manage.py runserver ip_address:8000 but then app is not accessed by localhost:8000 :(. I want to access django app by both localhost as well as ip_address of device. How can I do it? -
combine foreign key with fsm field in django-fsm
import datetime from django.db import models from django_fsm import FSMField, transition class WorkFlowState(models.Model): name = models.CharField(max_length=64, unique=True) preceding = models.ForeignKey( 'self', on_delete=models.CASCADE, blank=True, null=True) # postAction = models.CharField(max_length=64, null=True, blank=True) default_warn1 = models.DurationField( blank=False, null=False, default=datetime.timedelta(hours=12)) default_warn2 = models.DurationField( blank=False, null=False, default=datetime.timedelta(days=1)) default_duration = models.DurationField( blank=False, null=False, default=datetime.timedelta(days=1)) def __str__(self): return self.name class Transition(models.Model): name = models.CharField(max_length=64) source_state = models.ForeignKey(WorkFlowState, on_delete=models.CASCADE, related_name='transitions_from') target_state = models.ForeignKey(WorkFlowState, on_delete=models.CASCADE, related_name='transitions_to') def __str__(self): return self.name class Task(models.Model): name = models.CharField(max_length=100) assigned_on = models.DateTimeField(auto_now=True) created_on = models.DateTimeField(auto_now_add=True) task_state = FSMField(models.ForeignKey(WorkFlowState, on_delete=models.PROTECT), protected=True) def __str__(self): return self.task_state def perform_transition(self, transition_name): try: transition = Transition.objects.get(name=transition_name, source_state=self.task_state) setattr(self, 'assigned_to', transition.target_state) self.save() return True except Transition.DoesNotExist: return False I want to have a workflow state the that is a foriegn key to worlflowstate. first i create a transition model that can define states for fsm transition andi tried to define it as you see but it doent work. it store task status like a string -
Database migration from MySQL to Postgres Schema
I'm currently working on migrating a Django project that was initially using MySQL to PostgreSQL. The project involves multi-tenancy with separate schemas managed by django-tenants. I'd like some guidance on the best practices for migrating the database while ensuring compatibility with django-tenants. Are there specific steps or considerations I should be aware of to successfully transition from MySQL to PostgreSQL in this scenario? Any advice or examples related to migrating databases with django-tenants and multi-tenancy would be greatly appreciated. Thanks in advance! -
How to save Many to many field in Django?
I'm writing a function for a put request in Django. I have a many to many field and I have a problem updating this field. Here is my function @method_permission_classes([IsAdministratorManyToMany]) def update(self, request, *args, **kwargs): instance = self.get_object() request_data=request.data for field in ["services"]: if field in request_data: request_data[field] = request_data[field].split(",") serializer = self.get_serializer(data=request_data) print(serializer) serializer.is_valid(raise_exception=True) if serializer.validated_data.get("avatar"): try: if instance.avatar: instance.avatar.delete() except Exception as error: return Response( f'Error when update Institution avatar. {error}', status=status.HTTP_400_BAD_REQUEST, ) serializer.save() return Response(serializer.data) def perform_update(self, serializer): instance = serializer.instance instance = self.get_object() if serializer.validated_data.get("avatar"): try: if instance.avatar: instance.avatar.delete() except Exception as error: return Response( f'Error when update Institution avatar. {error}', status=status.HTTP_400_BAD_REQUEST, ) serializer.save() My serializer: class InstitutionSerializer(serializers.ModelSerializer): class Meta: model = Institution fields = ( "id", "avatar", "name", "working_hours", "services", "address", "location_lon", "location_lat", "email", "is_call_to_home", "is_emergency_call", "document", "status", "comments", "administrators", "managers", ) read_only_fields = ('status','administrators','managers') My model: class Institution(models.Model): """ Pet's parasite treatment """ avatar = models.ImageField( verbose_name=_("Avatar"), upload_to=upload_avatar, blank=True, ) name = models.CharField( verbose_name=_("Name"), max_length=256, ) working_hours = models.JSONField( verbose_name="Working schedule", ) services = models.ManyToManyField( to=InstitutionServices, verbose_name="Перелік послуг" ) address = models.CharField(max_length=256, verbose_name="Institution addres") location_lon = models.FloatField(null=True, blank=True, verbose_name="longitude") location_lat = models.FloatField(null=True, blank=True, verbose_name="latitude") email = models.EmailField(verbose_name="E-mail") is_call_to_home = models.BooleanField(default=False, verbose_name="Виклик до дому") is_emergency_call … -
How do I test ExportActionMixin in Django?
I'd like to test files produced on the admin website by import_export.admin.ExportActionMixin in Django. In particular I'd like to test the admin command by looking into the file (which I download on the admin website) and test the files contents. But I don't quite understand how to do it. My admin model: @admin.register(MyModel) class MyModelAdmin(ExportActionMixin, admin.ModelAdmin): resource_class = MyResource My resource class: class MyResource(resources.ModelResource): class Meta: model = MyModel headers = ('User ID', 'name') fields = ('user__id', 'user__name') def get_export_order(self): return self.Meta.fields def get_export_headers(self): return self.Meta.headers def get_queryset(self): queryset = super(MyModel, self).get_queryset() return queryset.select_related('user') My test: class MyTestCase(TestCase): def setUp(self): self.client = Client() user = User.objects.create(login="admin", email="admin@example.com", password="password") user.is_staff = True user.is_superuser = True user.save() self.client.login(username="admin", password="password") def test_import(self): url = reverse('/admin/project/mymodel') data = {'action': 'export_admin_action', 'file_format': 0, '_selected_action': 1} response = self.client.post(url, data=data, follow=True) self.assertEqual(200, response.status_code) self.assertEqual('text/csv', response['Content-Type']) self.assertTrue(response.has_header('Content-Disposition')) My test returns status code 200 (I assume the post request is successful) but the second assertion fails: AssertionError: 'text/csv' != 'text/html; charset=utf-8'. But I need to get the requested file and then test its contents. How can I do that? -
How can I use Azure AppInsights with OpenTelemetry in Django
Hi I have a Django app and I wanted to connect my traditional logs with Azure AppInsights. I'm using logging lib for my logs and this piece of code occurs in 100 times in the project. import logging logger = logging.getLogger(__name__) When I checked the open telemetry Azure docs I found the following example but to use this one I have to change all the logger instances because we need to add handler for open telemetry and an exporter for Azure. Is there any way to do it without changing all the logger occurrences? logger_provider = LoggerProvider() set_logger_provider(logger_provider) exporter = AzureMonitorLogExporter.from_connection_string( os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] ) get_logger_provider().add_log_record_processor(BatchLogRecordProcessor(exporter, schedule_delay_millis=60000)) # Attach LoggingHandler to namespaced logger handler = LoggingHandler() logger = logging.getLogger(__name__) logger.addHandler(handler) logger.setLevel(logging.INFO) -
fcm-django add extra params
I use drf and fcm-django for pushing notifications to user devices (android/ios) (with firebase) My Notification model: class Notification(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, max_length=128) user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) message_type = models.CharField(choices=NotificationType.CHOICES, blank=True, null=True, max_length=32) link = models.URLField(null=True, blank=True) title = models.CharField(max_length=100) body = models.TextField() unread = models.BooleanField(default=True, blank=False,) I need to add extra params "message_type" and "link", something like this: devicesGCM.send_message(body, title=title, type=message_type, link=link) How can I add extra param to notification message. -
How to show dataTable.Buttons in django app
I utilized dataTable.view to show particular data in my Django app and I'd like to show buttons such as csv and excel. I add buttons in options but when I want to construct them (according to the document), this error: $.fn.dataTable.Buttons is not a constructor appears. I also added buttons.dataTables.min.js , buttons.html5.min.js, buttons.foundation.min.js in the UI. var options = { ..... buttons: [ 'excel', 'csv' ], sDom: 'Bfrtip' }//end of defaultDataTableOptions var datatable = datatableview.initialize($('.datatable'), options); var table = $('#DataTables_Table_0').DataTable(); new $.fn.dataTable.Buttons( table, { buttons: [ 'copy', 'excel' ] } ); table.buttons().container().appendTo( $('#buttons', table.table().container() ) ); $.fn.dataTable.Buttons is not a constructor -
Image from django database showing as path
I am trying to display images from my Django database. But this is what I'm getting. enter image description here I have the images saved here: enter image description here and this is my code: Html: {% for image in images %} <div class="img"> {{ image.photo }} <img class="cardImg2" src=" {{ image.photo.url }} " alt=""> </div> {% endfor %} Views.py: def detail(request, product_id): product = get_object_or_404(Product, pk=product_id) images = Photo.objects.filter(product=product) return render(request, "kin/detail.html", { "product": product, "images": images }) I want the images to display as actual images and not stringed paths. How do I achieve this? -
Celery task result persistent strategy
I have a web server, a rabbitMQ server and two task processing servers in the system. Using Celery to manage the tasks. The web server needs to query the status of the tasks. Based on Celery's doc, I can choose database as result backend. In this case, should I set a database for the web server and another database for each task processing server or use one database for all these 3 servers? I also tried to use RPC as the backend, but each time the web server restarts, the status of tasks are "PENDING" after querying from AsyncResult. This is my configuration of Celery. CELERY_RESULT_BACKEND = 'rpc://' CELERY_RESULT_PERSISTENT = True CELERY_TRACK_STARTED = True CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_RESULT_EXPIRES = None Anyone can help? Thanks! -
django and s3 doesn't use X-Amz-Algorithm on ec2
I have recently deployed a test server for one of my projects on AWS EC2, utilizing an Ubuntu server with Gunicorn and Nginx. During testing on my localhost, the Django server functioned correctly. Specifically, I have a function generating presigned URLs for files to be accessed in my frontend. These presigned URLs include the X-Amz-Algorithm. However, upon obtaining the link from my EC2 server, I noticed that it incorporates a form of signing, including AWSAccessKeyId, a Signature, and an "Expires" parameter. But not the presigned link with the X-Amz-Algorithm My objective is to achieve the same presigned URL functionality on the EC2 server. How can I accomplish this? settings.py (S3 Bucket Config #S3 BUCKETS CONFIG AWS_ACCESS_KEY_ID = '*************' AWS_SECRET_ACCESS_KEY = '*******************************' AWS_STORAGE_BUCKET_NAME = 'project-backend' AWS_S3_SIGNATURE_VERSION = 's3v4' S3_USE_SIGV4 = True AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' #STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_ADDRESSING_STYLE = 'virtual' AWS_S3_ENDPOINT_URL = 'https://s3.eu-central-1.amazonaws.com' AWS_S3_REGION_NAME = 'eu-central-1' -
view on the django server giving 404 error
I have created 2 functions in a views file and the second function is showing a 404 error. Below is the code for the urls and views from django.contrib import admin from django.urls import path, include from mysite.views import current,hello urlpatterns = [ path('',current,name='time'), path('',hello,name='hello'), ] import datetime from django.http import HttpResponse def hello(request): return HttpResponse("Hello world. I Love you alot.Did you not know?") def current(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html) When i run the server I can see the time output but when i cant see hello world on http://127.0.0.1:8000/hello. As in I have 2 views defined but I can see one view and not the second one. Any suggestions? -
AttributeError: 'EditViewDevis' object has no attribute 'render'
Need help again. My aim is to create a quote and allow the user to add items dynamically. I'm having trouble validating the grouped form: 'EditViewDevis' object has no attribute 'render'. My createView class and updateView class are not working. I got always this error: AttributeError at /nrn/ebe907fe-9711-4657-9319-4b7cb7873ff6/editdevis/. 'EditViewDevis' object has no attribute 'render' I thought the error was due to my form_valid function, What did I do wrong? Any ideas how to resolve this error? Here's my code: forms.py from django import forms from .models import Article, Customer, Devis class ClientForm(forms.ModelForm): class Meta: model = Customer fields = ['name', 'gerant', 'siret', 'email', 'phone', 'address'] class DevisForm(forms.ModelForm): class Meta: model = Devis fields = ['customer', 'paid', 'comments'] labels = { "customer": "Nom Client", "paid": "Paid ? ", "comments": "Comments", } class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ['designation', 'category', 'quantity', 'unit', 'prix_unit', 'devise', ] ArticleFormSet = forms.inlineformset_factory(Devis, Article, form=ArticleForm, fields=['designation', 'quantity', 'prix_unit', ], extra=5, can_delete=True, can_delete_extra=True) views.py from django.shortcuts import redirect, render from django.urls import reverse_lazy from django.views.generic.detail import DetailView from django.views.generic import ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.contrib.auth.mixins import LoginRequiredMixin from nrn_app.forms import ClientForm, DevisForm, ArticleForm, ArticleFormSet from nrn_app.models import Article, Customer, Devis class … -
Export Django logs to Azure AppInsights with OpenTelemetry
I'm trying to use OpenTelemetry to send my Django project logs to Azure Application Insights. According to my research, it is possible to do it in OpenCensus by adding the following configuration. Is it possible to do it in OpenTelemetry? If it is what can I use instead of this class 'opencensus.ext.azure.log_exporter.AzureLogHandler'? My goal is to connect my all logs inside my django app with azure by changing only settings of logging. # Set the AppInsights Key as an env variable so it can be used by the logging system os.environ['APPLICATIONINSIGHTS_CONNECTION_STRING'] = 'InstrumentationKey=XXXXXXXXXXXXXXXXXXXXXXX' LOGGING = { 'disable_existing_loggers': True, #False, #<-- if true then make sure that you have a 'django' and '' logger 'filters': { "require_debug_false": { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'simple': { 'format': '[%(asctime)s] %(levelname)s %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, 'verbose': { 'format': '[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, 'azure_verbose': { 'format': '[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s traceId=%(traceId)s spanId=%(spanId)s', 'datefmt': '%Y-%m-%d %H:%M:%S' }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'INFO', 'filters': ['require_debug_true'], 'formatter': 'verbose' }, 'azure':{ 'level': 'INFO', 'filters': ['require_debug_false'], 'class': 'opencensus.ext.azure.log_exporter.AzureLogHandler', 'formatter': 'azure_verbose' }, }, 'loggers': { 'mylogger': { "handlers": [ "azure", "console", ], }, 'django': { 'handlers': … -
Having difficulty with datePicker in python-django project
The django web-app project I am working on has numerous apps. I am creating a new app with forms. The forms use 'datePicker'. The datePicker class is referenced in an 'attrs{}' block. On my new form I have exactly the same format as forms used in other parts of the project, but the datePicker refuses to display. The application uses Bootstrap 3 and javascript/css, but neither of the latter are referenced in the template. Code is below. I am relatively new to django, and it is not clear to me why this doesn't work. Some part of the is missing, but I can't identify it. What am I missing in this code? Best, Joe White template.html: {% extends 'common/base.html' %} {% load menu_tags %} {% load static %} {% block page_title %}Add New Project{% endblock %} {% block content %} Add New Project {% csrf_token %} {% load bootstrap3 %} {# Display django.contrib.messages as Bootstrap alerts #} {% bootstrap_messages %} {% bootstrap_form form layout="horizontal" %} {% buttons layout='horizontal' %} <button type="submit" class="btn btn-primary"> {% bootstrap_icon "star" %} Submit </button> {% endbuttons %} back to list $(document).ready(function () { $('.datepicker').datepicker({ format: 'yyyy-mm-dd', autoclose: true, }); $('.timepicker').timepicker({ format: 'hh:ii:ss', autoclose: true, showMeridian: … -
Django cannot get values from ManToMany
I have a problem. I write the little blog I have a post model and if I create a new post it has to send a link of the new post to the telegram group. The post has telegram_chat field ManyToMany when I save the post it runs the signal and must send the link, but when I want to get chat ID the query is empty. Sorry for my bad English. class Post(models.Model): """Post Model""" hash = models.UUIDField(default=uuid.uuid4, editable=False) title = models.CharField("Title", max_length=255) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) published_date = models.DateTimeField(auto_now_add=True) category = models.ForeignKey('Category', on_delete=models.CASCADE) tags = TaggableManager() image = models.ImageField(upload_to='post_images/', blank=True, null=True) content = RichTextUploadingField() telegram_chats = models.ManyToManyField('TelegramChat', related_name='posts', blank=True) def __str__(self): return f"{self.title}" def get_absolute_url(self): return reverse("main:post_detail", args=[self.slug]) def save(self, *args, **kwargs): if str(self.hash) not in self.slug: self.slug = f"{self.slug}-{self.hash}" super().save(*args, **kwargs) @receiver(post_save, sender=Post) def send_telegram_message(sender, instance, **kwargs): bot_token = 'YOUR_TELEGRAM_BOT_TOKEN' # Check if the post has associated chat IDs if instance.telegram_chats.exists(): chat_ids = instance.telegram_chats.values_list('chat_id', flat=True) bot = Bot(token=bot_token) # You may customize the message format as needed message = f"New post: {instance.title}\n\n{instance.content}\n\nLink: https://yourdomain.com/path-to-post/{instance.id}/" if instance.image: image_path = instance.image.path for chat_id in chat_ids: bot.send_photo(chat_id=chat_id, photo=InputFile(image_path), caption=message) else: for chat_id in chat_ids: bot.send_message(chat_id=chat_id, text=message) -
Proper way of react native - django authentication
What is the proper way of creating authentication in react native Login component with Django CBV Login(LoginView). Do I need to write API using DRF? Or can I just fetch POST request to .../login with username and password as body? -
Heroku and Django giving a 500 error when Debug is not set to False
I have been following and checking every forum post, setup instruction and video I can find. I've been checking git hub repos and comparing to my code. I cannot get my Django application to run on Heroku with DEBUG set to false and not get a 500 server error. So I wanted to reach out to ask two questions: How critical is it that I have DEBUG set to False? I have seen that it could expose information but the application is more of an online resume/portfolio site ("Hey, this is some information about me and here are some small apps I've made") Could someone take a look at my code and see what I am missing ( https://github.com/seanhayes13/codingHavoc )? I'm not using any databases for this part of the app Thank you If DEBUG is set to False, 500 error. If DEBUG is set to True, everything runs fine. I have the Heroku recommended if block setting the ALLOWED_HOSTS to ['*']. All of the static files (style sheets, pages and images) are loading fine -
how to make the session lifetime counted from the start of the page load, checked every minute and not disrupted by post request?
session life settings SESSION_COOKIE_AGE=120 (2 minutes) now a question, at the first rendering of the page of the template confirm_email.html the form of code input from 6 fields is loaded, if you do not enter the code (inactivity) and wait, then every minute will be checked to send a get request from the script check_session.js every minute in the view CheckSession and it will give json response back and 30 seconds before the end of session life will trigger the script timer.js and after the end of 2 minutes the user will be redirected to the main page - everything is fine here!!!!. And if at the first rendering of the confirm_email.html template page (for example, the page loaded at 18:00:00) the form of code input from 6 fields is loaded, and suppose you enter an incorrect code after 30 seconds (at 18:00:30), then a post request is sent to the ConfirmEmail view and the check_session script. js will send a request to the CheckSession view from this post request time, i.e. the script will send a request at 18:01:30, i.e. a minute from the post request, but not from the time the page loaded at 18:00:00. Where it is …