Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax form processing
After submitting a form to Django, it takes about 3 seconds to process I need an Ajax script that will redirect the user to an intermediate page where he will wait for a response from Django. Django got a new redirect after receiving the response I tried to solve this problem with Django, but I can't do 2 redirects in one view -
Save a model in the database with multilevel nested serializers in Django
i need help with my rest Api,with Django rest Framework and Django 4. My Api is for reading texts in foreign language, i'm trying to save a new MyTexts model in the database (Sqlite). I think the problem comes from the serializer TextSerializer. I have these models and serializers(correct them if they are wrong): #language/models.py from django.db import models # Model for a Language class Language(models.Model): LgName=models.CharField(max_length=40) LgDict1URI=models.CharField(max_length=200) LgDict2URI=models.CharField(max_length=200) LgGoogleTranslateURI=models.CharField(max_length=200) LgExportTemplate=models.CharField(max_length=1000) LgTextSize=models.IntegerField() LgRemoveSpaces=models.BooleanField() LgRightToLeft=models.BooleanField() LgSkills=models.TextField() def __str__(self) -> str: return self.LgName #language/serializer.py from rest_framework import serializers from .models import Language class LanguageSerializer(serializers.ModelSerializer): class Meta: model=Language fields='__all__' #learner/model.py from django.db import models from django.contrib.auth.models import AbstractUser from language.models import Language # Model for a Learner(a user) class Learner(AbstractUser): SelLanguage=models.OneToOneField(Language,on_delete=models.CASCADE,null=True,related_name="SelLanguage") is_teacher=models.BooleanField(default=False) can_post=models.BooleanField(default=False) level=models.IntegerField(default=0) def __str__(self) -> str: return self.username #learner/serializer.py from django.contrib.auth import authenticate, get_user_model from rest_framework import serializers from language.models import Language from language.serializers import LanguageSerializer from .models import Learner User = get_user_model() class UserSerializer(serializers.ModelSerializer): SelLanguage=LanguageSerializer(many=False,read_only=True) def create(self, validated_data): SelLanguage = validated_data.pop('SelLanguage') user = Learner.objects.create(**validated_data) lg=Language.objects.get(Learner=user, **SelLanguage) user.SelLanguage=lg user.save() return user class Meta: model = Learner fields = '__all__' #myTags/models.py from tkinter import CASCADE from django.db import models from accounts.models import Learner from language.models import Language # Model for optional tags … -
How to integrate novnc client inside django project
I have a couple virtual machines running inside proxmox but I found out you can use the novnc client to connect to these virtual machines and use the console in a web browser. This is perfect for different clients I work with. I already have a small django project that shows the running nodes and vm's inside of them. Now I wanted to include de js library by novnc. However I can't really find a lot of information online and since my coding experience is not that high I don't really know what I am doing wrong. I used this outdated repo and tried to see if I can find out how to get it to work. https://github.com/missuor/novnc-proxy-django for now I have a view that call the api of proxmox. /api2/json/nodes/{node}/lxc/{vmid}/vncproxy to be precise. this returns a ticket, port, cert, user and upid. Now I am not sure if I just need to call the vncproxy or use these variable to open a websocket by /api2/json/nodes/{node}/lxc/{vmid}/vncwebsocket. The django view i currently have just call the vncproxy and sends the values to the rendered template. This template I used from the repo metioned above, but I just don't know why I … -
Queryset for search by username and display_name In Django Rest Framework
I'm trying to search users by their usernames and display names. I have used that for the starting match. search_obj = User.objects.exclude(user_uuid=token_user_uuid).filter(Q(display_name__istartswith=search_name) | Q(username__istartswith=search_name) ).order_by('-created_on')[:10] I get the answer same as I want but the problem is if the display name is William Welch and I search for Welch It should return that user also, but it does not return that user. -
Calling a model's method inside a serializer and handling a received object
I'm supposed to write an API for the endpoints. It should be an application inside an existing project. I should work with its models and i'm not allowed to alter them in any way. The project consists of multiple application, and some application have their own models. There is an exempt from CategoryMetall/models.py in the CatalogNew application: class CategoryMetall(MPTTModel): position = models.ForeignKey( Menu, on_delete=models.CASCADE, verbose_name="foo", blank=True, null=True, ) subPosition = TreeForeignKey( "self", on_delete=models.CASCADE, verbose_name="bar", blank=True, null=True, ) def parent(self): if self.subPosition: return self.subPosition else: return self.position As i understood, the parent() method is supposed to return an object of either a CatalogNew model, or a Menu model. A Menu model is a model of another application from the project. Here is an exempt from it as well: Menu/models.py class Menu(models.Model): parent = models.ForeignKey( "self", on_delete=models.CASCADE, verbose_name="parent category", null=True, blank=True, ) So, i figured that in order to get a parent category i'm supposed to use the CategoryMetall.parent() method written by some other developer. The issue is, i'm also supposed to somehow serialize it. I have written a serializer in my serializers.py: class CategoryMetallSerializer(serializers.HyperlinkedModelSerializer): parentCategory = serializers.ReadOnlyField(source='parent') class Meta: model = CategoryMetall fields = ['id', 'name', 'parentCategory'] And a view for … -
Hosting Django Docker Postgres on DigitalOcean Droplets
I am new to deploying to DigitalOcean. I recently created a Droplet, into which I will put my Django API to serve my project. I saw that the droplet I rent has 25 GB of memory, and for the actual size of my project, it could be a good fit for the database. I run my entire code with Docker Compose, which handles Django and PostgreSQL. I was wondering if it is a good idea to store all the data in the PostgreSQL created by Docker Image, and stored in the local memory of the droplet, or do I need to set up an external Database in Digital Ocean? Technically I think that could work, but I don't know if it is safe to do, if I will be able to scale the droplets once the size scales, or if I will be able to migrate all the data into an external database, on digital ocean, a managed PostgreSQL all my data without too many problems. And if I save it all locally, what about redundancy? Or can I clone my database on a daily basis in some way? If someone knows about that and can help me, please I … -
ModuleNotFoundError: No module named 'config' outside django app
I am using cookiecutter-django on my project and having problem while trying to import settings from config outside app. Getting error ModuleNotFoundError: No module named 'config' Project structure project ┣ .envs ┃ ┗ .local ┃ ┃ ┣ .bot ┃ ┃ ┣ .django ┣ bot ┃ ┣ __init__.py ┃ ┗ bot.py ┣ compose ┃ ┣ local ┃ ┃ ┣ django ┃ ┃ ┃ ┣ Dockerfile ┃ ┃ ┃ ┗ start ┃ ┃ ┗ pytelegrambot ┃ ┃ ┃ ┣ Dockerfile ┃ ┃ ┃ ┗ start ┣ config ┃ ┣ settings ┃ ┃ ┣ __init__.py ┃ ┃ ┣ base.py ┃ ┃ ┣ local.py ┃ ┣ __init__.py ┃ ┣ urls.py ┃ ┗ wsgi.py ┣ project ┃ ┣ app ┃ ┃ ┣ migrations ┃ ┃ ┃ ┗ __init__.py ┃ ┃ ┣ admin.py ┃ ┃ ┣ apps.py ┃ ┃ ┣ signals.py ┃ ┃ ┣ models.py ┃ ┃ ┗ views.py ┣ requirements ┃ ┣ base.txt ┣ README.md ┣ local.yml ┣ manage.py bot.py import telebot from config.settings.base import env bot = telebot.TeleBot(env('BOT_TOKEN')) def send_welcome(message): print(message) if __name__ == '__main__': bot.infinity_polling() signals.py from bot.bot import send_welcome @receiver(post_save, sender=Model) def translate(sender, instance, created, **kwargs): send_wlcome("Hi") Here I am sending message on telegram bot when object created. If I try to … -
Python - What is wrong with this fucniton declaration?
def convert(self, path: str): ^ SyntaxError: invalid syntax i am getting a SyntaxError. I checked online and saw this is how it should be declared. what is wrong with this? -
celery beat schedule: why one same task is completed in different time durations?
I have used celery-beat to get data from about 30 different APIs and save them in database. There are two prblems: first: why it takes so long to do the task (i thought it shouldn't take more than 2-3 seconds)? second: why a single task takes different time durations to be done? celery: terminal: -
Django + vue.js importing modules problem while using vue-simple-context-menu
How can I import modules for VueJS app in a template, rendered by Django. I'm trying to import module vueSimpleContextMenu. for ref- https://www.npmjs.com/package/vue-simple-context-menu trying to use this library but it requires import statement which I am unable to use. This is my situation: archiveModal.html: <template id="archiveModal"> <ul> <li v-for="item in items" @click.prevent.stop="handleClick($event, item)" class="item-wrapper__item" > {{item.name}} </li> </ul> <vue-simple-context-menu element-id="1" :options="options" ref="vueSimpleContextMenu" @option-clicked="optionClicked" /> <template> archiveModal.js const archiveModal = { delimiters: ['[[', ']]'], template: '#archiveModal', data() { return { options: [ { name: 'Duplicate', slug: 'duplicate', }, { type: 'divider', }, { name: 'Edit', slug: 'edit', }, { name: '<em>Delete</em>', slug: 'delete', }, ], }; }, methods: { handleClick(event, item) { this.$refs.vueSimpleContextMenu.showMenu(event, item) }, optionClicked(event) { window.alert(JSON.stringify(event)) }, }, component: { 'vue-simple-context-menu': VueSimpleContextMenu, }, }; On Github it requires import VueSimpleContextMenu from 'vue-simple-context-menu'; import 'vue-simple-context-menu/dist/vue-simple-context-menu.css'; Is there a way to use that in django template and where am I doing the mistake? -
Returns only the last data. I need all the data Django python
return response is only sending the last response in the for loop I need all the data in postman data=[] data.append({"coll_code":coll_code,"coll_name":coll_name,"coll_location":coll_location,"branch_name":branch_name,"branch_id":curentbranch_id,"extention2021":c1, "seconground2021":c2, "firstround2021":c3, "extention2020": c4, "seconground2020":c5, "firstround2020":c6, "extention2019": c7, "seconground2019":c8, "firstround2019":c9}) return Response(data) -
How to use django-autocomplete-light and django-hacker to make a chained dropdown in django admin?
I have 3 models 1) university 2) courses and 3) enquiry. My enquiry model has a foreign key to "course". And Course has a foreign key to the university. I only want to show the courses related to that university while adding an enquiry. I tried django-smart-select but failed to do so. I tried This answer but I dont understand the logic and failed to implement in my project. this is my models.py file class university(models.Model): univ_name = models.CharField(max_length=100) country = CountryField(blank=True, null=True) univ_desc = models.CharField(max_length=1000) univ_logo = models.ImageField(upload_to="media") univ_phone = models.CharField(max_length=10, blank=True) univ_email = models.EmailField(max_length=254, blank=True) univ_website = models.URLField(blank=True) assigned_users = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, default="") def __str__(self): return self.univ_name class Meta: verbose_name_plural = "Universities" class Course(models.Model): university = models.ForeignKey(university, on_delete=models.CASCADE) course_name = models.CharField(max_length=100) course_levels = models.ForeignKey(course_levels, on_delete=models.CASCADE) intake = models.ForeignKey(intake, on_delete=models.CASCADE) documents_required = models.ForeignKey(documents_required, on_delete=models.CASCADE) course_requirements = models.ForeignKey(course_requirements, on_delete=models.CASCADE) Active = models.BooleanField() def __str__(self): return self.course_name class enquiry(models.Model): student_name = models.CharField(max_length=100) student_phone = models.CharField(max_length=10) student_email = models.EmailField() student_address = models.TextField() current_education = models.ForeignKey(current_education, on_delete=models.CASCADE) country_interested = CountryField(blank=True, null=True) university_interested = models.ForeignKey(university, on_delete=models.CASCADE) course_interested = models.ForeignKey(Course, on_delete=models.CASCADE, limit_choices_to={'Active':True}) level_applying_for = models.ForeignKey(course_levels, on_delete=models.CASCADE) intake_interested = models.ForeignKey(intake, on_delete=models.CASCADE) assigned_users = models.ForeignKey(User, on_delete=models.CASCADE, default="", limit_choices_to={"is_active": True}) enquiry_status = models.ForeignKey(enquiry_status, on_delete=models.CASCADE, default="") course_interested= ChainedForeignKey(Course,chained_field= 'university_interested',chained_model_field= … -
Django Unit test is written but coverage report says there are missing statements
I try to get coverage reports using a simple django model. Unit test for model was written but report says there are missing statements. The model: from django.db import models from model_utils import FieldTracker from generics.base_model import BaseModelMixin class AModel(BaseModelMixin): record_name = models.CharField(max_length=255) tracker = FieldTracker() class Meta(BaseModelMixin.Meta): db_table = 'a_model_records' def __str__(self): record _name = self. record_ name if record_name is None: record_name = "N/A" return record name The unit test: class TestAModel(TestCase): def setUp(self): super().setUp() def test_allowed_domain_model(self): record_name = "some name" is_active = True user = User.objects.first() record = AModel.objects.create( record_name=record_name, is_active=is_active, created_by_id=user.id, ) self.assertEqual(str(record), record_name) self.assertEqual(record.name, record_name) self.assertEqual(record.is_active, is_active) The command line code I run: source activate set -a source local.env set +a coverage run --source="unit_test_app" --rcfile=.coveragerc project/manage.py test -v 2 coverage report coverage html The coverage configuration is like this: [run] omit= */migrations/* */tests/* */manage.py */apps.py */settings.py */urls.py */filters.py */serializers.py */generics/* [report] show_missing = true Coverage result shows missing statements: This is the simplest example. There are many ignored functions by coverage which descends percentage average, but actually covered by unit tests. Why does coverage act like this? -
Can I provide automatically current user in Django rest API like this?
I have a Django rest api. In my model I have a user as a foreign key. When I do a post with the, I do not want that the user needs to provide his own user. But if the user does not provide his user credentials, the serializer won't be valid and then won't be saved. I have found that we can access to serialized dat before validation with initial_data so I am doing like this to save the user automatically from the token provided. The user need to provide everything except his own user. Is it ok or am I doing something not recommended ? @api_view(['POST']) @permission_classes([IsAuthenticated]) def add_mesure(request): serializer = MesureSerializer(data=request.data) serializer.initial_data['user'] = request.user.id if serializer.is_valid(): serializer.save() return Response(serializer.data) -
I am using Django and I want to encrypting my URL to secure it can some one help me
I am using Django rest framework and I want to encrypting my URL to secure it, I want to encrypt only one URL which is section URL I create the encryption file but I do not know tho use it inside the views.py here is my code views.py class ChapterSectionList(generics.ListAPIView): serializer_class=SectionSerializer def get_queryset(self): chapter_id=self.kwargs['chapter_id'] chapter=models.Chapter.objects.get(pk=chapter_id) return models.Section.objects.filter(chapter=chapter) encryption_util.py from cryptography.fernet import Fernet import base64 import logging import traceback from django.conf import settings def encrypt(text): try: txt = str(txt) cipher_suite = Fernet(settings.ENCRYPT_KEY) encrypted_text = cipher_suite.encrypt(txt.encode('ascii')) encrypted_text = base64.urlsafe_b64encode(encrypted_text).decode("ascii") return encrypted_text except Exception as e: print(e) logging.getLogger("error_logger").error(traceback.format_exc()) return None def decrypt(txt): try: txt = base64.urlsafe_b64encode(txt) cipher_suite = Fernet(settings.ENCRYPT_KEY) decoded_text = cipher_suite.decrypt(txt).decode("ascii") return decoded_text except Exception as e: logging.getLogger("error_logger").error(traceback.format_exc()) return None -
Django : Reduce number of possible choices based on previous model choice inputs
I have multiple models : class Game(models.Model): name = models.CharField('Nom du jeu', max_length=100) logo = models.ImageField('Logo', blank=True, upload_to='game_logos') class League(models.Model): game = models.ForeignKey(Game, verbose_name='Jeu', null=True, on_delete=models.SET_NULL) league = models.CharField('Ligue', max_length=20) hexcolor = models.CharField('Code couleur Hex', max_length=7, blank=True, default='#000000') class Event(models.Model): game = models.ForeignKey(Game, verbose_name='Nom du jeu', null=True, on_delete=models.SET_NULL) event_type = models.CharField(verbose_name="Type d'événement", max_length=50, choices=type_course) league = models.ForeignKey(League, verbose_name='Ligue', null=True, on_delete=models.SET_NULL) circuit = models.ForeignKey(Circuit, verbose_name='Circuit', null=True, on_delete=models.SET_NULL) event_date = models.DateTimeField(verbose_name="Date de la course") The logic here is, that we have races, that take place place in a certain game, and in a certain league. The thing is, I can have different games that have their own league, independent from the league of the other games (Formula 1 will have League A, B and C, and another game will have League 1, 2 and 3). So when I set up a new event, as soon as I choose the game, I want to get the leagues associated with this game, not all of them. How can I filter the choices of the leagues based on the game input ? -
Pylint Fatal error while checking on every python file
/Users/..../coding/projects/.../.../campaign/permissions.py: Fatal error while checking /Users/..../coding/projects/.../.../campaign/permissions.py'. Please open an issue in our bug tracker so we address this. There is a pre-filled template that you can use in '/Users/.../Library/Caches/pylint/pylint-crash-2023-01-09-17-28-38.txt'. I have just configured pylint on vscode. But have this eeror apper on the first line of every python file.enter image description here How can i fix this? -
Should I use oneToMnay or ManyToMany in django
I am new in django and trying to create a website where I can search for vehicles and see what parts I have for this vehicle. I have two databases, one with vehicles and one with parts: class Vehicle(models.Model): vehicle_id = models.BigIntegerField(primary_key=True) vehicle = models.CharField(max_length=255) def __str__(self): return self.vehicle class Part(models.Model): part_id = models.BigIntegerField(primary_key=True, db_column='part_id') part_name = models.CharField(max_length=255, db_index=True, null=True) catalog_code = models.CharField(max_length=255, null=True) price = models.CharField(max_length=255, default=None, null=True) description = models.CharField(max_length=255, default=None, null=True) vehicle_id = models.ForeignKey(Vehicle, on_delete=models.PROTECT, null=True) def __str__(self): return self.part_name Now I using oneToMany, but can't figure out if it is correct and how can I see all parts for one vehicle -
pictures are not shown in django production site
I have a django website in production. Everything works fine except pictures are not shown. The pictures are not stored in the database but located in a different location on the server. When I inspect the site than the url is shown correctly This is in my template {% if img_url != "" %} <img scr="{{ img_url|safe }}" width="500" height="300"> <br> {% else %} {% endif %} This is in my view how I generate the url. The pictures are located in each program and link_picture is just the name and ending of that picture e.g. picture1.png url = os.path.join(settings.MEDIA_ROOT,project.get_program_display(),project.link_picture) if os.path.exists(url): img_url = url else: img_url = "" This is in my settings STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join('/mnt/data/import', 'media') This is in my apache2 config file Alias /static /home/user1/FDB/static <Directory /home/user1/FDB/static> Require all granted </Directory> Alias /media /mnt/data/import/media <Directory /mnt/data/import/media> Require all granted </Directory> <Directory /home/user1/FDB/fdb> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/user1/FDB/fdb/wsgi.py WSGIDaemonProcess django_app python-path=/home/user1/FDB python-home=/home/user1/FDB/venv WSGIProcessGroup django_app Any help is appreciated. -
How to filter rows in django and html?
How to filter column's in django using templates (html,bootstrap)? I have table called Some contains 50 column's. example: a,b,c,d,e,f,g how to filter columns if i select a,b column show two columns records after adding c column need to show c records ? -
Forbidden (CSRF cookie not set.) only thrown on a single view when I have disabled CSRF protections on POST?
I am developing a django backend using the djangorestframework and simplejwt authentication. I am using it for a react native mobile app so I am disabling CSRF protections for my views. For some reason, even though every other view works without issue, my token blacklist view throws an error Forbidden (CSRF cookie not set.) For example the following view works fine: @method_decorator(csrf_exempt, name='dispatch') class BusinessProfileView(APIView): permission_classes = (permissions.IsAuthenticated, HasAccountOwnershipBP) def post(self, request, format='json'): serializer = BusinessProfileSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): ... def put(self, request, format='json'): ... But this token blacklist view throws the above error @method_decorator(csrf_exempt, name='dispatch') class BlackListToken(APIView): permission_classes = (permissions.IsAuthenticated,) def post(self, request): refresh = request.data['refresh'] try: #get this refresh token from outstanding and invalidate it token = RefreshToken(refresh) token.blacklist() print('ran') return Response(status=status.HTTP_200_OK) except Exception as e: print(e) return Response(status=status.HTTP_400_BAD_REQUEST) I've tried setting csrf exempt on the post method directly but that doesn't seem to help anything. I initially tried to use simplejwt's packaged token blacklist but that also threw the same error so I was trying to gain some more control over the view creation with this custom version. Just in case here is my middleware list as I'm aware the order can affect things MIDDLEWARE = … -
How to pass {% url 'category' %} in my category_list.html?
I have a detail view for categories and if i pass in the URL directly it works just fine. But if i want to pass it as a link in my template it gets an error. Here is my models: class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return (self.name) def get_absolute_url(self): return reverse("home") Here is my views: class CategoryClassView(TemplateView): model = Category template_name = "categories.html" def get_context_data(self, **kwargs): cats = kwargs.get("cats") category_posts = Category.objects.filter(name=cats.replace('-', ' ')) context = {'cats':cats.replace('-', ' ').title(), 'category_posts':category_posts} return context Here is my URLS: path('category/<str:cats>/', CategoryClassView.as_view(), name='category') Here is my template: {% extends "base.html" %} {% block content %} {% for category in category_list %} <div class="card"> <div class="card-header"> <span class="font-weight-bold"><a href="">{{ category.name}}</a></span> &middot; </div> </div> {% endfor %} {% endblock content %} Could you write a more detailed explanation for your answer? Why is just passing {% url 'categoryl' %} is not working? A link to a list of useful materials would be also acceptable for better understanding. -
Forbidden: /unauthentication error for token
(views.py) class userApi(APIView): def get(self,request): auth = get_authorization_header(request).split() if not auth: raise AuthenticationFailed('User Authentication Failed!!!') elif auth and len(auth)==2: token =auth[1].decode('utf-8') id=decode_access_token(token) #payload = decode_access_token(token) users=user.objects.filter(id = id).first() serializer=userSerializer(users) return Response(serializer.data) raise AuthenticationFailed('unauthenticated') (authentication.py) import jwt,datetime from rest_framework.exceptions import AuthenticationFailed def create_access_token(id): return jwt.encode({ 'user_id':id, 'exp':datetime.datetime.utcnow()+datetime.timedelta(minutes=10), 'iat':datetime.datetime.utcnow() },'access_secret',algorithm='HS256') def decode_access_token(token): try: #payload = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"]) payload=jwt.decode(token,'access_secret',algorithm='HS256') return payload['user_id'] except: raise AuthenticationFailed('unauthenticated') Filter the user details form id form authentication token. -
how to create a object from django models to database and save it
Hi everyone this is my models and i'am calculation total total_time in a function . But unable to save the entry in database in (totaltime) field . Please suggest the best possible way to do this . class Attendance(models.Model): employee = models.ForeignKey( Employee, on_delete=models.CASCADE, default=1, related_name='Attendance') attendance_date = models.DateField(null=True) in_time = models.TimeField(null=True) out_time = models.TimeField(null=True, blank=True) totaltime = models.TimeField(null=True, blank=True) @property def total_time(self): if self.out_time != None: t1 = datetime.strptime(str(self.in_time), "%H:%M:%S") t2 = datetime.strptime(str(self.out_time), "%H:%M:%S") delta = t2 - t1 return delta else: return None I was trying to print the totaltime feild in class but shown result is none.please advise how can i add this entry in database -
Reverse for 'edit_vehicle' with arguments '('',)' not found. 1 pattern(s) tried: ['vehicle/edit/(?P<vehicle_id>[0-9]+)\\Z']
NoReverseMatch at /vehicle/vehicle_view/ Reverse for 'edit_vehicle' with arguments '('',)' not found. 1 pattern(s) tried: ['vehicle/edit/(?P<vehicle_id>[0-9]+)\\Z'] Here my Render link in HTML ✎ Views.py def edit_vehicle(request, vehicle_id): instance = get_object_or_404(Vehicle, id=vehicle_id) form = UpdateVehicleForm(request.POST or None, instance=instance) context = { 'form': form, 'vehicle_id': vehicle_id, 'page_title': 'Edit Vehicle' } if request.method == 'POST': if form.is_valid(): model_name = form.cleaned_data.get('model_name') vehicle_type = form.cleaned_data.get('vehicle_type') manufacture_company = form.cleaned_data.get('manufacture_company') vehicle_number = form.cleaned_data.get('vehicle_number') try: vehicle = Vehicle.objects.get(id=vehicle_id) vehicle.model_name = model_name vehicle.manufacture_company = manufacture_company vehicle.vehicle_type = vehicle_type vehicle.vehicle_number = vehicle_number vehicle.save() messages.success(request, "Successfully Updated") return redirect(reverse('edit_vehicle', args=[vehicle_id])) except Exception as e: messages.error(request, "Could Not Add " + str(e)) else: messages.error(request, "Fill Form Properly") return render(request, 'user/edit_vehicle.html', context) urls.py path("edit/int:vehicle_id",views.edit_vehicle, name='edit_vehicle'),