Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery TaskResult inserted after finishing task
I have some strange behavior with the Celery task queue-module in the Django Framework in Python. My code works when all variables are correctly set up. But implementing some validation code that is separate from Celery seems to interfere with Celery. I'll explain what I am programming first. My complete code is at the bottom of this post. Dashboard users can execute tasks which are sent through Redis to a Celery-worker. This works. Next to that I also successfully implemented the Celery Progress-backend, and with it's ProgressRecorder I can now set the progress. Some jQuery, Ajax, html and css enable a fancy progress bar in the dashboard. I now combined this ProgressRecorder together with some custom code in a class. This works as well. With the custom code you can specify which Python function definitions should log progress. My code is built modular so function definitions are re-used on many levels and not every function should log in every task. Therefore the developer should specify which functions should log progress. The user does this with the 'display_progress_of_defs'-key when initiating the class: progress_recorder = ProgressRecorder(self) progress_logging = LogTaskProgressV3(task_id=task_id, app_id=app_id, progress_recorder=progress_recorder, total_steps=total_steps, display_progress_of_defs=["function_def_a", "function_def_c"]) In the class I added validation to confirm … -
Doctor appointment booking system in Django
I am trying to create doctor appointment booking system in Django. I have two models: Doctor and Patient, with personal details. I am looking for the way how to connect both, using specific time-slots/date for appointments. Doctors may be available in a different time-slots or days. For example: Doctor A is available from Monday to Friday, 8:00 - 16:00. I need to book Patient A for 30-minutes appointment at 10:00 and Patient B at 10:30. class Doctor(models.Model): first_name = models.CharField(max_length=30, verbose_name="First name") second_name = models.CharField(max_length=30, verbose_name="Second name") doctor_type = models.ForeignKey(Specialisation, on_delete=models.CASCADE, verbose_name='Specialisation') doctor_status = models.CharField(max_length=30, choices=status_choices, default='Non-Active', verbose_name='Doctor status') image = models.ImageField(upload_to='photos', blank=True, verbose_name='Photo') def __str__(self): return self.second_name + " " + self.first_name class Patient(models.Model): first_name = models.CharField(max_length=30, verbose_name="First name") second_name = models.CharField(max_length=30, verbose_name="Second name") contact_details = models.CharField(max_length=30, verbose_name="Contact details") postcode = models.CharField(max_length=3, verbose_name="PostCode") patient_status = models.CharField(max_length=30, choices=status_choices, verbose_name='Patient status') def __str__(self): return self.second_name + " " + self.first_name Thanks! -
How does React and Django actually work together
Hello I have now just started with learning React however I am getting a bit confused how does this two i.e Django and React actually get to work with one another. With routing from page to page is this handled by Django or React or this is a choice that one can take self? I am also wondering when dealing with normal Django templates same applies when using react or what? I have been searching where I can get a full blog/write-up where I can learn how to integrate the two and the best practices to this two but could not seem to find the one that is answering me or I just did not understand because I am a Beginner in this domain. Will this be best practice(This is the idea that I had on how people use this two frameworks) the idea that I had is one just builds a backend api that which then React can use however the rest such as page routing is all handled by React is this true or best practise or the is a better way in which people handle this. Can you please give me a detailed explanation on how this … -
show only what admin add to DB django admin
Help please. There are several admins who have different rights. There is a model where they can add a product. I want to make sure that every administrator sees what they have added themselves. In the database table there is a row сreated_by. For example, I add my books to the database and another administrator adds his books. each administrator have to sees what he added. Thow do I do this? model.py class MyBooks(models.Model): book = models.ForeignKey(Books, on_delete=models.CASCADE, blank=True, null=True, default=None) fomil = models.CharField('Фомил',max_length=100, blank=True, null=True, default=None) name= models.CharField('Ном',max_length=100, blank=True, null=True, default=None) is_active = models.BooleanField('Ичозати таблиг (фаъол)',default=True) created = models.DateTimeField('Санади сохташуда', auto_now_add=True, auto_now=False, ) updated = models.DateTimeField('Санади азнавшуда',auto_now_add=False, auto_now=True) admin.py class BooksAdmin(admin.ModelAdmin): list_display = [field.name for field in MyBooks._meta.fields] def save_model(self, request, obj, form, change): if not obj.created_by: obj.created_by = request.user obj.save() class Meta: model = MyBooks -
How to set a field will be change by if statement in models for Django?
I have a field in models that the True/False value will be affect by other field. May I know how to set it? models.py: class Product(models.Model): storage_amount = models.PositiveIntegerField() if storage_amount == 0 or None: out_of_storage_or_not = models.BooleanField(default=True) else: out_of_storage_or_not = models.BooleanField(default=False) -
djongo as second db engine
I want to add mongodb as second database on my django project. I use djongo lib. When i run the tests with pytest, during database creation, first migrations are performed for postgresql, then all migrations want to be applied to the mongo (but i deny it by DATABASE_ROUTERS). How to deny apply migrations to mongodb but allow to postgres? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env('POSTGRES_NAME'), 'USER': env('POSTGRES_USER'), 'PASSWORD': env('POSTGRES_PASS'), 'HOST': 'postgres', 'PORT': '5432' }, 'mongo': { 'ENGINE': 'djongo', 'NAME': 'my_project', 'CLIENT': { 'host': 'mongo', } } } class SimpleRouter: @staticmethod def allow_migrate(db, app_label, **kwargs): if db == 'mongo': return False else: return True DATABASE_ROUTERS = (SimpleRouter,) pytest output: Creating test database for alias 'mongo' ('test_my_project')... backend | test setup failed self = <djongo.cursor.Cursor object at 0x7faf305a0c10> sql = 'INSERT INTO "django_migrations" ("app", "name", "applied") VALUES (%s, %s, %s)' params = ['contenttypes', '0001_initial', datetime.datetime(2020, 7, 29, 15, 14, 35, 55164)] -
Why aren't changes to my css visible in HTML page (django)?
I have a weird Problem with my django project. I have added a static folder in my app called home. Within the static folder I made another folder called home. The full path for my .css files is: C:/Users/myuser/app/home/static/home/new.css I have successfully loaded this .css file and the styles I added are visible when viewing the HTML page. However I made some alterations to that new.css file and saved it. However the HTML page only displays the css from the original .css file. Is this normal? Can anyone think of a reason this might be happening? Thanks in advance :) -
AttributeError from Django model inheriting an abstract base model
I'm trying to put together a simple little app that allows users to keep track of their own pokemon. Each pokemon has 1-2 different 'types' (e.g. fire, water, etc.), so I've added in a clean function to limit the maximum number of types the user can select. However, when trying to add a pokemon I am given the following error: AttributeError at /admin/pokollector/custompokemon/add/ 'CustomPokemon' object has no attribute 'poke_types' I'm assuming this has something to do with the poke_types variable not being properly inherited, but I have no idea why that would be. Here is the code from my models.py file: from django.db import models from django.core.validators import MinValueValidator as min, MaxValueValidator as max from django.core.exceptions import ValidationError class PokeType(models.Model): poke_type = models.CharField(max_length=15) def __str__(self): return self.poke_type #Current generation of games for gen_added field gen = 8 class Pokemon(models.Model): poke_name = models.CharField(max_length=30) poke_type = models.ManyToManyField(PokeType) evolves_from = False evolves_into = False gen_added = models.PositiveIntegerField(validators=[min(1), max(gen)]) def clean(self): #Allow max of 2 poke_types to be selected if len(self.poke_types > 2): raise ValidationError('A Pokemon has a maximum of two types.') class Meta: verbose_name_plural = 'Pokemon' abstract = True class CustomPokemon(Pokemon): name = models.CharField(max_length=30) level = models.PositiveIntegerField(blank=True, null=True) def __str__(self): return self.name -
Can I use Signal receiver within a class
I have a signal like this: virtual_daily_created = django.dispatch.Signal(providing_args=['min_date', 'max_date', 'train_id']) Calling it from a view like this: signal = virtual_daily_created.send_robust(self.__class__, min_date=start_ts, max_date=end_ts, train_id=train_id) and the receiver is in a class defined like this: class BigQueryData: def __init__(self): some_code def set_query(self, table: bigquery.TableReference, train_id: str, min_date: datetime, max_date: datetime,**kwargs) -> str: do_thing def set_table(self, type: str) -> bigquery.TableReference: do_thing @receiver(virtual_daily_created) def get_gga_data(self, min_date: datetime, max_date: datetime, train_id: str, **kwargs): do_thing Finally in my app containing the BigQueryData class, in a app.py file I have: from django.apps import AppConfig from django.dispatch import receiver class ShiftsConfig(AppConfig): name = 'shifts' def ready(self): from api.v1.virtual_daily_report import VirtualDailyReportList from reports.signals import virtual_daily_created virtual_daily_created.connect(receiver, sender=VirtualDailyReportList) Thing is when a signal is received I got this error: get_gga_data() missing 1 required positional argument: 'self' So I tried to change my signal like this: virtual_daily_created = django.dispatch.Signal(providing_args=['self', 'min_date', 'max_date', 'train_id']) And to Call it like this: signal = virtual_daily_created.send_robust(self.__class__, self=BigQueryData(), min_date=start_ts, max_date=end_ts, train_id=train_id) But then when I receive a signal I get this error: send_robust() got multiple values for argument 'self' Is it even possible to receive a signal from a method with self as first arg ? Thank you :) -
How do I render DJango-Rest-Framework apis to templates like in Native Django
I have successfully made the apis using Django Rest's views and serializer. Due to some issues I now want to render templates and run the project using native Django. Now how do I migrate the modelviewsets and serializer to render templates and work like native Django does. Although apis are working I want full custom template rendering. This is how my API looks like= [ { "id": 6, "created_at": "2020-07-17T10:11:34.154037Z", "updated_at": "2020-07-27T14:36:44.319520Z", "cartitem": [ { "id": 17, "item": { "id": 11, "price": "500.00", "quantity": 22, "size": 1, "color": 2 }, "quantity": 5 } ], "number_of_items": 5, "total": "2500.00" } ] This is my cart API for the e-commerce website I am working on. Note that I have written viewsets and serializer, everything is correctly working, I want to render this. I cant find enough resources how to. -
Celery on Heroku doesn't shutdown properly when I automatically deploy from github
The problem I am having is surrounding the restarting process of Celery during an app version release in Heroku. Every time I push code to my production GitHub it does this: 2020-07-29T15:09:13.725295+00:00 app[worker.1]: File "<frozen importlib._bootstrap_external>", line 846, in source_to_code 2020-07-29T15:09:13.725295+00:00 app[worker.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2020-07-29T15:09:13.725295+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.8/site-packages/celery/backends/redis.py", line 22 2020-07-29T15:09:13.725296+00:00 app[worker.1]: from . import async, base 2020-07-29T15:09:13.725296+00:00 app[worker.1]: ^ 2020-07-29T15:09:13.725296+00:00 app[worker.1]: SyntaxError: invalid syntax 2020-07-29T15:09:14.451767+00:00 heroku[worker.1]: Process exited with status 1 2020-07-29T15:09:14.516084+00:00 heroku[worker.1]: State changed from up to crashed Then I have to manually push code again and the celery works just fine. This happens every single time. Is there a way to prevent the celery app from trying to start up before the other app is done shutting down? -
set custom basePath in drf-yasg
I am using drf-yasg to document my APIs and I have the following setup, from django.urls import path from drf_yasg.views import get_schema_view public_schema_view = get_schema_view(..., urlconf='public_apis.urls') private_schema_view = get_schema_view(..., urlconf='private_apis.urls') urlpatterns = [ path('public/', public_schema_view.with_ui('swagger', cache_timeout=0), name='schema-public'), path('private/', private_schema_view.with_ui('swagger', cache_timeout=0), name='schema-private'), ] Note: The public_schema_view and private_schema_view are renedered two different set of URLs from the modules public_apis.urls and private_apis.urls respectively. Here I want to have two basePaths, /api/v1/public/ for public_schema_view and /api/v1/private/ for private_schema_view So, the question is, how can I set multiple custom basePath in drf-yasg ? -
ImportError on python setup.py develop
This is my directory structure: api-models - api_models - __init__.py - models.py - migrations - __init__.py - 0001_initial.py - setup.py This is my setup.py: from setuptools import find_packages, setup setup( name='api_models', version='0.1.1', packages=['api_models'], ) In my project, this is in my settings.py: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'waffle', 'simple_history', 'rest_framework', 'rest_framework.authtoken', 'django_fsm', 'django_celery_results', 'django_celery_beat', 'schedule', 'core', 'ops', 'cdg', 'workflow', 'api_app', 'assignment_classifier', 'dictionary', 'knowledge_base', 'scheduler', 'memoize', # function caching 'api_models', ) Running "python setup.py install" appears to work as desired. However, running "python setup.py develop" causes my project to return ImportError: No module named 'api' I can't find anywhere in my code that references "api" (rather than "api-models" or "api_models"). What am I missing? I tried changing the packages line in setup to instead read "packages=find_packages(),", but that didn't seem to make any difference. -
Django schedule task
I just need advise what is the best way to do it to schedule a task. this is my models: class Jobs(models.Model): name= models.CharField(max_length=100) expire =models.DateField(auto_now=False, auto_now_add=False, blank= True, null= True) I want to delete a job after 15 days once a job expires. I can check expire and delete it problematically but I am very much confused to choose a scheduler. not getting what is the best way to schedule it. I heard of celery, threading and a lots of things about it scheduling. I need a expert advise, what is the best way to do this kind of task? is celery good option for me or there is any other best way to do it? Fogive me please if i ask something amateur. -
Deploying django to AWS Lambda connecting to RDS MySQL, showing error: NameError: name '_mysql' is not defined
Deploying django to AWS Lambda using zappa connecting to RDS MySQL, not able to deploy showing error: NameError: name '_mysql' is not defined: zappa update dev gives error: Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code AWS Cloudwatch logs: name '_mysql' is not defined: NameError Traceback (most recent call last): File "/var/task/handler.py", line 609, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 240, in lambda_handler handler = cls() File "/var/task/handler.py", line 146, in init wsgi_app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS) File "/var/task/zappa/ext/django_zappa.py", line 20, in get_django_wsgi return get_wsgi_application() File "/var/task/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/var/task/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/var/task/django/apps/registry.py", line 114, in populate app_config.import_models() File "/var/task/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/var/lang/lib/python3.6/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "/var/task/django/contrib/auth/models.py", line 2, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/var/task/django/contrib/auth/base_user.py", line 47, in class AbstractBaseUser(models.Model): File "/var/task/django/db/models/base.py", line 121, in new new_class.add_to_class('_meta', Options(meta, app_label)) File "/var/task/django/db/models/base.py", … -
Reverse for 'add_to_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/add/(?P<item_id>[^/]+)/$']
I cant seem to add products/plans to my cart page im getting this error. This is my views def add_to_cart(request, item_id): """ Add plan to shopping cart """ cart = request.session.get('cart', {}) cart[item_id] = cart.get(item_id, 1) request.session['cart'] = cart return redirect(reverse('plans')) This is my plans.html - this is a button where im trying to a plan to my cart <form method="post" action="{% url 'add_to_cart' item.id %}"> {% csrf_token %} <div class="text-center"> <span class="input-group-btn"> <button class="btn btn-light color-orange " type="submit"> Add to Cart </button> </span> </div> </form> And this is my urls from my cart app from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.view_cart, name='view_cart'), path('add/<item_id>/', views.add_to_cart, name='add_to_cart'), ] Would be great if someone could guide me -
Django rest framrwork assertion error: Class ProductSerializer missing "Meta.model" attribute
I have imported the Django model Product into the DRF model serializer class, but I get the error Class ProductSerializer missing "Meta.model" attribute. What surprises me is that the model is set on the Meta class. What I'm I doing wrong? Error AssertionError at /api/products/ Class ProductSerializer missing "Meta.model" attribute Request Method: GET Request URL: http://localhost:8000/api/products/ Django Version: 3.0.4 Exception Type: AssertionError Exception Value: Class ProductSerializer missing "Meta.model" attribute Exception Location: c:\dev\django-paystack\env\lib\site-packages\rest_framework\serializers.py in get_fields, line 1020 Python Executable: c:\dev\django-paystack\env\Scripts\python.exe Python Version: 3.7.1 Python Path: ['c:\\dev\\django-paystack', 'c:\\dev\\django-paystack\\env\\Scripts\\python37.zip', 'C:\\Users\\Romeo\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\Romeo\\AppData\\Local\\Programs\\Python\\Python37\\lib', 'C:\\Users\\Romeo\\AppData\\Local\\Programs\\Python\\Python37', 'c:\\dev\\django-paystack\\env', 'c:\\dev\\django-paystack\\env\\lib\\site-packages'] Server time: Wed, 29 Jul 2020 14:43:24 +0000 Here is the view: from django.shortcuts import render from rest_framework import viewsets, generics from rest_framework.response import Response from .models import Product from .serializer import ProductSerializer class ProductsViewSet(viewsets.ViewSet): """List products viewset""" def list(self, request): queryset = Product.objects.all() serializer = ProductSerializer(queryset, many=True) return Response(serializer.data) Model Class from django.db import models class Product(models.Model): """Product items""" name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) image = models.FileField(upload_to="uploads/%Y/%m/%d", null=True, blank=True) price = models.FloatField(null=True, blank=True) def __str__(self): return self.name class Order(models.Model): """Order for product item""" product = models.ForeignKey( Product, max_length=200, blank=True, on_delete=models.DO_NOTHING ) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.product.name Model serializer class from rest_framework import serializers from … -
Iterate through similar model field names in template (e.g. FieldName1, FieldName2, etc.)
Fairly new to Django and Python, but trying my best to learn how to clean my code. Currently, I have a model called Recipe that can hold 30 steps (Field Names = Step1, Step2, etc.) and 30 ingredients (Field Names = Ingredient1, Ingredient2, etc.) amongst other fields. The snippet of code below works great, but I am currently manually doing this for all 30 table rows up to Step30, Ingredient30, etc. I've tried setting up a for loop that places {{ i }} at the end of the Field Name to generate up to 30, but am generating parsing issues. I've also tried placing the Field Names in a list or dictionary and looping through them that way, but ultimately will only generate the name of the string, not the attributes value. Below is my setup, which as I mentioned currently works. HTML <tr> <td> {% if recipe.hot_ingredient_icon1 %} <img src="{% static 'img/icons/hot-icon.png' %}" alt="hot-icon" class="ingredient-key-icon"> {% endif %} {% if recipe.cansub_ingredient_icon1 %} <img src="{% static 'img/icons/substitute-icon.png' %}" alt="subsitute-icon" class="ingredient-key- icon"> {% endif %} {% if recipe.fresh_or_ground_ingredient_icon1 %} <img src="{% static 'img/icons/fresh-or-ground-icon.png' %}" alt="fresh-or-ground-icon" class="ingredient-key-icon"> {% endif %} </td> {% if recipe.ingredient1 %} <td>{{ recipe.ingredient1 }}</td> {% endif %} {% … -
Custom User Authentication For Json gives error
I am trying to design a custom Json user authentication as standard django user model does not suit me. But i am having problems. Serializer.py class UserLoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=255) password = serializers.CharField(max_length=128, write_only=True) class EmailAuthBackend(): def authenticate(self, request, email, password): try: user = User.objects.get(email=email) success = user.check_password(password) if success: return user except User.DoesNotExist: pass return None def get_user(self, uid): try: return User.objects.get(pk=uid) except: return None View.py class UserLoginView(RetrieveAPIView): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def post(request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) return Response(serializer.data) def get(self, request, format=None): queryset = User.objects.all() serializer = UserLoginSerializer() return Response(serializer.data) The problem that i am facing is : -It is returning the same output of input (if i entered userabc@email.com,it returns userabc@email.com . Http 200 Response unrelated to the method) instead of turning user or turning none. What can i do to solve this issue? -
Customise BootstrapDateTimePickerInput
This is my registration form. The ridiculous date format allows me to differentiate between my custom made format and more generic ones. models.py class User(AbstractBaseUser): d_o_b = models.DateField(default=timezone.now()-datetime.timedelta(days=6570)) 6570 is 18 * 365 forms.py widgets = {'d_o_b': BootstrapDateTimePickerInput(format='%d/%d/%m/%m/%m/%m/%Y', attrs={'class':'datepicker-start'})} When I change the date, the date format changes to an American style one. When I change the date, I want my custom made formatting to remain. And I also want to stop users being able to select dates pre 2000. boostrap_datetimepicker.html This was the default code (minus the date format which I modified). {% include "django/forms/widgets/input.html" %} <div class="input-group-append" data-target="#{{ widget.datetimepicker_id }}" data-toggle="datetimepicker"> <div style='background-color:blue' class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> <script> $(function () { $("#{{ widget.datetimepicker_id }}").datetimepicker({ format: 'DD/DD/MM/MMM/YYYY/', }); }); </script> I thought the function widget.datetimepicker_id would run every time you chose a date. I thought you used this function to determine how your date could appear on the screen. But the function only seems to have any effect first time you load the page and only when d_o_b has a default value. And if you have (a) widgets = {'d_o_b': BootstrapDateTimePickerInput(format='%d/%d/%m/%m/%m/%m/%Y', attrs={'class':'datepicker-start'})} as oppose to (b) widgets = {'d_o_b': BootstrapDateTimePickerInput()} then the function widget.datetimepicker_id also seems to have … -
permission denied: mod_wsgi Call to fopen() failed for 'path/wsgi.py apache ubuntu
hi i try to deploy my django project 2.2v on ubuntu apache server when i run cat /var/log/apache2/error.log i get this error: [time] [wsgi:error] [pid 13224:tid 2323232] (13)Permission denied: [remote some number:number] mod_wsgi (pid=13323, process='django_app', application='django_project|'): Call to fopen() failed for '/root/project_name/project_name/wsgi.py'. my wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zettapc.settings') application = get_wsgi_application() This is my /etc/apache2/sites-available/django_proj.conf : <VirtualHost *:80> Alias /static /root/project_name/static <Directory /root/project_name/static> Require all granted </Directory> Alias /meida /root/project_name/meida <Directory /root/project_name/meida> Require all granted </Directory> <Directory /root/project_name/zettapc> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /root/project_name/project_name/wsgi.py WSGIDaemonProcess django_app python-path=/root/project_name python-home=/root/project_name/venv/ WSGIProcessGroup django_app </VirtualHost> and output of on my browser is : Internal Server Error is there something i've missed -
Implementing ajax like button in infinite scroll listview django
I am trying to implement ajax like button in infinite scrolling listview of the Django. But my ajax like button works only on the first page. Here is the infinite scroll javascript: $(document).ready(function(event) { var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], handler: function(direction) { }, offset: 'bottom-in-view', onBeforePageLoad: function () { $('.spinner-border').show(); }, onAfterPageLoad: function () { $('.spinner-border').hide(); } }); }); Here is the jquery for like button: $(document).ready(function(event){ $(document).on('click', '.{{post.id}}-PostLike', function(event){ event.preventDefault(); var pk = $(this).attr('value'); $.ajax({ type: 'POST', url: '{% url "tasks:Post_like" %}', data: {'post_id':pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: 'json', success: function(response){ $('.{{post.id}}').html(response['form']) console.log($('.{{post.id}}').html(response['form'])); }, error: function(rs, e){ console.log(rs.responseText); }, }); }); }); -
Django: object and reference object fields access
I have two class in my models.py file: class Asset(models.Model): name = models.CharField(max_length=250) short_name = models.CharField(max_length=100) class AssetTimeSeries(models.Model): asset= models.ForeignKey(Asset, on_delete=models.CASCADE,) date = models.DateField() contribution = models.DecimalField(max_digits=12, decimal_places=2) irr_value = models.DecimalField(max_digits=9, decimal_places=4) quarter_highlights = models.TextField() and I defined views.py code like this: class AssetDetailView(DetailView): model = Asset context_object_name = 'asset' template_name = 'asset/asset_detail.html' and this is the asset_detail.html file: {% block content %} <div class="asset-detail"> <h2>{{ asset.name }}</h2> <p>Short name: {{ asset.short_name }}</p> {% for asset_time_series in asset.asset.all %} <p>{{ asset_time_series.quarter_highlights }}</p> <p>{{ asset_time_series.irr_value}}</p> {% endfor %} <div> <h3>Asset history</h3> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">Date</th> <th scope="col">Contribution</th> </tr> </thead> <tbody> {% for asset_time_series in asset.asset.all %} <tr> <td>#</td> <td>{{ asset_time_series.date }}</td> <td>{{ asset_time_series.contribution }}</td> </tr> {% endfor %} </tbody> </table> </div> </div> {% endblock content %} Is there a clever way to get last inserted values of the AssetTimeSeries object related to an Asset objects? I mean can I rewrite this code to show me only the last values? instead of all the values? {% for asset_time_series in asset.asset.all %} <p>{{ asset_time_series.quarter_highlights }}</p> <p>{{ asset_time_series.irr_value}}</p> {% endfor %} -
How fetch username of staff user in django forms
I am using a custom User model. And I have another Customer model. I want the user field will only show the staff user no other type of user in the field will show in the registration form. In my case, it is showing all types of users whether it is staff or customer or a service user. Models.py class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=254, unique=True) name = models.CharField(max_length=254, null=True) email = models.EmailField(max_length=254, null=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_Customer = models.BooleanField(default=False) is_Service_Provider = models.BooleanField(default=False) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'username' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % self.pk def get_username(self): return self.username class Customer(models.Model): user = models.OneToOneField('accounts.User', on_delete=models.SET_NULL, null=True) email = models.EmailField(max_length=254, null=False) date_Of_Birth = models.DateField(null=False) country = models.ForeignKey('accounts.Country', null=True, on_delete=models.SET_NULL, related_name='Country') state = models.ForeignKey('accounts.State', null=True, on_delete=models.SET_NULL, related_name='State') city = models.ForeignKey('accounts.City', null=True, on_delete=models.SET_NULL, related_name='city') address = models.CharField(max_length=254, null=False) refernce_by_person_name = models.CharField(max_length=254, null=True) refernce_by_person_contact_no = models.IntegerField(null=True) phone_no = models.IntegerField(null=False) alternate_no = models.IntegerField(null=False) hobbies = models.CharField(max_length=254) def __str__(self): return self.user.username views.py def form(request): forms = CustomerRegistrationForm() if request.method == "POST": forms = CustomerRegistrationForm(request.POST) if forms.is_valid(): forms.save() return redirect('/customer/show') context = { 'forms' : forms, } return … -
How to show view actions in Django REST Framework
I need to make a spreadsheet of the endpoints in our api and the methods that can be used, and I'm trying to use django's show_urls management command as a base. My question is: is there a way to get the allowed methods on a view from the view class itself?