Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery workers stop receiving tasks after a certain period without any error
I'm using Celery beat and workers for task scheduling in a Django project. Redis is being used as the broker. I've daemonized it with systemd. Django project settings for Celery # Celery application definition CELERY_BROKER_URL = "redis://localhost:6379" CELERY_ACCEPT_CONTENT = ["application/json"] CELERY_TASK_SERIALIZER = "json" CELERY_TIMEZONE = "UTC" CELERY_MAX_TASKS_PER_CHILD = 1 CELERY_IGNORE_RESULT = True # Celery periodic task schedule CELERY_BEAT_SCHEDULE = { "task-1": { "task": "project.apps.app1.tasks.task_no_1", "schedule": datetime.timedelta(seconds=5), }, "task-2": { "task": "project.core.tasks.task_no_2", "schedule": datetime.timedelta(seconds=10), }, "task-3": { "task": "project.apps.app1.tasks.task_no_3", "schedule": datetime.timedelta(seconds=10), }, "task-4": { "task": "project.apps.app1.tasks.task_no_4", "schedule": datetime.timedelta(seconds=5), }, "task-5": { "task": "project.apps.app1.tasks.task_no_5", "schedule": datetime.timedelta(seconds=10), }, "task-6": { "task": "project.apps.app1.tasks.task_no_6", "schedule": datetime.timedelta(seconds=30), }, "task-7": { "task": "project.apps.app1.tasks.task_no_7", "schedule": datetime.timedelta(seconds=30), }, } /etc/default/celeryd # Name of nodes to start CELERYD_NODES="worker1 worker2" # Absolute or relative path to the 'celery' command: CELERY_BIN="/home/adnan/project/env/bin/celery" # App instance to use # comment out this line if you don't use an app CELERY_APP="project.core" # How to call manage.py CELERYD_MULTI="multi" CELERYD_USER="adnan" CELERYD_GROUP="www-data" CELERYD_LOG_LEVEL="INFO" # - %n will be replaced with the first part of the nodename. # - %I will be replaced with the current child process index # and is important when using the prefork pool to avoid race conditions. CELERYD_PID_FILE="/var/run/celery/%n.pid" CELERYD_LOG_FILE="/var/log/celery/%n%I.log" # Options for Celery Beat … -
Gunicorn, nginx, django, inside of a docker container. Gunicorn successfully runs on port 80 but nginx fails
I'm trying to set up a simple blogging site that I wrote using the django framework. The website works except that it isn't serving static files. I imagine that's because nginx isn't running. However, when I configure it to run on any port other than 80 I get the following error: nginx: [emerg] bind() to 172.17.0.1:9000 failed (99: Cannot assign requested address) When I run it on a port that is already being used by gunicorn I get the following error: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use) My nginx configuration file is as follows: upstream django { server 127.0.0.1:8080; } server { listen 172.17.0.1:9000; server_name my.broken.blog; index index.html; location = /assets/favicon.ico { access_log off; log_not_found off; } location /assets { autoindex on; alias /var/www/html/mysite/assets; } location / { autoindex on; uwsgi_pass unix:///run/uwsgi/django/socket; include /var/www/html/mysite/mysite/uwsgi_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
Django admin: "How to properly display multi-layered relations?"
I'm new to Django framework and trying to build a math test application. Idea is to generate a test from a pool of questions. I have a following DB entities: class TestResult(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) score = models.IntegerField(blank=True, null=True) class Meta: db_table = 'test_results' class Question(models.Model): text = models.CharField(unique=True, max_length=255) type = models.IntegerField(blank=True, null=True) class Meta: db_table = 'questions' class Answer(models.Model): question = models.ForeignKey(Questions, on_delete=models.CASCADE) text = models.CharField(max_length=255) is_correct = models.BooleanField() class Meta: db_table = 'answers' class AskedQuestion(models.Model): question = models.ForeignKey(Questions, on_delete=models.CASCADE) test = models.ForeignKey('TestResults', on_delete=models.CASCADE) class Meta: db_table = 'asked_questions' class GivenAnswer(models.Model): answer = models.ForeignKey(Answers, on_delete=models.CASCADE) test = models.ForeignKey(TestResults, on_delete=models.CASCADE) class Meta: db_table = 'given_answers' I am able to display AskedQuestion and GivenAnswer as 2 separate StackedInline for TestResult. But I want to display Question + Answer pairs when I navigate to TestResult page in Django admin. Any suggestions would be appreciated. -
[Django-pymongo]: Retain Mongo connection across request?
I have below code to open connection to mongo cluster deployed in altas under django view. def homePage(request): context = {} import pymongo client = pymongo.MongoClient(<connection str>) db = client.foo return render(request, 'Home/index.html', context) I see for each request it opens a new connection which is adding delay to load page. Is there any way i can move this connection code some where else and reuse connection handle across all request? I tried moving code to settings.py and tried exporting db handle to views.py but after sometime connections times out. Version of libs are: Django 4.0.1 django-settings-export 1.2.1 pip 21.1.2 pymongo 4.0.1 -
error Template does not exist, but template is exist
Templates does not exit, but template is already exist. In this project, I am doing upload file. Please help to solve this problem. urls.py: from django.contrib import admin from django.urls import path from usermaster import views from django.conf.urls.static import static from mysite5 import settings urlpatterns = [ path('admin/', admin.site.urls), path('upload/', views.index), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) views.py: from django.http.response import HttpResponse from django.shortcuts import render from usermaster.forms import MachineForm # Create your views here. def index(request): if request.method == 'POST': form = MachineForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['upload_file']) model_instance = form.save(commit=False) model_instance.save() return HttpResponse("File uploaded successfuly") else: form = MachineForm() return render(request,'usermaster/upload_file.html',{'form':form}) def handle_uploaded_file(f): with open('usermaster/static/upload/'+f.name, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) models.py: from django.db import models # Create your models here. class Machine(models.Model): machine_name = models.CharField(max_length=200) operation_no = models.IntegerField() upload_file = models.FileField() forms.py: from django import forms from usermaster.models import Machine class MachineForm(forms.ModelForm): class Meta: model = Machine fields = '__all__' upload_file.html: <html> <head> <title>Django File Upload</title> </head> <body> <p><h1>Django File Upload</h1></p> <form method="post" class="post-form" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> </body> </html> Templates does not exit, but template is already exist. In this project, I am doing upload file. I don't know why template … -
FieldError: Unsupported lookup for CharField or join on the field not permitted on Django
Why do I get this error: FieldError: Unsupported lookup 'unaccent' for CharField or join on the field not permitted? Info Language: Python Platform: Django Database: PostgreSQL Code View: def search(request): query = request.GET.get("query") searched = Book.objects.filter(title__unaccent__icontains=query) # Error here return render(request, "main/search.html", { "query": query, "searched": searched, }) Expected output Unaccent the query and search for the unaccented version in the database. Description I get the error FieldError: Unsupported lookup 'unaccent' for CharField or join on the field not permitted when I try to query the database using __unaccent while using the advanced search features mentioned in the django docs. -
PermissionDenied return to home
For my blog on all the relevant views such as delete and update I have this if request.user.id != post.author_id: raise PermissionDenied() This is working as expected however it just sends the user to a page that says 403 forbidden. I would rather just redirect the user to the homepage. Would it be insecure or poor practice to do something like return HttpResponseRedirect('/') or is it fine as is and I am overthinking it -
item['total_price'] = item['price'] * item['quantity'] KeyError: 'quantity'
Good afternoon, I'm writing a store on django, but the following problem occurred when going to the shopping cart page: item['total_price'] = item['price'] * item['quantity'] KeyError: 'quantity'. The error itself lies in cart.py , and it seems simple, but I do not know how to solve it. Forms.py: PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) views.py from django.shortcuts import redirect, get_object_or_404, render from django.views.decorators.http import require_POST from shop.models import Product from .cart import Cart from .forms import CartAddProductForm @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) return render(request, 'cart/detail.html', {'cart': cart}) def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm( initial={'quantity': item['quantity'], 'update': True}) return render(request, 'cart/detail.html', {'cart': cart}) cart.py from decimal import Decimal from django.conf import settings from shop.models import Product class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart … -
How to pass django context values to the javascript variable?
I want to pass all the values of the {{ i.nsn }} turn by turn to the ajax script. {% for i in dibbs %} <p>{{ i.nsn }}</p> {% endfor %} If I tried the ajax script in the way {% for i in dibbs %} <script> var nsn = {{ i.nsn }} console.log("Hello") $('.togglebtn').on("click",function(){ console.log("Hello") $.ajax({ type: 'GET', url: "http://localhost:8000/toggle/"+nsn, contentType: 'application/json', success: function (data) { appendData(data); function appendData(data) { var mainContainer = document.getElementById("switch_{{forloop.counter}}"); for (var i = 0; i < data.length; i++) { var div = document.createElement("div"); div.innerHTML = '<tr>' + data[i].line_items + ' ' + data[i].nomenclature+'</tr>' ; mainContainer.appendChild(div); } } } }); }); </script> {% endfor %} The ajax script also repeats as per the loop. My url is different for every nsn. I want to send a single ajax request when I clicked in the button. I want to execute a single ajax function for a single click removing the for loop. -
How to get the ID of the record created in the model after saving it from a Form
Let's say I submit a form to the back-end and I save a record of the model in the following way: views.py: def viewName(request): if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): form.save() #I want to get the id of this after it is saved else: print (form.errors) form = ProjectForm() return render(request, 'index.html', context) forms.py: class ProjectForm(ModelForm): class Meta: model = Project fields = '__all__' Right after saving the form, I would like to get the id of the record for the model. I tried with form.id and form.pk as I saw in other similar questions without success. How can I get the id or the pk of the new entry added to the Project model? -
How to write a search in django backend side search?
class Player(TimeStampedModel): name = models.CharField(max_length=200) email = models.CharField(max_length=200) email_verified = models.BooleanField(default=False, blank=True) phone = models.CharField(max_length=200) phone_verified = models.BooleanField(default=False, blank=True) company_id = models.ImageField(upload_to=get_file_path_id_card, null=True, max_length=255) company_id_verified = models.BooleanField(default=False, blank=True) team = models.ForeignKey(Team, related_name='player', on_delete=models.DO_NOTHING) def __str__(self): return self.name This is my moodel i want to serch using name and phone number. -
How to host Django website on oracle cloud virtual machine?
I am trying to host a Django Project on Oracle cloud virtual machine running Ubuntu. As I am not too experienced with virtual machines, I was following along with this tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 What I have succeeded in doing so far is to create postgresql database and starting django project and connecting the database to the django project, and applying migrations. However, as per the tutorial, I run python manage.py runserver 0.0.0.0:8000 and it appears that the website has been deployed, but upon entering public ip into browser, it says could not connect to the ip. Any help? I have added ingress rules 8000/udp and 8000/tcp into the subnet but still no luck -
Django Custom Password Reset Form widget not working
Stumped as to why my template isn't showing my custom password reset form. Here is code: forms.py class CustomPasswordResetForm(PasswordResetForm): def __init__(self, *args, **kwargs): super(CustomPasswordResetForm, self).__init__(*args, **kwargs) email = forms.EmailField( label='', widget=forms.EmailInput(attrs={ 'placeholder': 'placetest@test.com', 'class': 'form-field', })) Views.py class PasswordResetView(auth_views.PasswordResetView): form_class = CustomPasswordResetForm template_name = 'password_reset.html' urls.py urlpatterns = [ path('login/', LoginView.as_view(), name='login'), path('password_reset', PasswordResetView.as_view(), name='password_reset'), path('login_success/', login_success, name='login_success'),] Template {% load static %} {% block title %}Home{% endblock %} {% block content %} <div class="form-container" id="pwrest"> <div class="form-title"> <h2>Enter your email address</h2> </div> <form method="POST"> {% csrf_token %} <p>email</p> <div>{{ form.email }}</div> <input class="submit-button" type="submit" value="Send me instructions!"> </form> </div> </div> {% endblock %} CSS .form-field{ width: 300px; height:30px; margin-bottom:5px; margin-top:5px; border:none; border-radius: 5px; background-color:whitesmoke; } When I view the template in my browser, I am seeing the form field as the default, its almost like its just not recognizing the CSS class. I'm not sure what I've missed. Thank you. -
Change date time format after AJAX call in Django
I have the following Datatable: $('#table').DataTable( { responsive: true, autowidth: false, destroy: true, deferRender: true, ajax: { url: '/ajax_view/', type: 'GET', data: {}, dataSrc: "" }, columns: [ {"data": "fields.filename"}, {"data": "fields.uploaded"}, {"data": "fields.updated"}, {"data": "fields.user"}, {"data": "pk"}, ], columnDefs: [ { className: 'text-center', targets: [1] }, { targets: [0], class: 'text-center', orderable: true, render: function (data, type, row) { var filename = data.replace(/^[^/]*\//,''); var buttons = '<a class="file-links" href="/media/'+data+'" target="_blank">'+filename+'</a>'; return buttons; } }, { targets: [-1], class: 'text-center', orderable: false, render: function (data, type, row) { var buttons = '<button type="button" value="'+data+'" class="btn btn-danger fileId"><svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" fill="white" class="bi bi-trash-fill" viewBox="0 0 16 16"><path d="M2.5 1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1H3v9a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V4h.5a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1H2.5zm3 4a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 .5-.5zM8 5a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7A.5.5 0 0 1 8 5zm3 .5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 1 0z"/></svg></button>'; return buttons; } }, ], order: [ [0, 'asc'] ], "pagingType": "numbers", dom: 'rtp' … -
Flask & MySQL connector in Python
I am using MySQL in a Python written backend without an ORM. I have a bunch of classes that provide database access services using mysqlconnector and these services may be used by the same or different API routes. They are provided as member functions using a single MySQLConnection and MySQLCursor object that is initialized in a constructor and then passed around. Is it possible to make this thread-safe without altering the design too much i.e. without requiring opening a new connection for every member function that accesses the database? -
Python Azure SDK - Incorrect datetime format inferred when reading tabular data from blobstore with from_delimited_files()
I am using the Azure Python SDK to read a tabular dataset from a Blob Store as follows: df = Dataset.Tabular.from_delimited_files(path=[DataPath(ds, blobstore_dir + 'tabular_data.csv')], separator=',', header=True) The data has four datetime columns, one of the columns reads in with no problem because there are instances where the month-day order is not ambiguous, but the other three are being inferred incorrectly as "month-day" instead of "day-month". When reading in the data I get the following warning: UserWarning: Ambiguous datetime formats inferred for columns ['Period Start', 'Period End', 'Extracted At'] are resolved as "month-day". Desired format can be specified by set_column_types. I have attempted to set the column types as below, and have tried a few different formats but all I end up with is NULL in place of all the values. df = Dataset.Tabular.from_delimited_files( path=[DataPath(ds, blobstore_dir + 'tabular_data.csv')], separator=',', header=True, set_column_types={'Period Start': DataType.to_datetime("%d-%m-%Y %H:%M:%S"), 'Period End': DataType.to_datetime("%d-%m-%Y %H:%M:%S"), 'Extracted At': DataType.to_datetime("%d-%m-%Y %H:%M:%S")}) The documentation for from_delimited_files() is here Can anyone tell me how to force from_delimited_files() to resolve the ambiguous datetimes as day-month or tell me how to use set_column_types correctly? I've worked around it temporarily by inserting a dummy row with a non-ambiguous datetime. -
Files in media directory being routed through the dynamic link gets blocked
I have a dynamic link which i declared in django urls.py as this url(r'^(?P<user_name>[a-zA-Z0-9]+)', views.dynamic_link, name="user_details"), But all the media files is not been shown in the web pages of this dynamic link although the url of those files where correct whereas all files in the static folder is been shown. I called the media file through <img src="{% get_media_prefix %}{{list.picture}}" alt="this is alt {{img}}"> This is a sample of the link of the media and static file url in the web page code /static/css/bootstrap.css /media/images/byron_cream.jpg When I tried to view images, css etc from my static folder directly from inside the browser the browser displayed the images, css etc but doing the same thing with the media files the browser was not showing up but sending page to show the url does not exist(which i created for non existing url ). On further test I saw that the url of the media file was passing through the def dynamic_link function unlike that of the static files In other to ensure that a url which exist in my database is what is being called I have written my views function to check that any url which is passed thrugh the … -
Helpdesk ticketing system for IT - opening ticket by receiving email from the customer?
I have started to learn django, and I have build a helpdesk ticketing system, right now the tickets can only be opened by admin and I want the customer to open the ticket automatically by sending email to a specific email address, I know what am asking is broad but any advise on what tools are needed to achieve this would be highly appreciated. -
values_list query is returning the foreign keys pk rather than it's value
I am trying to get all the categories currently used in Recipes without any duplicates, by querying CategoryToRecipe. class Category(models.Model): name = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.name class CategoryToRecipe(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) name = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL) query_set = CategoryToRecipe.objects.values_list('name', flat=True).distinct() query_set is returning numbers, which I assume are the ID for Category, not the name (e.g. Lunch, Dinner, etc.). How do I get the actual name string of Category? -
Unused space in sqlite
I ran sqlite3_analyzer in order to try to understand why a database consumes much more disk space than expected, even after using VACUUM. The output shows that there are many tables with extra pages used for seemingly no reason. Here is an example: *** Table ACCOUNT_EMAILCONFIRMATION and all its indices *********************** Percentage of total database...................... 2.6% Number of entries................................. 0 Bytes of storage consumed......................... 12288 Bytes of payload.................................. 0 0.0% Bytes of metadata................................. 24 0.20% Average payload per entry......................... 0.0 Average unused bytes per entry.................... 0.0 Average metadata per entry........................ 0.0 Maximum payload per entry......................... 0 Entries that use overflow......................... 0 Primary pages used................................ 3 Overflow pages used............................... 0 Total pages used.................................. 3 Unused bytes on primary pages..................... 12264 99.80% Unused bytes on overflow pages.................... 0 Unused bytes on all pages......................... 12264 99.80% Here, three pages, each 4,096 bytes are used to store zero entries. The result is that a tiny database takes hundreds of KB. This makes me suspect that the database size might quickly explode when I put my Django website into production. So, why does this happen? -
Django registration form exceeds username length. [error]
I have a custom user model that has a username field with a max_length=50. Under the custom registration form, it throws me an error when the value of the username` field is just less than 10 characters: Ensure this value has at most 50 characters (it has 170). Below are the codes that I used that is in correlation with the username field: #models.py class UserAccount(AbstractBaseUser, PermissionsMixin): username = models.CharField(null=False, blank=False, max_length=50, unique=True) #forms.py class RegisterForm(UserCreationForm): username = forms.CharField(widget=TextInput( attrs={ "class": "form-control", "id": "username", #"placeholder": "Username", })) class Meta: model = UserAccount fields = ('username',) def clean_username(self): username = self.cleaned_data.get("username") username_filter = UserAccount.objects.filter(username__iexact=username) if username_filter.exists(): self.add_error('username', "Username is already taken") return self.cleaned_data HTML <div class="row form-group"> <div class="col-sm-4 label-column"> <label class="col-form-label" for="username-input-field">Username </label> </div> <div class="col-sm-6 input-column">{{register_form.username}}</div> </div> The error only occurs when I use the registration form on the html when creating a user, but when I create the user via python manage.py shell and admin panel, it gets created without any error. -
Django why I can't access objects of another model via foreignkey?
I have two model Doctor and UserProfile. I want to access UserProfile model objects via foreignkey. here his my code: models.py class Doctor(models.Model): docter_id_num = models.CharField(blank=True,null=True,max_length=100) doctor_name = models.CharField(max_length=100) slug = models.SlugField(max_length=255,unique=True,blank=True,null=True) class UserProfile(models.Model): acess_doctor_model = models.ForeignKey('hospital.Doctor', on_delete=models.CASCADE,blank=True,null=True,related_name="acess_doctor_model") ....my others model fields Now I need to access UserProfile model from my views fuction. here is my views.py def EditDoctor(request,slug=None): obj = get_object_or_404(Doctor,slug=slug) user_profile = UserProfile.objects.filter(acess_doctor_model=obj) print(user_profile) here is my perint result for user_profile : <QuerySet [<UserProfile: None>]> here is my print result for obj: Doctor_id: DCKMC3G0-----Doctor Name: HARTHO Why I can't get access userprofile model via this queryset: UserProfile.objects.filter(acess_doctor_model=obj) -
Different permissions for different methods in action decorator view?
I have an action decorator in a ViewSet that accepts two methods: class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer = DefaultItemSerializer @action(detail=True, method=["get", "post"], permission_classes=[AllowAny]) def custom_action(self, request, pk): qs = self.get_object() if request.method == "GET": return Response(CustomItemSerializer(qs).data, status=200) else: serializer = CustomItemSerializer(qs, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response(serializer.data, status=400) Currently both get and post have the same permission of AllowAny. What if I want them to be different? E.g. get to be AllowAny while post should only be IsAdminUser -
Why is Django forms fields value not rendering in html template for function based update view?
The issue is when i try to update my profile, i do not see the exising value i do not actually know what is wrong with the views.. views.py def profile_update(request): info = Announcements.objects.filter(active=True) categories = Category.objects.all() profile = get_object_or_404(Profile, user=request.user) Profile.objects.get_or_create(user=request.user) if request.method == "POST": u_form = UserUpdateForm(request.POST, instance=profile) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Acount Updated Successfully!') return redirect('profile', profile.user.username) else: u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, 'info': info, 'categories': categories } return render(request, 'userauths/profile_update.html', context) -
Why Djano forms fields value not rendering in html template for function based update view?
This is my update views: def EditDoctor(request,slug=None): if request.method == "POST": obj = get_object_or_404(Doctor,slug=slug) form = DoctorUpdateFrom(request.POST,instance=obj) if form.is_valid(): form.save() return redirect('hospital:all-doctor') else: form = DoctorUpdateFrom() context = {'doctor_form':form} return render (request,'hospital/edit-doctor.html', context) The main problems I am not seeing any existing value in my forms. it's just rendering an empty forms.