Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can we use Django-cacheops in Django 3+ versions?
I am updating the django project form 1.3 to Django 3.2 I am trying to use Django-cacheops as I already built in my old version project, but its give me the error of File "C:\Users\mahad\projects\Allay\env\lib\site-packages\cacheops\simple.py", line 9, in <module> from django.utils.hashcompat import md5_constructor ModuleNotFoundError: No module named 'django.utils.hashcompat' Is this library is deprecated or I can use it? If yes then give me the way to do it or kindly refer some extra plugin for saving the cache with redis -
authentication failed when I use postgresql with django
OS: AWS linux django3.2.7 python 3.7 psql (PostgreSQL) 13.3 I am trying to use postgresql with django. I changed setting.py like below: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbname', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '5432', } } I created a password for postgre and I successfully logged in as this user. $ sudo su - postgres Last failed login: Sun Sep 26 18:21:57 JST 2021 on pts/4 There were 6 failed login attempts since the last successful login. -bash-4.2$ psql Password for user postgres: psql (13.3) Type "help" for help. postgres=# However, when I tried to execute this: $ python3 manage.py runserver I got this error: django.db.utils.OperationalError: FATAL: Ident authentication failed for user "postgres" I am not sure what is the problem and would like to know how I can fix this. Thank you in advance! -
Unable to start Django server inside docker container
I am unable to connect to the Django server on a docker container. I am trying to use 0.0.0.0:8000 to connect and I used "docker-compose up" to create a container. docker-compose.yaml version: '3.7' services: server: build: context: ./PriceAlertWeb dockerfile: Dockerfile image: serverimg3 container_name: servercon3 ports: - 8000:8000 Dockerfile FROM python:3.7 WORKDIR /ServerCode/ COPY . /ServerCode/ RUN pip install -r req.txt CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] I am able to create a container successfully. But when I try accessing it with "http://127.0.0.1:8000/userDetails/", I'm unable to see my content. Please note that when I try running "python manage.py runserver 0.0.0.0:8000" on my local, my application functions as expected. (Screenshots below) -
How to add geocoder to django-leaflet's (admin) form widget
I tried to add leaflet-contrtol-geocoder(https://github.com/perliedman/leaflet-control-geocoder) to django-leaflet's widget. Added below script, and I can see geocoder icon added and function correct. window.addEventListener("map:init", function (event) { var map = event.detail.map; // var options = { url: "http://localhost:3100/v1", expanded: false, bounds: false, sources: 'whosonfirst' }; geocontrol = L.control.geocoder(options); geocontrol.addTo(map); }); But this way it won't update associated textarea for geom field. I tried to modify leaflet-control-geocoder to fire L.Draw.Event.CREATED instead of just addLayer, but leaflet.forms.js use a flag to ignore events of other draw controls: // We use a flag to ignore events of other draw controls for (var toolbar in drawControl._toolbars) { drawControl._toolbars[toolbar].on('enable disable', function (e) { this._acceptDrawEvents = e.type === 'enable'; }, this); } Any idea how this can be done? I can't find a place to set _acceptDrawEvents for geocoder control. Thanks! -
How to store django model's logs individually in another database?
I've been using auditlogs, and models_logging recently. The issue with them is that they store all the logs in a single table in my mongodb. I want to store the logs individually. Is there any way or any package that offers such features? -
Use React CDN and Django on same server and port
I'm using django for the backend and render the webUI from the django templates. Now I wanted to dive into React and migrate to a client side rendered UI. My idea is to setup django to only load the first (index.html) page where all the react cdn scripts (react, reactDOM, react-router, prop-types, axios, ...) and component scripts are loaded and their state will then be handled on the client machine. My idea was to reduce the load on the application server due to the fact that the app server will have to handle a lot of concurrent users, a lot of api hits, input-ouput operations, high CPU consumption, handle multiple tcp connections, have high RAM usage which will accumulated take up a lot of resources. For that reason I didn't want to build a react app and run it on the same machine on a dedicated port, because it will run next to the django application and take up RAM resources. But the problem with the cdn variant of react is that I don't know how to use all the other modules that are pre-delivered when creating a react app create-react-app: prop-types, axios, and many more. Do I have to … -
Extracting a fied value from JsonResponse in Django and pass it to Ajax Jquery
I'm creating a dropdown list select with ajax and Jquery in Django The expected behavior is when I choose the first select, the ajax will fill the second one This is what I have for while: models.py class MaintenanceEquipment(models.Model): equip_id = models.CharField(max_length=30, auto_created=False, primary_key=True) line_nm = models.CharField(max_length=20, blank=True, null = True) sequence = models.CharField(max_length=30, blank=True, null = True) equip_model = models.CharField(max_length=30, blank=True, null = True) def __str__(self): return self.equip_id views.py: def maintenanceIssueView(request): equipment_list = MaintenanceEquipment.objects.all() context = {'equipment_list':equipment_list} return render(request, 'maintenance/maintenanceIssue.html', context) def load_equipment(request): from django.core import serializers if request.method == 'GET': line_nm = request.GET.get('line_nm') equipment = MaintenanceEquipment.objects.filter(line_nm=line_nm) instances = serializers.serialize('json', equipment) print(instances) return JsonResponse({ "status_code": 200, "instances": instances, }, safe=False) urls.py: urlpatterns = [ path('maintenanceIssueView/', views.maintenanceIssueView, name="maintenanceIssueView"), path('ajax/load_equipment/', views.load_equipment, name="ajax_load_equipment"), ] maintenanceIssue.html: <form method="POST" id="maintenanceForm" data-equipment-url="{% url 'ajax_load_equipment' %}" novalidate> {% csrf_token %} <div style="text-align:left;" class="container-fluid"> <div style="text-align:left;" class="form-row"> <div class="form-group col-md-6"> <label for="line_nm" style="font-size:medium;">Line</label> <select class="form-control" id="line_nm" name="line_nm" > {% for instance in equipment_list %} <option id="{{ instance.line_nm }}" value="{{ instance.line_nm }}">{{ instance.line_nm }}</option> {% endfor %} </select> </div> <div class="form-group col-md-6"> <label for="sequence" style="font-size:medium;">Machine</label> <select class="form-control" id="sequence" name="sequence"></select> </div> </div> </div> </form> <script> $("#line_nm").change(function () { var url = $("#maintenanceForm").attr("data-equipment-url"); var line_nm = $(this).val(); $.ajax({ url: url, … -
Pycharm / Django defer Oracle Database connection
I have a Django project that connects to an Oracle database - implemented in PyCharm. I would like the app to monitor the connection and display a status as to whether the database is up or down. I stopped the listener to simulate an error. However, when I start the PyCharm server to test the functionality, the app immediately attempts a database connection and fails. Is it possible to defer the database connection until I can command one within the app? Here is the error traceback on server startup: C:\Users\steve\PycharmProjects\Tools\venv\Scripts\python.exe C:/Users/steve/PycharmProjects/Tools/Tools/manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\steve\PycharmProjects\Tools\venv\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\steve\PycharmProjects\Tools\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\steve\PycharmProjects\Tools\venv\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\steve\PycharmProjects\Tools\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\steve\PycharmProjects\Tools\venv\lib\site-packages\django\db\backends\oracle\base.py", line 229, in get_new_connection return Database.connect( cx_Oracle.DatabaseError: ORA-12541: TNS:no listener The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\steve\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\steve\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\steve\PycharmProjects\Tools\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper … -
Django dropdown list - change to None during edit
I have a model with month choice field (from January to December). When I want to edit model by generic UpdateView, field with month is shown by '----', but I don't want to change the month. Is there a proper way to display in form month that was decalared when creating object? In model: months_choice =( "1": "January", "2": "February", and so on ) date = models.CharField(max_length=3, choices=months_choice) Rendered form shows this: [I want display here the month that was declared earlier] [1]: https://i.stack.imgur.com/cUys8.png -
How to calculate average of difference of date time field in Django models and send it to rest API?
I have two models Gigs and Orders. and want to calculate the average of diffrence between order_start_time and order_completed_time of every gig. check my code its giving following error Cannot resolve keyword 'orders' into field. Choices are: category, category_id, details, gig, id, images, price, reviews, seller, seller_id, title please help! Models.py (in seller app) class Gigs(models.Model): title = models.CharField(max_length=255) category = models.ForeignKey(Categories , on_delete=models.CASCADE) images = models.ImageField(blank=True, null = True, upload_to= upload_path) price = models.DecimalField(max_digits=6, decimal_places=2) details = models.TextField() seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE) @property def average_completionTime(self): if self._average_completionTime is not None: return self._average_completionTime return self.gig.aggregate(Avg('order_completed_time'-'order_start_time')) Models.py(in buyer app) focus on item field from seller.models import Gigs class Orders(models.Model): buyer = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='buyer_id') seller = models.ForeignKey(User,default=None, on_delete=models.CASCADE,related_name='seller_id') item = models.ForeignKey(Gigs,default=None, on_delete=models.CASCADE,related_name='gig') payment_method= models.CharField(max_length=10) address = models.CharField(max_length=255) mobile = models.CharField(max_length=13,default=None) quantity = models.SmallIntegerField(default=1) status = models.CharField(max_length=13,default='new order') order_start_time = models.DateTimeField(default=None) order_completed_time = models.DateTimeField(default=None) created_at = models.DateTimeField(auto_now_add=True) Views.py class RetrieveGigsAPI(GenericAPIView, RetrieveModelMixin): def get_queryset(self): return Gigs.objects.all().annotate(_average_rating=Avg('orders__time')) serializer_class = GigsSerializerWithAvgTime permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.retrieve(request, *args, **kwargs) Serializers.py class GigsSerializerWithAvgTime(serializers.ModelSerializer): average_completionTime = serializers.SerializerMethodField() def get_average_completionTime(self, obj): return obj.average_completionTime class Meta: model = Gigs fields = ['id','title','category','price','details','seller','images','average_completionTime'] -
Move down the webpage upon form button click
I'm creating a webpage with Django, I've got a submit button on a form that once it gets clicked some data will be sent to my server. I could direct the webpage to a new URL once the form is submitted but instead I'd like to stay on the same webpage and simply have the screen focus move down to a new section, is this possible? I've seen a couple of examples of how to scroll down with href but the user won't be clicking an href link, they'll be clicking a submit button where scrolling down is just a secondary action to the button click if that makes sense. -
Is there any way to look up cache by contains and delete cache from MemCached in Django?
I have been working on a Django web app and initially I'm used database level cache. But now I need to change on Memcached. I would like to know about clearing cache from the Memcached. I'm using Python 3.8.10 and Django==3.1. We can clear cache in database level by filter by contains. So like, Is there any way to loop up cache using contains and delete from Memcached? What is the best way to achieve this? -
How to display database content without parsing an ID to the urls in django
I'm still a beginner in Django and building a management system, I wish to display content from the database using a for loop from 2 tables(GoCustomerRegisration and GoCustomerStatus). But unfortunately, when I iterate over one table the other table brings me only the last element of that table. What I really wish to do is iterate over both tables at once and each element should correspond to it on the other table. Check out my code below: something.html {% for item in detail %} <tr> <td> <a class="text-black text-decoration-none" href="{{ item.photo.url }}"> <img class="rounded-circle me-2" style="object-fit: contain; background-color:#91debb; border:1px solid palegreen;" alt="" width="30" height="30" src="{{ item.photo.url }}"></a> </td> <td> <a class="text-black lg:hover:text-blue-400 text-decoration-none" href="{% url 'customer_detail' pk=item.id %}">{{ item.name }}</a> </td> <td class="text-capitalize">{{ item.type }}</td> <td>{{ item.destination }}</td> <td>{{ item.age }}</td> <td>{{ item.time_of_submission }}</td> <td> <span>{{ hello.value }}%</span> <div class="col"> <div class="progress progress-sm"> <div class="progress-bar progress-bar-striped bg-success" aria-valuenow="{{ hello.value }}" aria-valuemin="0" aria-valuemax="100" style="width: {{ h.value }}%;"><span class="visually-hidden"></span> </div> </div> </div> </td> {% endfor %} my views.py @login_required def preview(request): global hello detail = GoCustomerRegistration.objects.all() next_event = Event.objects.last() for i in range(1, (len(detail))+1): print(i) hello = GoCustomerStatus.objects.get(name_id=i) print(hello) context = { 'detail': detail, 'event': next_event, 'hello': hello, } return render(request, 'customers_preview.html', … -
Facebook: Graph API not able to get lead generation forms created for particular page
https://graph.facebook.com/v12.0/page-id/leadgen_forms?token=somethings not able to get data of lead generation forms created for this page anyone any comment meanwhile i am making API on python -
Get read topic count for followed category in a blog
I have a Django blog.. With a Language and SubTopic model. Every subtopic belongs to a language.. Users can follow a language and they'll only topics for that language #follow language, views.py class followLanguageView(TemplateView): template_name = 'lessons/lessons.html' def get(self, request, *args, **kwargs): language_id = kwargs['pk'] language = Language.objects.filter(id=language_id).first() skill_id = kwargs['pk'] skill = Skill.objects.filter(skill_follow__user=self.request.user).first() if language: if request.GET.get('unfollow'): LanguageFollow.objects.filter(language=language, user=self.request.user).delete() SkillFollow.objects.filter(skill=skill, user=self.request.user).delete() elif LanguageFollow.objects.filter(language__language_follow__user=self.request.user).exists(): LanguageFollow.objects.filter(language=language, user=self.request.user).delete() else: LanguageFollow.objects.get_or_create(language=language, user=self.request.user) return redirect(reverse('lessons')) I have a manytomanyfield in subtopic . Where users can mark a topic as read.. I want to get the total count of topics read for the specific category the user is following #read count, views.py @login_required def dashboard(request): language_follow = LanguageFollow.objects.filter(user=request.user) read = LanguageFollow.objects.filter(language__language_follow__user=request.user) read_count = SubTopic.objects.filter(read=read).count() total_topic = SubTopic.objects.filter(language__language_follow__user=request.user).count() percent = topicPercent(read_count, total_topic) return render(request, 'auth_user/userDashboard.html', { "read_count": read_count, "total_topic": total_topic, 'language_follow': language_follow, "percent": percent, }) #models.py class SubTopic(models.Model): title = models.CharField(_("title"), max_length=150) main_title = RichTextUploadingField(max_length=50000, null=True, blank=True, default=None) main_explanations = RichTextUploadingField(null=True, blank=True, default=None) language = models.ForeignKey(Language, verbose_name="topic_language", on_delete=models.CASCADE, related_name='follow_language', default=None) topic = models.ForeignKey(Topic, verbose_name=("topic"), on_delete=models.CASCADE, default=None) published = models.DateField(auto_now_add=True, blank=True, null=True) slug = models.SlugField(unique=True, max_length=50000, blank=True, null=True) read = models.ManyToManyField(User, related_name='read', blank=True) def __str__(self): return self.title def all_user(self): return list(self.subtopic_follow.values_list('user', flat=True)) def save(self, *args, **kwargs): if … -
How to disable add permission in the Django's admin page when the choices drop down field doesn't contain any data?
I have a model which has a template_name field which is shown as drop down in django admin. template_id = models.CharField(max_length=255, choices=template_data, unique=True) The template_data is getting populated from some other script. The format of template_data is : (('123', 'car'), ('456', 'bike')) This works fine when template_data has some values but when the template_data is an empty tuple, then I want to disable any add permission on admin page. Currently when the redis is off, the add button is disabled but how to do the same when the template_data is an empty tuple? Diasbled add permission when redis is off: def has_add_permission(self, request, obj=None): is_redis = RedisCache.is_redis_available() if is_redis is not True: return False return True RedisCache.is_redis_available(): Redis check is happening by calling is_redis_available func of RadisCache class. -
Django Delete a many to many field
I have 2 models User which is Django's auth_user, and HostCourse which has a many to many relationship with User class HostCourse(TimeStamped, models.Model): created_by = models.ManyToManyField(User, blank=True) ... When I delete some data from HostCourse, it throws the following error: ERROR: update or delete on table "courses_hostcourse" violates foreign key constraint "courses_hostcourse_c_hostcourse_id_ec1070c3_fk_courses_h" on table "courses_hostcourse_created_by" If I'll include on_delete=models.CASCASE, will it also delete the users of the respective HostCourse? If yes, how can I find a workaround, so that it deletes courses and not users? -
Annotate count of models by geometric intersection
Problem Assuming these models: class ModelA(models.Model): geometry = models.PolygonField() class ModelB(models.Model): geometry = models.PolygonField() How can I annotate to a ModelA queryset the count of intersecting ModelB instances using purely the ORM? Each ModelA's geometry should be intersected with the ModelBs' geometries and intersecting ModelBs counted. Eventually I would like to order_by the count of ModelB instances and find the ModelA instances that have the highest count of intersecting ModelB instances. What I have tried ModelA.objects.annotate( n_modelb=Count( ModelB.objects.filter(geometry__intersects=OuterRef("geometry")) ), ) --> ProgrammingError: subquery must return only one column ModelA.objects.annotate( n_modelbSubquery( ModelB.objects.filter(geometry__intersects=OuterRef("geometry")).count() ), ) --> ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. ModelA.objects.annotate( modelb_ids=Subquery( ModelB.objects.filter(geometry__intersects=OuterRef("geometry")).values( "id" ), ), n_modelb=Count("modelb_ids"), ) --> CardinalityViolation: more than one row returned by a subquery used as an expression Related questions I think I am basically stuck at this comment to this answer: https://stackoverflow.com/a/46154553/9778755. This solution works when the models have a relationship. If you're trying to count on models without a relationship, this does not work. – Danielle MadeleyMar 17 '20 at 6:36 -
docker doesn't see heroku environment variables
I have django/react/postgres/docker app. When I try to push it to heroku it doesn't see environment variables from heroku config vars tab during build phase Is there a way to get heroku environment variables inside of the docker container? On heroku I attached Heroku Postgres addon, but since my env variables are hidden during build phase I'm getting an error: django.db.utils.OperationalError: could not connect to server Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Dockerfile.prod FROM python:3.8 RUN apt-get install -y curl \ && curl -sL https://deb.nodesource.com/setup_12.x | bash - \ && apt-get install -y nodejs WORKDIR /app/backend COPY ./backend/Pipfile* /app/backend/ RUN pip install pipenv && pipenv install --system WORKDIR /app/frontend COPY ./frontend/package*.json /app/frontend/ RUN npm install COPY . /app/ RUN npm run build WORKDIR /app/frontend/build RUN mkdir root && find . -type f -exec cp {} root \; RUN mkdir /app/backend/staticfiles WORKDIR /app ENV DJANGO_SETTINGS_MODULE=config.settings.prod RUN python backend/manage.py collectstatic --noinput EXPOSE $PORT RUN ["python", "backend/manage.py", "migrate", "--no-input"] CMD [ "python", "backend/manage.py", "runserver", "0.0.0.0", $PORT] settings.py ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': env.str("DB_NAME", default="postgres"), 'USER': env.str("DB_USER", default="postgres"), 'PASSWORD': env.str("DB_PASS", default="postgres"), 'HOST': env.str("DB_HOST", default="localhost"), 'PORT': env.decimal("DB_PORT", default=5432) } } -
Django export to csv outputting just one row of data
I have 4 rows of data in a simple database and I would like to output it to a .csv. I have setup Django csv and everything seems to be working ok but I am only getting the first row. Can anyone tell me what is wrong with the code I have used as I obviously need all 4 rows. models.py class account(models.Model): Price = models.DecimalField('price', max_length=20, blank=True, null=True, max_digits=10, decimal_places=2) User = models.CharField('user', max_length=120, blank=True, null=True,) Account_Number = models.CharField('account Number', max_length=20, blank=True, null=True,) Date = models.DateField(default=now) def __str__(self): return str(self.User) views.py def stage(request): slist = account.objects.all() return render(request, 'stage.html', {'slist': slist}) def export_csv(request): response=HttpResponse(content_type='text/csv') writer = csv.writer(response) writer.writerow(['User', 'Account Number', 'Price', 'Date']) for file in account.objects.all().values_list('User', 'Account_Number', 'Price', 'Date'): writer.writerow(file) response['Content-Disposition'] = 'attachment; filename="Expenses.csv"' return response urls.py urlpatterns = [ path('', views.home, name="home"), path('stage/', views.stage, name='stage'), path('export_csv', views.export_csv, name='exportcsv') ] html <table id="dataTable" class="table"> <thead> <tr> <th>User</th> <th>Account Number</th> <th>Price</th> <th>Date</th> </tr> </thead> <tbody> {% for item in slist%} <tr> <td>{{item.User}}</td> <td>{{item.Price}}</td> <td>{{item.Account_Number}}</td> <td>{{item.Date}}</td> </tr> {% endfor %} </tbody> </table> <div><a href="{% url 'exportcsv' %}"> <button type="button" class="button">Export to CSV</button></a></div> -
Webmin alternative for Django, ubuntu server [closed]
A while ago i setup my django website in production by webmin. Unfortunately the django script in webmin became reserved for pro version. Do you know alternative to webmin where i can setup a django server (apache/nginx/psql) easly ? My server is on Ubuntu LTS. Thank for your time. -
how to display manytomanyfields in django admin
I add a likes field in my item models and would like to display all likes against each item in the admin panel. How I can do that currently is what my code looks like. I am getting this error:'User' object has no attribute 'likes' Model: likes = models.ManyToManyField(User, related_name='blog_posts') Admin.py class ItemAdmin(admin.ModelAdmin): list_display = ('title','author','item_category','date','get_products') list_filter = ('item_category',) def get_products(self, obj): return "\n".join([p.likes for p in obj.likes.all()]) -
Django swappable model foreign keys
Suppose I have a reusable app, that defines a model Person and a model Invite. A Person has a OneToOne field to AUTH_USER_MODEL and defines some basic fields (such as birthday). It is a swappable model, so that a project which uses this app can easily add other fields (such as gender, etc.) In my reusable app, I define a setting that provides the swapping model (otherwise, a default one will be used, exactly as django.contrib.auth does it. The Invite model has a OneToOneField to the swappable Person model and an email field. (I think, it's quite clear what this model is for). The model itself is swappable as well, but I don't think that this makes any difference for the kind of problem I am facing. reusable app models: class AbstractPerson(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name='person') birthdate = models.DateField() class Meta: abstract = True class Person(AbstractPerson): class Meta(AbstractPerson.Meta): swappable = 'REUSABLEAPP_PERSON_MODEL' class AbstractInvite(models.Model): email = models.EmailField() person = models.OneToOneField(settings.REUSABLEAPP_PERSON_MODEL, on_delete=models.CASCADE, null=False, related_name='+') class Meta: abstract = True class Invite(AbstractInvite): class Meta(AbstractInvite.Meta): swappable = 'REUSABLEAPP_INVITE_MODEL' If I create the initial migration for my reusable app (using a dummy project and not swapping out my models), I get the … -
In django i want to change the date from views
I want to update the date from the backend views in django how can i did that here are my views where i want to do this def refresh_dashboard(request): date = datetime.datetime.now().strftime ("%Y%m%d") m = datetime.date.today() print(f"the date is {m}") customer = Customer.objects.all() for i in customer: # print(i.eligible) period = i.next_payment.strftime("%Y%m%d") if period <= date and i.eligible == True: x = Bill.objects.create(name = i.name,status ="unpaid",price = i.recuring_amount,generate_date = date) x.save() obj = i # obj.next_payment.strftime("%Y%(m+1)%d") obj.eligible = False obj.save() # print(f"the date is {date} and the obtain from the customer is {period}") # print(f"this customer {i.name} bill need to be generated") # print(f"the date is {datetime.datetime.now()}") return redirect('/') -
Can I retrieve the FCM token using Django?
I'm learning push notifications in PWA app using Django. Most of the tutorials seem to suggest retrieving the FCM token in the front end. There are some JS libraries to do this, but I was wondering if that is considered the best practice or should I retrieve the token in the back end? I'm using fcm-django and need to store the token as registration_id in my database.