Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running nginx and gunicorn in the same docker file
I have a Dockerfile which at the end runs run.sh. I want to run gunicorn on port 8000 and proxy requests on 80 to 8000 with nginx. The problem is running server is a blocking command and it never executes nginx -g 'daemon off;'. What can I do to handle this situation? Here is the run.sh file: python manage.py migrate --noinput gunicorn --bind=0.0.0.0:8000 bonit.wsgi:application & nginx -g 'daemon off;' And this the Dockerfile: FROM python:3.8 # set work directory WORKDIR /usr/src/app # set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update && apt-get install -y nginx supervisor build-essential gcc libc-dev libffi-dev default-libmysqlclient-dev libpq-dev RUN apt update && apt install -y python3-pip python3-cffi python3-brotli libpango-1.0-0 libpangoft2-1.0-0 RUN pip install --upgrade pip COPY requirements.txt . RUN pip install -r requirements.txt COPY . . COPY nginx.conf /etc/nginx/nginx.conf RUN python manage.py collectstatic --noinput ENTRYPOINT ["sh", "/usr/src/app/run.sh"] -
Django Elastic Search - How to improve Big Data Indexing speed in ES
I've Epsiode Index where I've only 1 field which I used for searching. I've 53 Millions of records in PostgreSQL. I used django-elasticsearch-dsl lib. for elastic search engine. The problem is When I run the cmd to dump the PostgreSQL episodes table into Episode Index it almost takes 5-6 hours. How can I overcome this problem. Its a bottleneck for me to deploy on prod. documents.py search_analyzer = analyzer('search_analyzer', filter=["lowercase"], tokenizer=tokenizer('autocomplete', 'edge_ngram', min_gram=1, max_gram=15)) @registry.register_document class EpisodeDocument(Document): title = fields.TextField(analyzer=search_analyzer) class Index: name = 'episode' settings = { 'number_of_shards': 4, 'number_of_replicas': 2, 'max_ngram_diff': 10 } class Django: model = Episode queryset_pagination = 5000 cmd for Data dump into ES python manage.py search_index --rebuild ES machine: t3.2xlarge -
LDAP bind failed: LDAPOperationsErrorResult - 1 - operationsError - None - 000004DC: LdapErr: DSID-0C090A5C,
I am using "django-python3-ldap". I have set up all and while syncing user by command "./manage.py ldap_sync_users" This shows the following binding error LDAP connect succeeded LDAP bind failed: LDAPOperationsErrorResult - 1 - operationsError - None - 000004DC: LdapErr: DSID-0C090A5C, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v4563 - searchResDone - None Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django_python3_ldap/ldap.py", line 182, in connection yield Connection(c) File "/usr/local/lib/python3.5/dist-packages/django_python3_ldap/management/commands/ldap_sync_users.py", line 24, in handle for user in connection.iter_users(): File "/usr/local/lib/python3.5/dist-packages/django_python3_ldap/ldap.py", line 93, in <genexpr> self._get_or_create_user(entry) File "/usr/local/lib/python3.5/dist-packages/ldap3/extend/standard/PagedSearch.py", line 68, in paged_search_generator None if cookie is True else cookie) File "/usr/local/lib/python3.5/dist-packages/ldap3/core/connection.py", line 853, in search response = self.post_send_search(self.send('searchRequest', request, controls)) File "/usr/local/lib/python3.5/dist-packages/ldap3/strategy/sync.py", line 178, in post_send_search responses, result = self.get_response(message_id) File "/usr/local/lib/python3.5/dist-packages/ldap3/strategy/base.py", line 403, in get_response raise LDAPOperationResult(result=result['result'], description=result['description'], dn=result['dn'], message=result['message'], response_type=result['type']) ldap3.core.exceptions.LDAPOperationsErrorResult: LDAPOperationsErrorResult - 1 - operationsError - None - 000004DC: LdapErr: DSID-0C090A5C, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, v4563 - searchResDone - None here are my settings file ` # The URL of the LDAP server. LDAP_AUTH_URL = "ldaps://example.com:636" # Initiate TLS on connection. LDAP_AUTH_USE_TLS = True # The … -
django query with filtered annotations from related table
Take books and authors models for example with books having one or more authors. Books having cover_type and authors having country as origin. How can I list all the books with hard cover, and authors only if they're from from france? Books.objects.filter(cover_type='hard', authors__origin='france') This query doesnt retrieve books with hard cover but no french author. I want all the books with hard cover, this is predicate #1. And if their authors are from France, I want them annotated, otherwise authors field may be empty or 'None'. Tried many options, annotate, Q, value, subquery, when, case, exists but could come up with a solution. -
Making a custom template for CreateView and UpdateView with placeholders and error validation
I'm making a generic blog while learning Django. I have an ArticleCreateView and ArticleUpdateView, and I am trying to make a custom template that both views would share. From what I understand, CreateView and UpdateView use the same template by default (article_form.html), which is the template I'm trying to modify. I have the following in my models.py: class Article(models.Model): title = models.CharField(max_length=100) body = models.TextField() # def __str__ ... # def get_absolute_url ... In my views.py: class ArticleCreateView(CreateView): model = Article fields = ['title', 'body'] template_name = 'article_form.html' class ArticleCreateView(CreateView): model = Article fields = ['title', 'body'] template_name = 'article_form.html' Having the following in my template article_form.html works: <form method='post'> {{ form.as_p }} <button> Publish </button> </form> I want to make it more fancy though, with loads of CSS, and a simplified version is: <form method='post'> {% csrf_token %} <fieldset class="fieldset-class"> {{ form.title.errors }} <input class="form-class" type="text" placeholder="Article Title" name="{{ form.title.name }}" value="{{ form.title.value }}" /> </fieldset> <fieldset class="form-group"> {{ form.body.errors }} <textarea class="form-control" rows="8" placeholder="Article Body" name="{{ form.body.name }}" >{{ form.body.value }}</textarea> </fieldset> </form> What I want is a form that: has placeholders in empty fields (instead of labels) has model-based error validation (max_length is respected and both fields … -
Django Validation is working on django admin but not working on html template
I'm creating a form where if we register it should save data to the database if the form is valid. otherwise, it should raise an error but it doesn't save data to the database, and also some fields are required but if I submit the form it doesn't even raise the error field is required. but if I register it manually on Django admin pannel it works perfectly fine. here is my model: class foodlancer(models.Model): Your_Name = models.CharField(max_length=50) Kitchen_Name = models.CharField(max_length=50) Email_Address = models.EmailField(max_length=50) Street_Address = models.CharField(max_length=50) City = models.CharField(max_length=5) phone = PhoneNumberField(null=False, blank=False, unique=True) def __str__(self): return f'{self.Your_Name}' also, I disabled html5 validation forms.py class FoodlancerRegistration(forms.ModelForm): phone = forms.CharField(widget=PhoneNumberPrefixWidget(initial="US")) class Meta: model = foodlancer fields = "__all__" views.py: def apply_foodlancer(request): form = FoodlancerRegistration() return render(request, 'appy_foodlancer.html', {"form": form}) and finally Django template <form method="POST" novalidate> {% csrf_token %} {{ form.as_p }} <button type="submit" class="cta-btn cta-btn-primary">Submit</button> </form> Thank you for your time/help -
how to change where summernote looks for images
Everything works for me on summernote but when i add image in the text it dosent show up in frontend i know the reason is that it looks for image on localhost:3000/media/django-summernote/2021-12-06/default.png but istead of 3000 it should be going to localhost:8000 urls.py from django.contrib import admin from django.urls import path, include, re_path from django.views.generic import TemplateView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('api-auth/', include('rest_framework.urls')), path('summernote/', include('django_summernote.urls')), path('api/', include('api.urls')), path('admin/', admin.site.urls), ] + static (settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns +=[re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] -
django - AttributeError at /signup/ 'User' object has no attribute 'profile'
I implemented 2FA in my Django application however I am getting AttributeError at /signup/ 'User' object has no attribute 'profile' error when clicking submit in my SignIn form. It shows me that error occurs in six.text_type(user.profile.email_confirmed) line. I don't have any custom User model. I am using default User model. Could you please tell me wjere is the issue and how to fix it? tokens.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.profile.email_confirmed) ) account_activation_token = AccountActivationTokenGenerator() views.py from django.contrib.auth import login from django.contrib.auth.models import User from .forms import SignUpForm from django.views.generic import View from django.shortcuts import render, redirect from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse_lazy from django.contrib import messages from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.template.loader import render_to_string from .tokens import account_activation_token from django.utils.encoding import force_text from django.contrib import messages # Sign Up View class SignUpView(View): form_class = SignUpForm template_name = 'user/register.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = … -
PayU payment integration failed on Django
I used payu payment integrations on django using paywix. Now i faced a problem payment failed on success payment and payu not response any data about that. Payu redirect to sucess page but not response any data about payment can any one help me on this -
limiting the number of records return with getattr in django model
currently working on a billing application for multi company database. Where some data are company code dependent and some are not. to filter the data for each data model i am trying to make a generic function to filter each data model. i am using a Model level indication for each data model to know if the data is company dependent or not. my generic method is like below. def filter_Company_or_Group(dbModelName, compGroup, compId, filter = {}, ModelLevel = '', orderByField = '', recordLimit = -1, unique = False): if ModelLevel == '': ModelLevel = getdbModelLevel(dbModelName) if ModelLevel == '': ModelLevel = 'Global' q_objects = Q() modelFilter = {} if ModelLevel == 'Company': modelFilter = {'company_id' : compId} q_objects = Q(company_id = compId) if ModelLevel == 'Group': modelFilter = {'company_Group_id' : compGroup} q_objects = Q(company_Group_id = compGroup) if ModelLevel == 'Company OR Group': q_objects |= Q(company_id = compId) q_objects |= Q(company_Group_id = compGroup) if ModelLevel == 'Global' or ModelLevel == 'ANY': q_objects = Q() if filter != {}: for key, value in filter.items(): q_objects &= Q(**{key: value}) if orderByField == '' : orderByField = 'id' objList = getattr(billing.models, dbModelName).objects.order_by(orderByField).filter(q_objects) if recordLimit != -1: objList = objList[:recordLimit] return objList here method getdbModelLevel … -
Django admin doest work on production. Forbidden (403) CSRF verification failed. Request aborted
I have a problem with admin login on Production. Everything works fine on local I use httpS I've already cleaned my browser cache for several times. It doesn't help Settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ALLOWED_HOSTS = ['tibrains.com'] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_REPLACE_HTTPS_REFERER = True CORS_ORIGIN_WHITELIST = ( 'https://www.tibrains.com', 'https://www.tibrains.com/admin/login/?next=/admin/', 'tibrains.com', 'www.tibrains.com' ) CSRF_TRUSTED_ORIGINS = ['tibrains.com', 'https://www.tibrains.com/admin/login/?next=/admin/', 'https://www.tibrains.com/admin/', ] CSRF_COOKIE_DOMAIN = '.tibrains.com' SESSION_COOKIE_DOMAIN = "tibrains.com" CSRF_COOKIE_SECURE=True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') Nginx location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } -
AttributeError : 'super' object has no attribute 'get'
i'm creating a simple webstore, in the product template i put the order form using FormMixin. When i submit the order, and AttributeError appears saying that : 'super' object has no attribute 'get' models.py class Product(models.Model): name = models.CharField(max_length=255) description = models.TextField() nominal_price = models.PositiveIntegerField(verbose_name='prix normal',) reduced_price = models.PositiveIntegerField(blank=True, null=True) quantity = models.PositiveIntegerField(default=10) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') photo = models.ImageField(upload_to="img/products/", default="img/products/user_default.png") def __str__(self): return self.name class Customer(models.Model): full_name = models.CharField(max_length=150) address = models.CharField(max_length=1500, null=True) phone = models.IntegerField() city = models.CharField(max_length=100) email = models.EmailField(null=True) def __str__(self): return self.full_name class Order (models.Model): product = models.ManyToManyField(Product, through='OrderProduct') customer = models.ForeignKey(Customer, on_delete=models.CASCADE) views.py class ProductDetailView(FormMixin, TemplateView): model = Product template_name = 'product.html' form_class = OrderForm def get_success_url(self): return reverse('index') def post(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) form = OrderForm(request.POST) if context['form'].is_valid(): product = get_object_or_404(Product, name=self.kwargs['product_name']) customer = form.save() # Order.objects.create(customer=customer) instance = Order.objects.create(customer=customer) instance.product.add(product) return super(TemplateView, self) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['product'] = Product.objects.get(name=self.kwargs['product_name']) context['form'] = self.get_form() return context urls.py urlpatterns = [ path('', views.ProductListView.as_view(), name='index'), path ('products/<str:product_name>/', views.ProductDetailView.as_view(), name='product'), path('categories/', views.CategoryListView.as_view(), name='categories'), ] Here is the traceback Traceback Traceback (most recent call last): File "D:\Python\Django\Django projects\Store\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Python\Django\Django projects\Store\venv\lib\site-packages\django\utils\deprecation.py", line 119, in … -
React and Django simple jwt profile update not null error
my problem I created a user profile model that is one to one relationship to django custom user model to update the profile from react. when i click update button in my ui, it says update user profile failed. I tried changing the model to null=True and I make makemigrations and migrate for many times but it doesn't work. Thank you for your answer in advanced! My error return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: profiles_userprofile.user_id [09/Dec/2021 16:00:49] "PUT /profile-api/update-profile/ HTTP/1.1" 500 198827 User profile model from django.db import models from django.conf import settings class UserProfile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) phone = models.CharField(max_length=30, default='') address = models.CharField(max_length=300, default='') profile_image = models.ImageField(upload_to="profile_images", default='') User profile serializer from rest_framework import serializers from .models import UserProfile class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('phone', 'contact', 'profile_image',) User profile view class UserProfileView(APIView): parser_classes = (MultiPartParser, FormParser) permission_classes = (permissions.IsAuthenticated,) def put(self, request, format=None): user = self.request.user email = user.email data = self.request.data phone = data['phone'] address = data['address'] profile_image = data['profile_image'] UserProfile.objects.filter(user=user).update_or_create( phone=phone, address=address, profile_image=profile_image) user_profile = UserProfile.objects.get(user=user) user_profile = UserProfileSerializer(user_profile) return Response({'profile': user_profile.data, "email": str(email)}, status=status.HTTP_200_OK) Update profile react actions export const update_profile = (phone, address, profile_image) => … -
Django - Time difference right way
In the following code i'm trying to get the difference between two times, if the difference is not equal to 15 minutes throw an error. I use the following way which seems to work, however i have a feeling that is not the proper way. def clean(self): cleaned_data = super().clean() start_appointment = cleaned_data.get("start_appointment") end_appointment = cleaned_data.get("end_appointment") difference = end_appointment - start_appointment if difference != '0:15:00': raise forms.ValidationError("Start appointment should have a 15 minutes difference from end appointment!") Please have a look and let me know if this is the right way. Thank you -
string concat causing 'str' object has no attribute 'object'
I have a view like below: I get the error: 'str' object has no attribute 'object' it must have something to do with my string concat - what has gone wrong :) thanks def edit_skill_plan(request): #t = skills.objects.get(skill_id='django_5158517') skillid = request.POST.get('editbut') user = request.user t = skills.objects.get(creator=user, skill_id=skillid) t.status = 'closed' t.save() # this will update only complete_date = datetime.today().strftime('%Y-%m-%d') week_num = datetime.today().strftime('%V') x = t.skill_name user = request.user points = t.points cat = t.category year = datetime.today().strftime('%Y') status = str(request.user.username) +' completed the task: ' + str(x) + ' which was worth: ' + str(points) + ' points' status.object.create(creator=user, status=status, status_date=complete_date) -
Django custom decorator with redirect and re-redirect after decorator condition has been satisfied
I am trying to build a decorator that has a similar function like the @login_required decorator in Django. However, I do not want to force a login but rather that the requesting user accepts an agreement and then after the user accepted the agreement, it should be redirected to the actual target page. The @login_required decorator appends the following to the URL, when calling the home page before authentication: ?next=/en/home/ I need the custom decorator to also be able to append and process the actual target URL. Does anyone of you know how to do that? Does Django offer any function for that? -
Is it a good way using a DjangoModelFactory and other factories in API requests?
I noticed that DjangoModelFactory has got more functionality than DRF ModelSerializers. I want to use DjangoModelFactory to create records in database in my API, but it seems no one do this. In most cases, Factories are used only for tests, not in usual code. Why? Is it a good way using them in API requests, for example? -
Django app deployed on Heroku is painfully slow on Firefox & Safari - potential causes?
I've deployed an e-commerce site app to Heroku with the static files and media photos being hosted from an Amazon S3 bucket. The app is totally smooth on Chrome and Brave (both mobile / desktop), but tends to be appallingly slow on Firefox and Safari, regardless of device. As an example, here's a screenshot of how long some of the assets took to load when opening the app via Firefox. Project link: MyShop If I run the project on local machine (also with static & media assets being loaded from S3 directly), it is still quite slow, albeit to a lesser degree. Any ideas on how to troubleshoot? -
Django using include with a dynamic view does not work
I created a view that allows me to have a dynamic slider and I render it in an html file called slider. i have a main page called test where i include this slider file, the problem is it doesn't render anything for me,it's like it doesn't see my slider view and therefore nothing is rendered, but the file is included anyway. someone can make me understand why and would you give me a hand to solve this problem? views class SlideListView(ListView): model = Slide template_name = 'slider.html' context_object_name = 'slides' def get_queryset(self): queryset = Slide.objects.all().order_by(F('ordine').asc(nulls_last=True)) #ordine con None a fine slider return queryset url path('', TemplateView.as_view(template_name="test.html")), html iclude <section class="container mt-3"> <div class="d-flex align-items-center justify-content-between"> <h1 class="nome-scheda">SLIDER</h1> <a href="{% url 'bo_slider' %}" class="btn btn-outline-primary">VARIE SLIDE</a> </div> <hr> <div class="row justify-content-center mt-5"> <div class="col-lg-6"> <div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> {% for slide in slides %} {% if slide.attivo == True %} <!--se lo switch è on mostro la slide--> <!--aggiungo classe active alla prima in modo da farlo partire--> <div class="carousel-item {% if forloop.first %} active {% endif %}"> <img src="{{ slide.immagine.url }}" class="d-block w-100"> {% if forloop.first %} <!--alla prima slide metto il tag h1--> <h1>{{ slide.titolo … -
Download file stored in a model with FileField using Django
I'm planning on creating a simple file upload application in Django (incorporated in some bigger project). For this one, I'm using two links: /files/ - to list all the uploaded files from a specific user, and /files/upload/ - to display the upload form for the user to add a new file on the server. I'm using a PostgreSQL database, and I'm planning to store all my files in a File model, that looks like this: class File(models.Model): content = models.FileField() uploader = models.ForeignKey(User, on_delete=models.CASCADE) My file upload view looks like this: @login_required def file_upload_view(request): if request.method == "POST" and request.FILES['file']: file = request.FILES['file'] File.objects.create(content=file, uploader=request.user) return render(request, "file_upload_view.html") else: return render(request, "file_upload_view.html") while my file list view looks like this: @login_required def file_view(request): files = File.objects.filter(uploader = request.user) return render(request, "file_view.html", {'files': files}) The problem is, I want my file_view() to display all files uploaded by a certain user in a template (which I already did), each file having a hyperlink to its download location. I've been trying to do this in my file list template: {% extends 'base.html' %} {% block content %} <h2>Files of {{ request.user }}</h2> <br> {% for file in files %} <a href="{{ file.content }}" … -
when should use regex for urls in django? [closed]
when is better and prefered to use regex in django (or drf) urls? -
Django project, data deleted from the database
I am new in web development with Django and MySQL database, I got to develop a web application with Django framework, after deployment of my project in the server. after 2 months, I noticed that data from my order table was deleted as well as the data of one user is displayed in the profile of another, I want to know what I must do as a test to know the PR eventual error and to stop the deletion of data in my database. data often deleted in the order and customer table. the ORDER model bind with a foreign key to other Model: class Order(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) created = models.DateTimeField( auto_now_add=True, verbose_name=_('Creation Date')) payed = models.DateTimeField( verbose_name=_('Payment Date'), default=datetime.now, null=True, blank=True) reference = models.IntegerField( verbose_name=_('Order Reference'), default=0, null=True, blank=True ) customer = models.ForeignKey( Customers, verbose_name=_('Customer'), null=True, blank=True, on_delete=models.CASCADE ) company = models.ForeignKey( Compagnie, verbose_name=_('Company'), null=True, blank=True, on_delete=models.CASCADE ) class Customers(models.Model): company = models.ForeignKey( Compagnie, verbose_name=_('Company'), null=True, blank=True, on_delete=models.CASCADE ) forename = models.CharField( verbose_name=_('First Name'), max_length=255, null=True, blank=True) GENDER = [('M', _('Male')), ('F', _('Female'))] gender = models.CharField( verbose_name=_('Gender'), max_length=1, choices=GENDER, null=True, blank=True) city = models.ForeignKey( City, verbose_name=_('City'), null=True, blank=True, on_delete=models.CASCADE ) additionalNum = models.CharField( verbose_name=_('Additional Number:'), … -
How to Build the Github Portfolio
I am a web developer and I want to build my GitHub portfolio for my Clients and remote jobs. Can anyone guide me on this? I have experience in Reactjs, Vuejs and Python Django. Should I contribute to exisitng open source projects or should I develop my own? -
Cutom Form with auto Certificate generation using django
I wanted to develop one functionality for django website. Idea: I want to create forms for categories like (event-x, event-y, etc..) through django admin and users will fill up the form through frontend. The form data will be stored in the database and it will generate pdf certificate and will send to respective users. And also should store the status of the certificate. The idea derived from google forms.. Any suggestions... -
My JQurery-AJAX code in my Django project for displaying a default value in a calculation based field fails to do so?
These are two of few models in my project: class Package(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=models.ForeignKey(Treatment, on_delete=CASCADE) patient_type=models.ForeignKey(PatientType, on_delete=CASCADE) date_of_admission=models.DateField(default=None) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) package_date=models.DateTimeField(auto_now_add=True) class Receivables(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) rt_number=models.CharField(max_length=15) discount=models.DecimalField(max_digits=9, decimal_places=2, default=0) approved_package=models.DecimalField(max_digits=10, decimal_places=2) approval_date=models.DateField(default=None) proposed_fractions=models.IntegerField() done_fractions=models.IntegerField() base_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) expected_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) receivables_date=models.DateTimeField(auto_now_add=True) I needed the approved_package in Receivables to display a default value calculated by subtracting discount from the total_package in Package. And it should all be in real time. So I wrote an AJAX code in Jquery in an HTML file and included the file in my main template. The code looks like: <script> $('select').change(function () { var optionSelected = $(this).find("option:selected"); var valueSelected = optionSelected.val(); var textSelected = optionSelected.text(); var csr = $("input[name=csrfmiddlewaretoken]").val(); console.log(textSelected); pkg={patient:textSelected, csrfmiddlewaretoken:csr} $.ajax({ url:"{% url 'pt_name' %}", method: "POST", data: pkg, dataType: "json", success: function(data){ console.log(data); console.log(data.pkg); console.log(data.ptt); var tp=data.pkg; var ptt=data.ptt; $('#id_discount').change(function(){ console.log('tp value: ', tp); console.log('ptt value: ', ptt); var discount=document.getElementById('id_discount').value; console.log('discount value: ', discount); var approved_package=document.getElementById('id_approved_package').value; if (ptt=='CASH') approved_package=tp-discount; console.log('approved package new value: ', approved_package); }); } }); }); </script> The code runs fine in the console of the browser. It fires all the codes. It calculates the approved_package but the result still does not show up in the field …