Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Do it exist a helper function how data_get (Laravel) in Django?
The data_get function retrieves a value from a nested array or object using "dot" notation: $data = ['products' => ['desk' => ['price' => 100]]]; $price = data_get($data, 'products.desk.price'); // 100 More detail in Laravel Doc -
Django How can I log client ip address?
I save the logs to the file with this configuration. But I could not log the client ip address. I also want to keep logs for 1 day. Is there a simple method for this? Does anyone have an idea about this? django-requestlogging I tried this library but failed. I do not know if it is up to date. Thanks LOGGING ={ 'version':1, 'loggers':{ 'django':{ 'handlers':['file','file2'], 'level':'DEBUG' } }, 'handlers':{ 'file':{ 'level':'INFO', 'class': 'logging.FileHandler', 'filename':'./logs/info.log', 'formatter':'simpleRe', }, 'file2':{ 'level':'DEBUG', 'class': 'logging.FileHandler', 'filename':'./logs/debug6.log', 'formatter':'simpleRe', } }, 'formatters':{ 'simpleRe': { 'format': ' {asctime} {levelname} {message} ', 'style': '{', } } } -
Django restframework nested serializing
A Django beginner here. My problem simplified: I have models Vocabulary and Transaltion and I want endpoint .../api/vocabulary/pk to return something like: { "name": "some vocabulary", ...other fields "translations": [ {"word": "some word", "tarnslation": "the word in other language"} {"word": "some word2", "tarnslation": "the word2 in other language"} ... ] } My current code: View: @api_view(["GET"]) def vocabulary(request, pk): vocab = Vocabulary.objects.get(id=pk) serializer = VocabularySerializer(vocab, many=False) return Response(serializer.data) Serializers: class TranlationSerializer(serializers.ModelSerializer): class Meta: model = Translation fields = "__all__" class VocabularySerializer(serializers.ModelSerializer): translations = TranslationSerializer(many=True) class Meta: model = Vocabulary fields = ("name", ...other fields, "translations") -
Django failed to load resuorcese of static file (net::ERR_ABORTED 404 (Not Found))
I have changed settings of the base directory(telusko) of my Django framework and also added {%load static%} in index.html but then also the console of chrome shows GET http://127.0.0.1:8000/static/plugins/OwlCarousel2-2.2.1/owl.carousel.css net::ERR_ABORTED 404 (Not Found) code snippet of setting.py sitetravello contains all the HTML, CSS, js files and I have created assets for all the static file through cmd python manage.py collectstatic # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATICFILILE_DIRS = [ os.path.join(BASE_DIR, 'sitetravello') ] STATIC_ROOT = os.path.join(BASE_DIR,'assets') the main index.html file code is {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Travello</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="Travello template project"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{% static 'styles/bootstrap4/bootstrap.min.css' %}"> <link href="{% static 'plugins/font-awesome-4.7.0/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css"> ERROR IN CHROME Failed to load resource: the server response with the status of 404(not found) ERROR IN CHROME CONSOLE GET http://127.0.0.1:8000/static/plugins/OwlCarousel2-2.2.1/owl.carousel.css net::ERR_ABORTED 404 (Not Found) -
Custom Drop-down into the Wagtail editor
How can i add the custom drop-down options, on click of which wagtail editor adds the option to the editor text ? -
Access Pgadmin4 in Production within dockerized django application
I'm not sure how much sense it would make, but I was learning docker to deploy Django app with Gunicorn + Nginx + AWS. So far, it works fine, where I have unit tested it in production. My question is how can I access pgAdmin4 now? docker-compose.staging.yml version: '3.8' # networks: # public_network: # name: public_network # driver: bridge services: web: build: context: . dockerfile: Dockerfile.prod # image: <aws-account-id>.dkr.ecr.<aws-region>.amazonaws.com/django-ec2:web command: gunicorn djangotango.wsgi:application --bind 0.0.0.0:8000 volumes: # - .:/home/app/web/ - static_volume:/home/app/web/static - media_volume:/home/app/web/media expose: - 8000 env_file: - ./.env.staging networks: service_network: db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.staging.db networks: service_network: # depends_on: # - web pgadmin: image: dpage/pgadmin4 env_file: - ./.env.staging.db ports: - "8080:80" volumes: - pgadmin-data:/var/lib/pgadmin depends_on: - db links: - "db:pgsql-server" environment: - PGADMIN_DEFAULT_EMAIL=pgadmin4@pgadmin.org - PGADMIN_DEFAULT_PASSWORD=root - PGADMIN_LISTEN_PORT=80 networks: service_network: nginx-proxy: build: nginx # image: <aws-account-id>.dkr.ecr.<aws-region>.amazonaws.com/django-ec2:nginx-proxy restart: always ports: - 443:443 - 80:80 networks: service_network: volumes: - static_volume:/home/app/web/static - media_volume:/home/app/web/media - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d - /var/run/docker.sock:/tmp/docker.sock:ro labels: - "com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy" depends_on: - web nginx-proxy-letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion env_file: - .env.staging.proxy-companion networks: service_network: volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d depends_on: - nginx-proxy networks: service_network: volumes: postgres_data: pgadmin-data: static_volume: media_volume: certs: html: vhost: I can access … -
Django Serializer getting attribute from another model
I am working just for my experience and I stacked with the following problem. There are three models: Book, Chapter, and Publisher. Each model is related to one another with the foreign key. class Book(models.Model): name = models.CharField(max_length=64) publisher = models.ForeignKey('Publisher', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.name class Chapter(models.Model): name = models.CharField(max_length=128) book = models.ForeignKey(Book, related_name='books', on_delete=models.CASCADE) class Publisher(models.Model): title = models.CharField(max_length=128) description = models.TextField() def __str__(self): return self.title class Meta: ordering = ['title'] I want to serialize the data in PublisherDetailSerializer which should show their books and all chapters related to their books. Here are my serializers: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('id', 'name', 'publisher') def to_representation(self, instance): ret = super().to_representation(instance) return ret class ChapterSerializer(serializers.ModelSerializer): id = serializers.IntegerField() name = serializers.CharField(required=False) location = serializers.SerializerMethodField() class Meta: model = Chapter fields = ('id', 'name', 'location') def get_location(self, instance): serializer = BookSerializer(instance.author, context=self.context) return serializer.data class PublisherSerializer(serializers.HyperlinkedModelSerializer): books = BookSerializer(many=True, read_only=True) class Meta: model = Publisher fields = ('id', 'title', 'description', 'books') class PublisherDetailSerializer(PublisherSerializer): chapters = serializers.SerializerMethodField() class Meta: model = Publisher fields = ('id', 'title', 'description', 'books', 'chapters') def get_chapters(self, instance): serializer = ChapterSerializer(Chapter.objects.filter(location=instance.books.name), many=True, context=self.context) return serializer.data def to_representation(self, instance): ret = super().to_representation(instance) return … -
Error code: Unhandled Exception - pythonanywhere
the error log was to logn so I put it on pastebin I am not sure how to fix this at all any help is appriecated! heres the error log https://pastebin.com/raw/eZFSUXnX -
Is there any way I can access Django template variables and URL tags in a JS file so that the user can not inspect the data and links?
I want to excess Django template variables and URL tags from my javascript file. currently, I'm doing it like follows- <script> const addcommentlink = "{% url 'post:add_comment'%}"; const postid = '{{post.id}}'; const deletecommentlink = "{% url 'post:delete_comment' %}"; const editlikelink = "{% url 'post:edit_like' %}"; const profilelink = "{% url 'instagram:profile' 'name' %}"; </script> <script src="{% static 'post/js/post_details.js' %}"></script> but I want to access it directly from the post_details.js file. Is there any way to do that? -
Call function that uses newly created model object (instance) when save model object in DJANGO
class Experience(models.Model): teacher = models.ForeignKey(User, on_delete=models.CASCADE) classroom = models.ForeignKey(Classes, on_delete=models.DO_NOTHING, verbose_name ="Clase") project = models.ForeignKey(Project, on_delete=models.DO_NOTHING, related_name="project_exp", verbose_name ="Experiencia") project_phases = ChainedManyToManyField( ProjectPhases, horizontal=True, verbose_name ="Fases de la experiencia", chained_field="project", chained_model_field="project") created_at = models.DateTimeField(auto_now_add=True, verbose_name = "Creado en") updated_at = models.DateTimeField(auto_now=True, verbose_name = "Actualizado en") class Meta: verbose_name = "Experiencia" verbose_name_plural = "Experiencias" default_related_name = 'experience' ordering = ['id'] def __str__(self): return f'Experiencia {self.id} - {self.project}' def save(self, *args, **kwargs): super(Experience, self).save(*args, **kwargs) ## Call a function with the newly created object @receiver(post_save, sender=Experience) def create_evaluations(sender, instance, **kwargs): if instance: create_experience_evaluation(instance) -
Package not found at IN heroku web application
I have a DJANGO web application which was deployed via heroku, it runs a particular process on media files. Whenever a user submits a form containing a file, the application saves the file in the database hence giving it a particular URL e.g https://my-special-app-name.herokuapp.com/media/documents/2020-10-08/test1.docx. Once the file is saved, the application uses celery to perform some tasks on the saved file which will then be saved in my database. I was able to get celery working by including worker: celery -A myprojectName worker -l info in my Procfile, then heroku ps:scale worker=1 after git push heroku master as stated in the heroku docs. Everything seems to work fine, celery receives tasks from the redis server but it keeps logging the same type of error e.g (Package not found at '/app/media/documents/2020-10-08/test1.docx') and the web application doesn't perform the process.I am able download the file from the server by accessing the url e.g https://my-special-app-name.herokuapp.com/media/documents/2020-10-08/test1.docx, unfortunately I have no idea why celery is receiving the app url with (/app/) preceding everything and not performing the desired process.It worked fine in development with an example url of http://127.0.0.1:8000//media/documents/2020-10-08/test1.docx. I don't know how to fix the error and I will really appreciate your help. enter … -
Display fields from one model in another in Django Admin connected with a Foreignkey
I have two models, one for uploaded files and one for comments. I now want to display the comments in the Admin view of each uploaded file. So for example, if I upload a file TestFile1, once I click on it in the Uploaded view in Django admin, I want to have all of the comments associated with that file. Is this possible? class Uploaded(models.Model): objects: models.Manager() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="users") file = models.FileField(upload_to=user_directory_path) def __str__(self): return f"{self.description} {self.file}" class Comment(models.Model): objects: models.Manager() file = models.ForeignKey('Uploaded', on_delete=models.CASCADE, related_name='comments') text = models.TextField() def __str__(self): return self.text -
nginx as a proxy to react and django backend
Hello guys Im very new to nginx, recently I have been attempting to connect nginx to my django backend and react frontend but have been facing some issues. What im trying to achieve is that a user will be able to access my nginx proxy at port 8080 or the default port, and be served with my built react application. There after any api calls will then be routed to my django backend that is listening at port 8000. Here is my nginx config file : upstream api { server backend:8000; } server { listen 8080; location /test/ { proxy_pass http://api$request_uri; } location /api/ { proxy_pass http://api$request_uri; include /etc/nginx/uwsgi_params; } location /static/rest_framework/ { proxy_pass http://api$request_uri; } # ignore cache frontend location ~* (service-worker\.js)$ { add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'; expires off; proxy_no_cache 1; } location / { root /var/www/frontend; try_files $uri /index.html; } } and here is my docker-compose file for production: version: "3.7" services: postgres: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=user - POSTGRES_DB=user backend: build: ./backend volumes: - static_data:/vol/web env_file: - ./.env.dev depends_on: - postgres frontend: tty: true build: ./frontend command: ["yarn","build"] volumes: - ./frontend:/usr/src/frontend redis: restart: always image: redis:latest ports: - "6379:6379" … -
How to filter on a Sum() containing F()s?
Suppose I have those two models: class Category(models.Model): name = models.CharField(max_length=32) class Item(models.Model): category = models.ForeignKey('Category', related_name='items', on_delete=models.CASCADE) quantity = models.SmallIntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) Then I'd like to query all categories to find out how each is performing with its items: (Category.objects.all() .annotate( sales_yesterday=Sum('items__quantity', filter=Q(items__created_at__date=yesterday)), revenue_yesterday=Sum(F('items__price') * F('items__quantity'), output_field=DecimalField()), sales_today=Sum('items__quantity', filter=Q(items__created_at__date=today)), revenue_today=Sum(F('items__price') * F('items__quantity'), output_field=DecimalField()) ) ) But revenue_yesterdayand revenue_today don't filter for yesterday and today respectively, unlike sales_yesterday and sales_today which do. Meaning the revenue_* annotations do their aggregations over the entire table and that's not what I want. The challenge I'm facing is how to apply those needed filters on my revenue_* annotations and one of the approaches I've tried is something similar to what I've done with my sales_* annotations: ( revenue_today=Sum(F('items__price') * F('items__quantity'), filter=Q(items__created_at__date=today), output_field=DecimalField()) ) Which only throws up an error: FieldError: Expression contains mixed types. You must set output_field. And I'm not sure what I should do since I already set output_field, and it's not clear to me if I'm putting that filter in the right place or in the right way inside Sum(). How do I solve this? -
Django one-to-one relationships and initial values
I´m learning to code and I´m trying to make a small app using Django. I have two models, Groups and Lists. The idea is that a user creates a Group, and then a List of students (which uses a formset). class Groups(models.Model): name = models.CharField(max_length=50) students_number = models.IntegerField() def __str__(self): return self.name class List(models.Model): name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) second_last_name = models.CharField(max_length=50) group = models.OnetoOneField(Groups, max_length=50, on_delete=models.CASCADE, default="Grupo") def __str__(self): return self.name All the students on that list should be assigned to the group you just created. I already set the one-to-one relationship, but in this way, the user has to choose the group for every student (it is supposed that ALL of these students belong to this group, so I think doing this repeatedly is unnecessary). This is the view: def addList(request): AddListFormSet = modelformset_factory(List, fields=("name", "last_name", "second_last_name", "group"), extra=2,) if request.method == "POST": form = AddListFormSet(request.POST) form.save() return redirect("/grupos") form = AddListFormSet(queryset=List.objects.none()) return render(request, "new_list.html", {"form": form}) How can I pre-assign the group that I just created for all the students that I capture in the next step? -
aggregate method in Django
I am new to Django and when i use Aggregate method , it returns something like {'max__age' : 35} but I need to display just the number (35 in this example). How can I solve it? Thanks all. -
No 'Access-Control-Allow-Origin' header is present on the requested resource React Django error
Access to fetch at 'http://localhost:8000/api/product/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. -
Large file upload to Django Rest Framework
I try to upload a big file (4GB) with a PUT on a DRF viewset. During the upload my memory is stable. At 100%, the python runserver process takes more and more RAM and is killed by the kernel. I have a logging line in the put method of this APIView but the process is killed before this method call. I use this setting to force file usage FILE_UPLOAD_HANDLERS = ["django.core.files.uploadhandler.TemporaryFileUploadHandler"] Where does this memory peak comes from? I guess it try to load the file content in memory but why (and where)? More information: I tried DEBUG true and false The runserver is in a docker behind a traefik but there is no limitation in traefik AFAIK and the upload reaches 100% I do not know yet if I would get the same behavior with daphne instead of runserver -
Moving the login panel to center of screen
While practicing Django, I want to mess around with CSS. In this case, I am creating a login page. The login form is currently appearing at the top-left corner of the page. How to I modify to make it right in the center? I am not good with CSS and could use some pointers. Here are my django files. I try to manipulate the panel-default but it does not work. base.html {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/base.css" %}" rel="stylesheet"> </head> <body> <div id="header"> <span class="logo">My Page</span> </div> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> login.html (which extends the base.html) {% extends "base.html" %} {% block title %}Log-in{% endblock %} {% block content %} <div class="panel panel-default"> <h1>Log-in</h1> <form method="post"> {{ form.as_p }} {% csrf_token %} <p><input type="submit" value="Log in"></p> </form> </div> {% endblock %} base.css @import url(http://fonts.googleapis.com/css?family=Muli); body { margin:0; padding:0; font-family:helvetica, sans-serif; } .panel-default{ position: absolute; top: 50%; left: 50%; } #header { padding:10px 100px; font-size:14px; background:#12c064; color:#fff; border-bottom:4px solid #1cdf78; overflow:auto; } -
how can make a custom filter with django-filter
Help!... I need to make a search engine that filters and obtain the results depending on the parameters that are sent from the front end, for example if they send the 3 parameters (Repository, family and array of Products) it would have to iterate through the array products and get the stock of that product by repository and family (group) I already did it with queries like these: for product in products["entries"]: product_id = product["id"] try: query = Stock.objects.filter(product__family=family,product__id=product_id) except Stock.DoesNotExist: query = None if query: try: query_to_return = StockSerializer(query,many=True).data But then I had a lot of problems and I couldn't find a way to paginate the data because there are many records, so I would like to do it with Django-Filter. class Stock(CustomModel): product = models.ForeignKey(Product, on_delete=models.PROTECT, related_name='stocks', verbose_name=("Producto")) repository = models.ForeignKey(Repository, on_delete=models.PROTECT, related_name='stocks', verbose_name=("Almacén")) date = models.DateTimeField(auto_now=True) class Product(CustomModel): name = models.CharField(max_length=100, unique=True, verbose_name=("Nombre")) codebar = models.CharField(max_length=20, null=True, blank=True, verbose_name=("Código de Barras")) brand = models.ForeignKey(Brand, null=True, blank=True, on_delete=models.PROTECT, related_name='products', verbose_name=("Marca")) model = models.CharField(max_length=50, verbose_name=("Modelo")) data_serie = models.CharField(max_length=50, verbose_name=_("Serie de Datos")) ....another fields.. class Repository(CustomModel): name = models.CharField(max_length=100, unique=True,verbose_name=("Nombre")) code = models.CharField(("Clave"), max_length=20, null=True, blank=True) repositories_group = models.ForeignKey(RepositoriesGroup, verbose_name=("Grupo"), on_delete=models.PROTECT, related_name='repositories', null=True, blank=True) description = models.TextField(("Descripción"), null=True, blank=True) .......Another … -
How do I create this complex user filter in Django 2.0?
I have several overlapping categories. I wanted to search and filter each person according to their type, specialty and place of residence class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) gender = models.CharField(choices = GENDER_CHOICES) country = models.CharField(choices = COUNTRY_CHOICES) city = models.CharField(choices = CITY_CHOICES) class License(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) types = models.CharField( choices = TYPES) specialization = models.CharField( choices = SPECIALIZATION_CHOICES) and this is my filter viws def search(request): profiles = Profile.objects.all() if request.method == 'POST': types = request.POST['types'] specialization = request.POST['specialization'] country = request.POST['country'] city = request.POST['city'] gender = request.POST['gender'] if types or specialization or username or country or city or gender: license_match = License.objects.filter( Q(types__exact = types)| Q(specialization__exact = specialization) ) profile_mutch = Profile.objects.filter( Q(country__exact = country)| Q(city__exact = city)| Q(gender__exact = gender) ) if license_match or profile_mutch: license_match = License.objects.filter( Q(types__exact = types)| Q(specialization__exact = specialization) ) profile_mutch = Profile.objects.filter( Q(country__exact = country)| Q(city__exact = city)| Q(gender__exact = gender) ) mutch = profile_mutch and license_match paginator = Paginator(mutch, 60) page = request.GET.get(mutch, 1) page_number = request.GET.get(page) page_obj = paginator.get_page(page_number) return render(request, 'search_result.html', {'page_obj': page_obj, 'result': mutch, 'profiles': profiles}) else: messages.error(request, 'No result found.') else: return HttpResponseRedirect('result') else: profile_mutch = Profile.objects.all() license_match = License.objects.all() … -
How to generate a "fake" slug in Django
I saw in a video I didn't save that you could do something like this: www.mysite.com/post/12345/this-is-a-title Where the 12345 is the id and what actually is used to do the query and the this-is-a-tilte part is automatically assigned when loading the page and you can actually write whatever you want there and will still load the page. How do I set this up in my path and do I still need a SlugField? -
Django: Cache function
I created the following serializer where I call the function _calculate_image_dimensions twice. I now tried @cachedproperty but doesn't work because I have to pass the values width, height. However, they will not change for get_width and get_height. Is there a way to make sure the calculation only computes once? class IntegrationImageSerializer(serializers.ModelSerializer): width = serializers.SerializerMethodField() height = serializers.SerializerMethodField() class Meta: model = IntegrationImage fields = ("image", "width", "height") def _calculate_image_dimensions(self, width, height) -> int: MAX_IMAGE_SIZE = 350 aspect_ratio = width / height if width > height: width = MAX_IMAGE_SIZE height = width / aspect_ratio else: height = MAX_IMAGE_SIZE width = height * aspect_ratio return round(width), round(height) def get_width(self, obj: IntegrationImage) -> int: width, height = self._calculate_image_dimensions( obj.image.width, obj.image.height ) return width def get_height(self, obj: IntegrationImage) -> int: width, height = self._calculate_image_dimensions( obj.image.width, obj.image.height ) return height -
Python and Django TimeZone Format Postgres
I have a line of code here that works on my dev server for Django and Python using SQL Lite, however when I upload my code it gives me an error about my time zone . Here is my Code. Postgres doesn't like the %z at the end , however SQL Lite its fine. What do I do to fix this on my Heroku Postgres Production Environment? Thanks new_event.start = datetime.strptime(str(obj.start_date) ,'%Y-%m-%d %H:%M:%S%z') Error Message: time data '2020-10-08 12:17:51-04:00' does not match format '%Y-%m-%d %H:%M:%S%z' -
Django Form Dropdown HTML code not working
I am trying to achieve a dropdown list of fields using my MODELS.py. When app is run HTML page displays OK and some of the inputs fields works fine. But the dropdown fields doesn't appear correctly and appear as TEXT only on the page. I have tried all sorts of HTML formating but still no success. Also I have searched thru NET but there isint much help available as well. Kindly check and help pls. MODELS.PY from django.db import models from django.contrib.auth.models import User # Create your models here. class Vehicle(models.Model): VEHICLE_STATUS_CHOICES = ( ('B', 'Booked'), ('NB', 'Not Booked'), ) INSURANCE_STATUS_CHOICES = ( ('U','Updated'), ('NU','Not Updated'), ) VEHICLE_TYPE_CHOICES = ( ('P','Passenger'), ('T','Truck'), ('C','Construction'), ) FUEL_TYPE_CHOICES = ( ('P','Petrol'), ('D','Diesel'), ) owner = models.ForeignKey(User,default=None,on_delete=models.CASCADE) cost_per_km = models.DecimalField(max_digits=20,default=0,decimal_places=2) price = models.DecimalField(max_digits=20,default="0",decimal_places=3) registration_plate = models.CharField(max_length=200,default='') vehicle_status = models.CharField(max_length=2, choices=VEHICLE_STATUS_CHOICES, default='NB') insurance_status = models.CharField(max_length=2,choices=INSURANCE_STATUS_CHOICES, default='NU') no_of_km_travelled = models.DecimalField(max_digits=20,default=0,decimal_places=0) fuel_type = models.CharField(max_length=1,default='P',choices=FUEL_TYPE_CHOICES) mileage = models.DecimalField(max_digits=20,default=0,decimal_places=0) vehicle_type = models.CharField(max_length=1,choices=VEHICLE_TYPE_CHOICES, default='P') image=models.ImageField(upload_to="vehicle_image",default="default.png",blank=True) def __str__(self): # return self.registration_plate return self.vehicle_type **Forms.py** from django import forms from .models import Vehicle class VehicleForm(forms.ModelForm): class Meta: model=Vehicle # fields = '__all__' fields = ('cost_per_km', 'price', 'registration_plate', 'no_of_km_travelled', 'mileage', 'vehicle_type', 'fuel_type', 'insurance_status', 'image') ----------------------------------------------------------------------------------------------- **Views.py** from django.shortcuts import render,redirect,get_object_or_404 from django.http import …