Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Do I need to clear the prefetch cache after each Django prefetch_related?
Django mentions that this is the way to clear the prefetch cache: non_prefetched = qs.prefetch_related(None) Which you should do since now the values are loaded into memory. One problem I'm finding is that this is even persisting across requests, meaning that the data is still cached even after returning in a separate session. Is this expected behavior, or am I misunderstanding? If this is the expected behavior, does this also mean I have to clear the cache at the end of every view with the call above? -
Tox.ini does not recognize python folder?
I ran into weird issue which I have trouble solving. I have following tox.ini file: [vars] PROJECT = django_project TASKS = tasks --exclude tasks/migrations PAGES = pages -exclude pages/migrations [tox] envlist = py310, flake8, black, mypy [testenv] deps = -rrequirements.txt -rrequirements-dev.txt commands = python manage.py test [testenv:flake8] basepython=python3 deps = -rrequirements-dev.txt commands= python -m flake8 --max-line-length=100 {[vars]PROJECT} {[vars]TASKS} {[vars]PAGES} whitelist_externals = /usr/bin/python3 [testenv:black] deps = -rrequirements-dev.txt commands = black --check --diff {[vars]PROJECT} {[vars]TASKS} {[vars]PAGES} [testenv:mypy] deps = -rrequirements-dev.txt commands = mypy --install-types --non-interactive \ --ignore-missing-imports \ --disallow-untyped-defs \ --disallow-incomplete-defs \ --disallow-untyped-decorators {[vars]PROJECT} {[vars]TASKS} {[vars]PAGES} The black commands works as expected for PAGES, but the commands flake8 and mypy are returning following error: error: unrecognized arguments: pages -exclude pages/migrations Does anyone have any idea what could be causing this? -
Could not parse the remainder: '{%get(gender='F')%}.fullname' from 'x.parent.{%get(gender='F')%}.fullname'
I have a problem with getting a data in template. I am writing code in python file its working. students = Student.objects.all() for x in students: print(x.parent.get(gender='M').fullname) It gets me Parent Fullname, but when i write it in template like: {% for x in students %} <td class="small d-none d-xl-table-cell text-center">{{ x.parent.{%get(gender='F')%}.fullname }}</td> {% endfor %} it gets me Could not parse the remainder: '{%get(gender='F')%}.fullname' from 'x.parent.{%get(gender='F')%}.fullname' error. I tried write it like {{ x.parent.get(gender='F').fullname }} but i get same error Same code working in python file but not working in template. -
videojs player seek buttons works in other browsers but not in chrome. The video starts again on clicking the progress bar
I'm fetching a video from s3 bucket using django(backend) and then playing the video in react (frontend) but the seek controls work in other browsers but not in chrome. The video starts again on clicking the progress bar or clicking the arrow keys. I don't understand what seems to be the problem. here is my django code for fetching video class GenericFileOperation(APIView): def get(self, request, material_type=None, course_id=None, format=None): key = request.GET.get('key') download = request.GET.get('download') if key is not None: s3_obj = download_assessment_file(key) splited_path = key.split("/") file_name = splited_path[len(splited_path)-1] contents = s3_obj['Body'].read() temp = tempfile.TemporaryFile() temp.write(contents) temp.seek(0) mime_type, _ = mimetypes.guess_type(key) response = HttpResponse(temp, content_type=mime_type) if download is not None: response['Content-Disposition'] = "attachment; filename=%s" % ( file_name) response['X-Frame-Options'] = "*" return response here is my code for videojs in react import React, { useEffect, useRef } from 'react' import VideoJs from 'video.js' import 'video.js/dist/video-js.css'; import "videojs-hotkeys"; import 'videojs-seek-buttons' const videoJsOptions = { controls: true, autoplay: false, fluid: true, loop: false, playbackRates: [0.5, 1, 1.5, 2], aspectRatio: '12:5', plugins: { seekButtons: { forward: 30, back: 10 }, hotkeys: {} } } const VideoPlayer = ({ url, fileType }) => { const videoContainer = useRef() useEffect(() => { videoContainer.current.innerHTML = ` <div data-vjs-player> … -
How do I make ManyToManyField limit_choices_to equal to request.user (Django)?
I should limit choices of manytomanyfield to logged in admin user profile, in django admin. class News(models.Model): title=models.CharField(max_length=200) users=models.ManyToManyField(User, blank=True, limit_choices_to={"profile__school": "request.user.profile.school"}) I have tried to implement it in admin.ModelAdmin, where I can access request.user, but couldn't find a way to do it. -
How to color value in list with django?
I am using the django framework. And I have a list with values. And the values from that list are displayed on a template. So this is the list: self.list_school_values = [ "12bg00", "Basisschool Vroonestein", "Lohengrinhof 1517, 3438RA NIEUWEGEIN Utrecht", "Lohengrinhof 1517, 3438RA NIEUWEGEIN Utrecht", "mevr. W.M. van den Brink", "030-6037291", "info@vroonestein.nl", "196", "Verdi import B.V.", "dhr. Kees Kooijman", "Koopliedenweg 38 , 2991 LN BARENDRECHT", "verdi@qualitycontrolsystems.nl", ] and the template looks: <div class="form-outline"> <div class="form-group"> <div class="wishlist"> <table> <tr> <th>Gegevens school </th> <th>waardes school contract</th> </tr> {% for value0, value1 in content %} <tr> <td> {{value0}} </td> <td class="{% if value1 == '12bg00' %}red {% endif %}"> {{value1}} </td> </tr> {% endfor %} </table> </div> </div> </div> and css: .red { color: red; } But the value is not colored red. Question: how to color the value from the list red? -
Why is django not showing multiple error messages?
When my form has multiple error messages it only show the first one. Forms.py code: class LoginForm(AuthenticationForm): error_messages = { "invalid_login": _("Incorrect login details. Try again"), "inactive": _("This account is inactive."), } I'm just using the normal Auth form but overwriting the already existing error messages so the message says something different. Template code: <form method="POST"> {% csrf_token %} {{ form }} <button type="submit">Log in</button> </form> When a inactive user tries to login the form returns this: {'invalid_login': 'Incorrect login details. Try again', 'inactive': 'This account is inactive.'} While the user did fill in the right details. And this is the only error that gets shown: <ul class="errorlist nonfield"><li>Incorrect login details. Try again</li></ul> I want it to show either both or the inactive error message since I find that more important to know. -
I am new to django and react integrating both using webpack 5
I am following this tutorial https://medium.com/codex/how-to-integrate-react-and-django-framework-in-a-simple-way-c8b90f3ce945 using webpack to integrate react and django getting this error in when runnning python server Performing system checks... System check identified no issues (0 silenced). January 11, 2023 - 01:00:29 Django version 4.0.3, using settings 'music_controller.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [11/Jan/2023 01:00:30] "GET / HTTP/1.1" 200 395 Not Found: /{ % static [11/Jan/2023 01:00:30] "GET /%7B%20%%20static HTTP/1.1" 404 2376 [11/Jan/2023 01:00:36] "GET / HTTP/1.1" 200 395 Not Found: /{ % static [11/Jan/2023 01:00:36] "GET /%7B%20%%20static HTTP/1.1" 404 2376 [11/Jan/2023 01:00:37] "GET / HTTP/1.1" 200 395 Not Found: /{ % static [11/Jan/2023 01:00:37] "GET /%7B%20%%20static HTTP/1.1" 404 2376 [11/Jan/2023 01:00:37] "GET / HTTP/1.1" 200 395 Not Found: /{ % static [11/Jan/2023 01:00:37] "GET /%7B%20%%20static HTTP/1.1" 404 2376 [11/Jan/2023 01:00:37] "GET / HTTP/1.1" 200 395 Not Found: /{ % static [11/Jan/2023 01:00:38] "GET /%7B%20%%20static HTTP/1.1" 404 2376 build using webpack PS C:\Users\harshit\Desktop\tutorial\React-Django\music_controller\frontend> npm run dev frontend@1.0.0 dev webpack --mode development --watch asset main.js 1.12 MiB [compared for emit] (name: main) asset runtime.js 7.19 KiB [compared for emit] (name: runtime) Entrypoint main 1.12 MiB = runtime.js 7.19 KiB main.js 1.12 MiB runtime modules 3.42 KiB 7 modules cacheable modules 1.08 MiB … -
why is when i do put request using django rest framework i got 200 but when i try to see one of fields it shows null using get request not the put one
i was trying to do put request on postman and its scussec but when i try the get method to get same result one of the fields which's car_ year shows null i was trying to do put request on postman and its scussec but when i try the get method to get same result one of the fields which's car_ year shows null from django.shortcuts import render from django.http import HttpResponse,JsonResponse from rest_framework.parsers import JSONParser from .models import Driver from .serializers import DriverSerializer from django.views.decorators.csrf import csrf_exempt from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from rest_framework import generics from rest_framework import mixins from rest_framework.views import APIView # Create your views here. class GenericAPIView(generics.GenericAPIView,mixins.ListModelMixin,mixins.CreateModelMixin,mixins.UpdateModelMixin,mixins.RetrieveModelMixin,mixins.DestroyModelMixin): serializer_class = DriverSerializer queryset = Driver.objects.all() lookup_field = 'id' def get(self,request,id=None): if id: return self.retrieve(request) else: return self.list(request) def post(self,request): return self.create(request) def put(self,request,id=None): return self.update(request,id) from django.db import models # Create your models here. class Driver(models.Model): name=models.CharField(max_length=100) email=models.EmailField(max_length=100) phone_number=models.IntegerField(max_length=None) car_model=models.CharField(max_length=100) car_year=models.IntegerField(max_length=None) def __str__(self): return self.name from rest_framework import serializers from .models import Driver class DriverSerializer(serializers.ModelSerializer): class Meta: model=Driver fields=['id','name','email','phone_number','car_model','car_year'] ``` -
There seems to be a problem with Django Urls?
When ever I run python manage.py runserver, I get a message in the terminal "Not Found: /base/". I do not have this in my urls to start off with anyways so why am I seeing this? Below is what shows up when I run the server. And my url server is default to "http://127.0.0.1:8000/base/" instead of "http://127.0.0.1:8000". Using the URLconf defined in cric_manager.urls, Django tried these URL patterns, in this order: admin/ manager/ The current path, base/, didn’t match any of these. I tried to restart the termnial, VSCODE, and the webpage, but nothing seems to be working. Its getting a little bit annoying. -
How to display name of table from queryset in django
Trying to get the table name in django, I need it to display the detailview correctly via if statemnet. I have such a view to display class Home(ListView): template_name = 'home.html' def get_queryset(self): qs1 = Book.objects.all() qs2 = CD.objects.all() qs3 = Film.objects.all() queryset = sorted(list(chain(qs1, qs2, qs3)), key=operator.attrgetter('title')) return queryset and it returns to me this [<CD: Music1>, <CD: Music2>, <Book: Some books>] How can I get "CD" or "Book" in this template {% block content %} <div class="row"> {% for object in object_list %} <div class="col-md-3"> <div class="card card-product-grid"> <img src="{{ object.image.url }}"> <a href="{% url 'DetailBook' object.pk %}" class="title">{{ object.title }}</a> </div> </div> {% endfor %} </div> {% endblock content %} At the same time, if it's a bad idea to display detailview and listview and it's done differently, I'd appreciate it if you'd let me know I tried different ways of displaying object.key in a loop but it didn't work very well. And other queryset queries. -
'QuerySet' object is not callable
I have this function that must get the class code, and then look for this class in the database, then fill in the participant field of this class with the user who is authenticated. `def participar(request): cc = nameUser(request) if request.method == 'POST': busca = request.POST.get('busca') turma = Turma.objects.filter(codigo=busca) obj = turma(participantes=request.user) obj.save() else: return render(request, 'turmas/participar.html', cc) return render(request, 'turmas/participar.html', cc)` but when trying to add the following error occurs on the line turma(participantes=request.user) 'QuerySet' object is not callable what was expected is that after searching for the desired class by its code, the authenticated user would be added to the participant field of that class -
Django password reset PasswordResetConfirmView
View: def f_forget_password(request): ctx = dict() if request.method == "POST": password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): to_email = password_reset_form.cleaned_data['email'] to_email=to_email.lower() associated_users = User.objects.filter(Q(email=to_email)) if associated_users.exists(): if len(associated_users)!=1: return HttpResponse('Email Is Invalid.') current_site = get_current_site(request) for user in associated_users: mail_subject = "Password Reset Requested" email_template_name = "password/password_reset_email.txt" uid=urlsafe_base64_encode(force_bytes(user.pk)) c = { "email":user.email, 'domain':current_site.domain, 'site_name': 'mysit', "uid": uid, "user": user, 'token': account_activation_token.make_token(user), } try: message = loader.render_to_string(email_template_name, c) email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() except Exception as e: return HttpResponse('Invalid header found.<br/>') return redirect ("/password_reset/done/") else: return HttpResponse('Email not found.') template = loader.get_template('password/forget_password.html') response = HttpResponse(template.render(ctx, request),content_type='text/html') return response url: path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='password/password_reset_done.html'), name='password_reset_done'), path('reset/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='password/password_reset_complete.html'), name='password_reset_complete'), token.py: class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = TokenGenerator() view PasswordResetConfirmView dont work and my password dont change. when i clicked on passwordresetlink i have an Error: Password reset unsuccessful The password reset link was invalid, possibly because it has already been used. Please request a new password reset. -
Using delphi API from django based website
So, I am a beginner in Django I have a Desktop application Api (Delphi based app) in DLL format And I am trying to build a webpage that interact with this desktop App is there any way to do that?? if the answer in a No way, how can I use DLL API To Interact with this app using Kivy or PyQT5 or any python framework PS: I don't have any knowledge of Delphi I didn't try anything I'm just wondering if my idea is doable -
How to get the currently logged in user in django restframework?
I am trying to get the currently logged in user using django restframework and i have written a simple APIView to do this, but when i access the api_view it shows {"detail": "Authentication credentials were not provided."}, how do i provide the authentication credentials? because i have tried loggin in use the login API i created and it show the current access token but when i access the my-profile view it shows that i need to login? How do i provide the authentication details, login and see the user information maybe (username and email) class MyProfileView(APIView): permission_classes = [permissions.IsAuthenticated] def get(self, request): user = User.objects.get(request.user) return Response(user.data) -
Form with post doesn't reach my function in django
I'm stuck with a st*pid question and problem. I'm working with a form(html) on django, this form will be used to update information on my database regarding the page it's one. So my problem is : django terminal tell me he receive the post correctly app_1 | [10/Jan/2023 17:44:50] "GET /nb_database/49/ HTTP/1.1" 200 11810 app_1 | [10/Jan/2023 17:44:54] "POST /nb_database/49/ HTTP/1.1" 200 11810 However , i made a quick function to know my information from the form are coming to the function and here is the problem. The function never print anything, i supposed the request never reach the function Here is the function (located on the app named 'nb_database' : def adding_address_to_db(request): print("OK REQUETE RECEIVE") the urls.py (on the same app): from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('nb_database', views.nb_database, name='nb_database'), path('nb_database/<int:annonce_id>/', views.detail, name='detail'), path('nb_database/<int:annonce_id>/', views.adding_address_to_db, name='adding_address_to_db'), ] And here is the form in HTML , for this example let's say it's on page mysite.com/nb_database/49/ <form action="" method="post"> {% csrf_token %} <input type="text" name="adding_address_to_db" placeholder="Entrez l'adresse" style="color: black;"> </form> Basically i want to be able to answer the form on the generated page (mysite.com/nb_database/49/) and stay on it once answered. Any help … -
GraphQL Unknown argument 'place' on field 'ReservationType.tour error
I'm trying to get a list of tour reservations to a certain place using variables and I'm getting the error stated in the title `query GetReservationByTour($tour_place: String!) { reservations{ id, tour(place: $tour_place){ id, place, } } }` Variables: { "tour_place": "Spain" } Reservation and Tour Type: `class TourType(DjangoObjectType): class Meta: model = Tour fields = ('id', 'max_number_of_participants', 'date_start', 'date_end', 'price', 'place', 'unit_price') class ReservationType(DjangoObjectType): class Meta: model = Reservation fields = ('id', 'user', 'dateOfReservation', 'amount_of_adults', 'amount_of_children', 'total_price', 'tour')` And resolvers: ` def resolve_tours(root, info, **kwargs): return Tour.objects.all() def resolve_reservations(root, info, **kwargs): return Reservation.objects.all()` Im expecting to get working query -
Expanding serialized objects
I have records that represent the amount of money spent on specific expense types: class ProjectExpense: expense_type = models.ForeignKey('ExpenseType') month = models.DateField() value = models.DecimalField(max_digits=10, decimal_places=2) Dollar values are input by quarter, so example entries might look like this: [ Expense Type: Travel Month: 2022-04-01 # Quarter 2 Value: $120,000 ], [ Expense Type: Capital - Hardware Month: 2022-07-01 # Quarter 3 Value: $60,000 ] When I report these entries via my REST API, I'd like to spread the dollar amount throughout the quarter. So, using the first example above, the entries would end up looking like: [ Expense Type: Travel Month: 2022-04-01 Value: $40,000 ], [ Expense Type: Travel Month: 2022-05-01 Value: $40,000 ], [ Expense Type: Travel Month: 2022-06-01 Value: $40,000 ], In this example, one line item has been expanded into three, spreading the cost equally. Is this kind of thing possible using the Django Rest Framework? Serializers only ever seem to operate on one object at a time, so they feel like the wrong thing to use. Of course I could roll my own view, but I'd like to take advantage of the pagination capability that DRF offers. Is there a fairly simple solution for a … -
How to properly filter model to update Plotly graph in Django?
Good day! I am trying based on a small example build a graph plotly Based on data from the model I then try to make the date interval selectable. Created a form and built it into the template. From this form in the template, I get data by start and end date in the views code. Next, I'm trying to filter the data from the model based on the date range retrieved from the template. And based on the filtered data from the model, "update" the graph on the template. But I get an error - Plotly does not get the necessary lists of data to update the plot. If you have any information, I will be very grateful. I have already used many options for solving the issue, but unfortunately nothing works for me. I would really appreciate any help. You may be able to find errors in this code. ValueError: Cannot accept list of column references or list of columns for both `x` and `y`. templates <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/html"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="GET" action="{% url 'chart' %}"> {{ form.as_p }} <button>Submit</button> </form> {{ chart|safe }} </body> </html> forms from datetime import date … -
How do I pull in data from multiple models into a specific model serializer?
I have this model that represents a bookmark or favorite. It has multiple foreign keys to other models. In the api I would like to pull in the data from each of the models that is referenced in the particular bookmark. The model: class Bookmark(models.Model): marktype = models.CharField(max_length=10) post = models.OneToOneField(Post, on_delete=models.CASCADE, null=True, blank=True) question = models.OneToOneField(Question, on_delete=models.CASCADE, null=True, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "bookmark" verbose_name_plural = "bookmarks" ordering = ["created_at"] db_table = "bookmarks" def __str__(self): return "{}'s bookmark".format(self.owner.username) I tried to use a SerializerMethodField but I get an error: 'NoneType' object has no attribute 'id' Here is the serializer class BookmarkSerializer(serializers.ModelSerializer): post = serializers.SerializerMethodField() question = serializers.SerializerMethodField() class Meta: model = Bookmark fields = '__all__' def get_post(self, obj): obj = Post.objects.get(id=obj.post.id) post = ShortPostSerializer(obj) return post.data def get_question(self, obj): obj = Question.objects.get(id=obj.question.id) question = ShortQuestionSerializer(obj) return question.data what am I doing wrong please? -
Dependent and Dynamic Dropdown form in js
Hey so I am trying to to make both a dynamic and dependent dropdown form. Essentially I want the second form to be dependent of the first forms option, and when you add a new form field I want it to generate a new div form with a different ID and and the option in the first form removed from the second and then third form. In the case the user only selects on form and doesn't decide to add a second or a third, I would like to still submit a NULL value through the form's that aren't submitted. Js is not my strong suit so any help would be appreciated <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="nativelangdrop"> <option value="1">Fashion Designer</option> <option value="2">Visual Artist</option> <option value="3">Clothing reseller</option> <option value="4">Musician</option> <option value="5">Videographer</option> <option value="6">Photographer</option> <option value="7">Dancer</option> <option value="8">Sculpter</option> </select> <span id="additional"></span> <input id="addBtn" type="button" value=" + "/> <hr /> <select id="genre"> <option value="1">Fashion Designer</option> <option value="2">Visual Artist</option> <option value="3">Clothing reseller</option> <option value="4">Musician</option> <option value="5">Videographer</option> <option value="6">Photographer</option> <option value="7">Dancer</option> <option value="8">Sculpter</option> </select> <span id="additional2"></span> <script> var total; // To auto limit based on the number of options // total = $("#nativelangdrop").find("option").length - 1; // Hard code … -
create pdf with each post django
Currently working on a django social media application where next to posting every post to the feed, the information of each upload should create a pdf document, containing caption, image, created_at and image_id. I´ve put the canvas into the upload functions, so that both will be created on the same click. So far, i get a pdf (can't get the attributes from the post into the pdf tho) and the post is uploaded just fine. How do I get the posted data into the pdf? And how do save that pdf to a folder within the project instead of starting an automatic download? The user should not be able to notice the pdf converting. It is just for back office - but very necessary due to the social media website being a part of a big installation. So how do I get these pdfs? Here is the code: views.py def upload(request): if request.method == 'POST': #user = request.user.username image = request.FILES.get('image_upload') caption = request.POST['caption'] new_post = Post.objects.create( image=image, caption=caption) new_post.save() #create pdf buffer = io.BytesIO() p = canvas.Canvas(buffer) p.drawString(100, 100, "Hello world.") p = request.FILES.get('post_pdf') p.drawText('caption') p.drawImage('image') p.showPage() p.save() buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='hello.pdf') return redirect('/') else: return redirect('/') models.py … -
Set a public/base URL for a Django which is behind a proxy
I've got a Django app which sits behind an API Gateway (Gravitee more specifically). In the API Gateway there is an API set up with the endpoint https://mycompany.com/myapi/v1 which points to the Django app, acting as a proxy. So a user would request https://mycompany.com/myapi/v1/resource and get a response from the Django app. The app uses Django REST framework (DRF) which returns URLs in its responses: [ { "url": "http://inner-host-machine:1337/v1/resource/1", "id": 1, "name": "Name 1" } ] But as you can see it is returning the URL of the host the Django app is on, not the API Gateway URL. I would like that URL to be https://mycompany.com/myapi/v1/resource. I tried setting the Host header on the proxy to mycompany.com but the results in the URL https://mycompany.com/v1/resource which is not correct. Setting the Host header to mycompany.com/myapi does not work because it's not a valid host. The domain name provided is not valid according to RFC 1034/1035. Is there a setting in Django or DRF which sets a public or base URL? So all URLs in responses would start with that URL. -
Using models between an App and API app in Django Rest framework
I'm going to create API with Django Rest Framework for an existing Django project. I would like to use models of existing app (product/models.py) in 'API/models.py'. Will that work smoothly as of using models across multiple apps using from product.models import item,... After importing I'll be creating serializers.py . Can anyone answer me whether this will work? -
Why the changes I made in the Django model not being reflected in the html form?
I have a field named 'amount' of type Floatfield. I changed it to DecimalField and ran makemigrations and migrate commands and it successfully generated 0002_alter_expense_amount.py file. This change is reflected in the database. But in the html form when I try to add new amount It's showing this message. When I tried the same from the admin panel it was successful What should I do to make the html form accept the decimal value? Is there anything I'm missing? models.py from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now class Expense(models.Model): amount = models.DecimalField(decimal_places=2, max_digits=10) date = models.DateField(default=now) description = models.TextField() owner = models.ForeignKey(to=User, on_delete=models.CASCADE) category = models.CharField(max_length=255) def __str__(self): return self.category class Meta: ordering = ['-date'] class Category(models.Model): name = models.CharField(max_length=255) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name views.py @login_required(login_url="/authentication/login") def add_expenses(request): categories = Category.objects.all() context = { 'categories': categories, 'values': request.POST } if request.method == 'POST': amount = request.POST['amount'] description = request.POST['description'] date = request.POST['expense_date'] category = request.POST['category'] Expense.objects.create(owner=request.user, amount=amount, date=date, category=category, description=description) messages.success(request, 'Expense saved successfully') return redirect('expenses') else: return render(request, 'expenses/add-expenses.html', context) html form <form action="{% url 'add-expenses' %}" method="post"> {% include 'partials/messages.html' %} {% csrf_token %} <div class="form-group mb-3"> <label …