Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Yelp API call with python Requests
I've got a Django project with a class based view where my frontend makes a call to and sends through a user input. The View then collects that input and makes an API call and is expected to return a json object but I keep getting a 404. I'm not exactly sure which part is broken as nothing gets returned. Views.py class YelpLocation(APIView): def get(self, request): API_KEY= '***' API_HOST = 'https://api.yelp.com/v3/businesses/search/' location = self.request.GET['location'] headers = { 'Authorization': 'Bearer %s' % API_KEY, } params = { 'location' : location, 'term' : 'coffee' } response = requests.get( API_HOST, headers=headers, params=params) return Response(response) -
Where to put global html/css files in Django (Navbar.html, general.css, etc...) so that it's referable by all apps?
1) I want my project to be able to call {% include navbar.html %} from every template but I'm not sure where I'm supposed to place navbar.html. I tried placing it in mysite/templates/navbar.html but calling {% include navbar.html %} just gave me a TemplateSyntaxError. 2) I also want to be able to have a general.css referable by all of my apps. Is placing it in mysite/static/general.css a good idea?. -
What the Difference between Django synthax
hello guys what the difference between this two syntax 'blog' and 'blog.apps.BlogConfig' in project this is located in installed app. i think both are same but there should be difference between this 2 commands because they looks like different first one is this INSTALLED_APPS = [ 'blog', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] seccond one is : INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC
I am recording voice using javascript in .wav format: navigator.mediaDevices.getUserMedia({audio:true}) .then(stream => {handlerFunction(stream)}) function handlerFunction(stream) { rec = new MediaRecorder(stream); rec.ondataavailable = e => { audioChunks.push(e.data); if (rec.state == "inactive"){ let blob = new Blob(audioChunks,{type:'audio/wav;codecs=0'}); sendData(blob) } } } sending the file to convert it to text using speech_recognition: filename = "name.wav" print(filename) data = request.body BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) uploadedFile = open(filename, "wb") uploadedFile.write(request.body) uploadedFile.close() os.path.join(BASE_DIR,filename) r = sr.Recognizer() file = sr.AudioFile(filename) with file as source: audio = r.record(source) msg = r.recognize_google(audio) print(msg) return redirect('/') Error:- ValueError: Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format P.S. audio file is saving and I can hear sound/voice clearly well -
How to get data from two tables with DjangoORM?
I have two tables in the database: class CustomerEquipment(models.Model): serial_number = models.CharField(max_length=255) state_timestamp = models.DateTimeField() state_type = models.IntegerField() class Meta: managed = False db_table = 'customer_equipment' class LogCustomerEquipment(models.Model): state = models.IntegerField() state_timestamp = models.DateTimeField() serial_number = models.CharField(max_length=255) class Meta: managed = False db_table = 'log_customer_equipment' I execute two database queries: customer_equipment_list = CustomerEquipment.objects.using('portal').filter( Q(state_type=10) & Q(state_timestamp__icontains='2020-02-27') ) log_customer_equipment_list = LogCustomerEquipment.objects.using('portal').filter( Q(state=2) & Q(state_timestamp__icontains='2020-02-27') ) I need to get serial_number which are in both tables. How to do it? How can I optimize queries? -
ValueError: not enough values to unpack (expected 2, got 1) how can i solve this problem i am just tried
ValueError: not enough values to unpack (expected 2, got 1) how can I solve this problem I am just tried to get this Error for a long This is The Error (myDjangoEnv) D:\Django\User\learning_users>python manage.py migrate Traceback (most recent call last): File "manage.py", line 21, in main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\core\management__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\core\management__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\core\management\base.py", line 366, in execute self.check() File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\core\management\commands\migrate.py", line 64, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\contrib\staticfiles\checks.py", line 7, in check_finders for finder in get_finders(): File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\contrib\staticfiles\finders.py", line 282, in get_finders yield get_finder(finder_path) File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\contrib\staticfiles\finders.py", line 295, in get_finder return Finder() File "C:\Users\ABC.conda\envs\myDjangoEnv\lib\site-packages\django\contrib\staticfiles\finders.py", line 59, in init prefix, root = root ValueError: not enough values to unpack (expected 2, got 1) **models.py** from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): # user = models.OneToOneField(User) user = models.OneToOneField(User, on_delete=models.CASCADE) # user = models.ForeignKey(User,models.SET_NULL,blank=True,null=True) # user = models.ForeignKey(User, on_delete=models.PROTECT) #additional profile_site = models.URLField(blank = True) … -
Implement sessions on database in flask
I can't understand how to implement sessions on the database in the flask. I need a single connection from the database and multiple sessions from that single connection. The database used is pyodbc -
Django logging configuration working on local server but not on remote server
I'm trying to configure django logging in the django settings file so that it logs django info and info for my application to a custom file for easy viewing. Here's my logging config: 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'console': { # exact format is not important, this is the minimum information 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s', }, 'file': { # exact format is not important, this is the minimum information 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s', }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'formatter': 'file', 'filename': 'logs/django_log.log', 'backupCount': 10, # keep at most 10 log files 'maxBytes': 5242880, # 5*1024*1024 bytes (5MB) }, 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'console', }, }, 'loggers': { 'django': { 'handlers': ['file', 'console'], 'level': 'INFO', 'propagate': True, }, 'py.warnings': { 'handlers': ['console'], }, 'my_application': { 'level': 'INFO', 'handlers': ['file', 'console'], # required to avoid double logging with root logger 'propagate': False, }, }, } This works on my local manage.py test server, both with django events appearing and events that I log, initialized with my_application as the logger name. However, on my web server, the logging file is created and, oddly, only populated with occasional django WARNING messages. So, there … -
How to pass multiple <li> element from template to Django view?
I am trying to pass list elements from template to view when I click a button. My template looks like the following. <ul id="listFrom"> <li data-id="1"><a href="#">Element 1</a></li> <li data-id="2"><a href="#">Element 2</a></li> <li data-id="3"><a href="#">Element 3</a></li> <li data-id="4"><a href="#">Element 4</a></li> </ul> Thank you in advance. -
Models aren't loaded yet
I try to get all pages of ProgramPage where the field program_types has a certain pk Everything was fine before I had added this. program_type = ProgramType.objects.get(pk=1) programs = ProgramPage.objects.live().public().filter(program_types__in=[program_type]) Here is the full code of models.py: # program/models.py from django import forms from django.db import models from modelcluster.fields import ParentalManyToManyField from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel from wagtail.snippets.models import register_snippet @register_snippet class ProgramType(models.Model): name = models.CharField(max_length=255) panels = [ FieldPanel('name'), ] def __str__(self): return self.name class Meta: verbose_name_plural = "Program types" class ProgramPage(Page): description = RichTextField(blank=True) program_types = ParentalManyToManyField("program.ProgramType", blank=True) content_panels = Page.content_panels + [ FieldPanel('description'), FieldPanel('program_types', widget=forms.CheckboxSelectMultiple), ] class IndexProgram(Page): program_type = ProgramType.objects.get(pk=1) programs = ProgramPage.objects.live().public().filter(program_types__in=[program_type]) after "makemigrations" or "runserver" I get an error: raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. -
django create rtl PDF file dynamically
I have tried many library to create rtl PDF file with Arabic language dynamically and I couldn't figure how work it out as all working in ltr direction but not rtl direction, any suggestions? -
lists to Dictinary and printing in required format
I have 2 lists like this list1=['TEL', 'TEL', 'TEL', 'US0_STU', 'infocollect feml sfx-infocollect.sh CCR', 'TEL', 'TEL', 'TEL TEL.SYM dbase.mgr maoagent maoagent.SYM sysopt confmem'] listcr=['RA CROXES-23814', 'RA CROXES-23772', 'RA CROXE-16484', 'RA CROXE-16387', 'RA CROXE-16294', 'RA CROXE-16210', 'RA CROXE-16140', 'RA CROXE-16101'] I have tried to form a dictionary with the below following code mydict = {} k=0 for i in range(len(list1)): index=i if list1[i].find(" ")>=0: bin_list = list1[i].split(" ") for binary in bin_list: mydict.update({k:[binary,listcr[index]]}) k+=1 else: mydict.update({k:[list1[i],listcr[index]]}) k+=1 print(mydict) so the myDict is like this mydict={0: ['TEL', 'RA CROXES-23814'], 1: ['TEL', 'RA CROXES-23772'], 2: ['TEL', 'RA CROXE- 16484'], 3: ['US0_STU', 'RA CROXE-16387'], 4: ['infocollect', 'RA CROXE-16294'], 5: ['feml', 'RA CROXE- 16294'], 6: ['sfx-infocollect.sh', 'RA CROXE-16294'], 7: ['CCR', 'RA CROXE-16294'], 8: ['TEL', 'RA CROXE-16210'], 9: ['TEL', 'RA CROXE-16140'], 10: ['TEL', 'RA CROXE-16101'], 11: ['TEL.SYM', 'RA CROXE-16101'], 12: ['dbase.mgr', 'RA CROXE-16101'], 13: ['maoagent', 'RA CROXE-16101'], 14: ['maoagent.SYM', 'RA CROXE-16101'], 15: ['sysopt', 'RA CROXE-16101'], 16: ['confmem', 'RA CROXE- 16101']} In Django UI page I want to display the elements like this TEL RA CROXES-23814 RA CROXES-23772 RA CROXE- 16484 RA CROXE-16101 RA CROXE-16210 RA CROXE-16140 US0_STU RA CROXE-16387 infocollect RA CROXE-16294 feml RA CROXE- 16294 sfx-infocollect.sh RA CROXE-16294 CCR RA CROXE-16294 TEL.SYM RA CROXE-16101 dbase.mgr … -
Login is not working with newly set password in django?
I am implementing the UserCreationForm and with this I am setting some default password1 and password2 for user.After successful creation it sends email to this user instance and after clicking the email user activates and redirect to the set_user_password view. The view is posted below. It successfully creates the password for this user but the user is not being able to login with this newly created password. What might be the reason ? forms.py class SetPasswordForm(forms.ModelForm): password1 = forms.CharField(widget=forms.PasswordInput, validators=[validate_password]) password2 = forms.CharField(widget=forms.PasswordInput) class Meta: model = get_user_model() fields = ['password1', 'password2'] def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1: if not password1 == password2: raise forms.ValidationError("Sorry the two passwords didn't match") views.py def set_user_password(request, pk): user = get_object_or_404(get_user_model(), pk=pk) form = SetPasswordForm() if request.method == 'POST': form = SetPasswordForm(request.POST) if form.is_valid(): password = form.cleaned_data.get('password2') user.set_password(password) user.save() messages.success(request, 'Password created successfully.') return redirect('login') return render(request, 'user_invitation/set_password.html', {'user': user, 'form': form}) urls.py path('user/<int:pk>/set/password/', views.set_user_password, name='set_user_password'), -
Retrieving a Has Many Model Values with django-rest-framework serializers
class User(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Address(models.Model): name = models.CharField(max_length=100) user = models.ForeignKey(User, related_name='users') def __str__(self): return self.name How can i retrieve the address of a specific user using drf serializers ? -
Encryption in Flutter and Decryption in python
I'm trying to connect two different applications, flutter web and django application. I need to encrypt my data in flutter and decrypt it in python. Is there any solution for this? Is there any compatible encryption and decryption algorithm for both dart and python. -
Django Dropdown Menu Search Form With Multiple Model Field Sorting Ascending / Descending
I want to make a single dropdown menu for a search form where you are able to sort by all sorts of different fields in the model in ascending and descending order. How does this get accomplished? I started it off in my forms.py sort field but I am not sure how to write the view to be able to combine all of the sorts in a single dropdown menu. Desired Result: https://imgur.com/a/zgU2BMy Forms.py: class CourseForm(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control col-12', 'autocomplete':'off', 'id':'title', 'type':'search', 'placeholder': 'Course Name'}), required=False) min_views = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control', 'autocomplete':'off','id':'min_views', 'type':'number', 'min':'0', 'placeholder': '0'}), required=False, validators=[MinValueValidator(0), MaxValueValidator(99999999999999999999999999999999999)]) max_views = forms.IntegerField(widget=forms.NumberInput(attrs={'class':'form-control', 'autocomplete':'off', 'id':'max_views', 'type':'number', 'min':'0', 'placeholder': '1000000'}), required=False, validators=[MinValueValidator(0), MaxValueValidator(99999999999999999999999999999999999)]) min_date = forms.DateField(widget=forms.TextInput(attrs={'class':'form-control', 'autocomplete':'off', 'id':'max_date','type':'date', 'placeholder': 'mm/dd/yyy'}), required=False) max_date = forms.DateField(widget=forms.TextInput(attrs={'class':'form-control', 'autocomplete':'off', 'id':'min_date', 'type':'date', 'placeholder': 'mm/dd/yyy'}), required=False) expertise = forms.ChoiceField(widget=forms.Select(attrs={'class':'form-control', 'autocomplete':'off','id':'skill_level'}), choices = ([('',''), ('Beginner','Beginner'), ('Intermediate','Intermediate'),('Advanced','Advanced'), ]), required=False) subject = forms.ModelChoiceField(queryset=Subject.objects.filter().order_by('name'), to_field_name="name", empty_label="", widget=forms.Select(attrs={'class':'form-control', 'autocomplete':'off', 'id':'subject'}), required=False) membership = forms.ModelChoiceField(queryset=Membership.objects.all(), to_field_name="membership_type", empty_label="", widget=forms.Select(attrs={'class':'form-control', 'autocomplete':'off', 'id':'membership'}), required=False) sort = forms.ChoiceField(widget=forms.Select(attrs={'class':'form-control', 'autocomplete':'off','id':'sort'}), choices = ([('',''), ('title','Ascending Title'), ('title','Descending Title'),('created_at','Ascending Date'), ('created_at','Descending Date'), ('visited_times','Ascending Views'), ('visited_times','Descending Views'), ]), required=False) def __init__(self, *args, **kwargs): super(CourseForm, self).__init__(*args, **kwargs) self.fields['name'].label = "Course Name:" self.fields['min_views'].label = "Min Views:" self.fields['max_views'].label = "Max Views:" self.fields['min_date'].label = "Min Date:" self.fields['max_date'].label … -
Visual Studio Code don't recognize HTML file
I am learning to build a Website on Python Django, but when I create a HTML file in VS code, this Editor don't recognize this file. You can see in following picture. I don't know how to solve this problem. Pls help me if you know, thank you very much -
Unable to add time to TimeField in django model [<class 'decimal.InvalidOperation'>]
I have a django model like this... class ConversionResults(models.Model): conversion_results_id = models.AutoField(primary_key=True) conversion_rate_a = models.DecimalField(max_digits=4, decimal_places=2) clicks_a = models.IntegerField() conversion_rate_b = models.DecimalField(max_digits=4, decimal_places=2) clicks_b = models.IntegerField() week = models.IntegerField() date = models.DateField() time = models.TimeField() objects = models.Manager() class Meta: db_table = 'conversion_results' def __int__(self): return self. conversion_results_id When I try to add data to the model, like below ConversionResults( conversion_rate_a=conversion_rate_today_a, conversion_rate_b=conversion_rate_today_b, clicks_a=ctc_today_a, clicks_b=ctc_today_b, week=week, date=today_date, time=datetime.datetime.today().time() # the error is here ).save() I am getting error with the time field as shown below graphql.error.located_error.GraphQLLocatedError: [<class 'decimal.InvalidOperation'>] I don't get how this is even related to decimal, the model contains a TimeField. Any help will be appreciated -
can't able to add DIV element using a button
<!DOCTYPE html> <html> <head></head> <body> <form method="POST" action="act.php"> <p>Click the button to create a DIV element with some text, and append it to DIV.</p> <div id="myDIV"> MATHS PAPER </div> <button onclick="myFunction()">Add Question</button> <input type="submit" value="Create"> </input> <script> function myFunction() { var para = document.createElement("DIV"); para.innerHTML = "<div style='background-color:lightgreen'>QUESTION<div><input type='text' id='q1' placeholder='enter question'></div><div></input><input type='text' placeholder='enter option1 here'></input></div><div></input><input type='text' placeholder='enter option2 here'></input></div></div>"; document.getElementById("myDIV").appendChild(para); } </script> </form> </body> </html> How to make this code work? I observed on removing form tag, it is working. But I want it to be in form tag, so that I can post those questions and options, and save it in a database. reference: https://www.w3schools.com/jsref/met_document_createelement.asp -
Jenkins fails to install Django 2.0+
I am new to Docker & Jenkins. I want to build a CI/CD using docker & Jenkins. The issue that I have is, I cannot get Jenkins to install Django == 2.0.8. The cause of this issue is, Jenkins uses python2.7. I install python 3.5 on Jenkins, and set the PYTHONPATH = "/usr/bin/python3/lib", PYTHON="/usr/bin/python3/bin". But this doesn't work. I also tried online solutions, such as install ShiningPanda and it failed too. Anyone could shed me some lights? I have been struggle with it for 3 hours. It shouldn't be this difficult right. -
Key_error using self.cleaned_data[] in Django forms
I keep getting a key_error on line email = self.cleaned_data["email"] of the below in my forms.py. I am trying to also add an email validation or clean_email method, because somehow it seems that the key_error only occurs when I try registering with an invalid email address. Is adding def clean_email() the right approach? And if so, is the forms.py inside my class the right place to do so? forms.py: from django import forms from django.contrib.auth.models import User class RegisterForm(forms.Form): first_name = forms.CharField(widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': "First Name", 'autocomplete': "nope"}), label="First name", max_length=64, required=True) last_name = forms.CharField(widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': "Last Name", 'autocomplete': "new-password"}), label="Last name", max_length=64, required=True) email = forms.EmailField(widget=forms.TextInput(attrs={'class': "form-control", 'placeholder': "Email", 'autocomplete': "new-password"}), label="Email", max_length=132, required=True) password = forms.CharField(label="Password", max_length=32, widget=forms.PasswordInput(attrs={'class': "form-control", 'placeholder': "Password"})) confirmation = forms.CharField(label="Confirmation", max_length=32, widget=forms.PasswordInput(attrs={'class': "form-control", 'placeholder': "Confirm"})) def clean(self): email = self.cleaned_data["email"] if User.objects.filter(username=email).exists(): raise forms.ValidationError(u'Email "%s" is already in use.' % email) password = self.cleaned_data["password"] confirmation = self.cleaned_data["confirmation"] if password != confirmation: raise forms.ValidationError("Password and confirmation do not match!") The correspoinding method in views.py is: from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.contrib import messages def register_client(request): if request.method == "POST": … -
Django Auth - Unhash the hashed password
I have two server and one is using Django. My auth flow is that Server A(using Django) if the user submit the right account & password Then Server A will pass the password to Server B update the password. So how can I unhash the password in Django DB and pass the raw password to the Server B? -
django - production/development migrations and databases mixed up
This is my first Django app deployment, a lot to learn. So this is my settings for DATABASES in settings.py if DEBUG: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db_name', 'USER': 'db_user', 'PASSWORD': 'db_password', 'HOST': 'localhost', 'PORT': '', } } Problem: For fixing a bug, I updated some fields in models locally, git push, and git pull on server, make migrations on server like I normally would locally; the migrations were successful, however, they don't seem to have applied (if it's of any relevance, the bug fixing was some phone number field changed from IntegerField to CharField, preventing the error "Verify that this value is less than or equal to 2147483647"; But the weird thing is there wasn't any error for the cellphone IntegerField before deployment and running locally) Confusion: I remember that only one superuser was created on postgres database, or at least I thought it was, but I can log in with this superuser account in both production and development (that is no matter the DEBUG is set to True or False), how is that possible?? Same are the images uploaded only once, but … -
I am unable to install pillow file and currently using python 3.5.1, also having an error while coding, the error is NameError
Also while coding its not identifying models, even i have added apps file of models in settings. Also am unable to install pillow file and when i am checking django version its showing the command Found Exception, it was working till yesterday and now its not working stuck in between don't know why so? I have tried several things to resolve the same but nothing is happening and its so frustrating that i am unable to solve this error. File "d:/project/mysite/mysite/categorymodel.py", line 1, in class Category(models.Model): NameError: name 'models' is not defined (myproject) D:\project\mysite\mysite>C:/Users/BTN-2/envs/myproject/Scripts/python.exe d:/project/mysite/mysite/categorymodel.py Traceback (most recent call last): File "d:/project/mysite/mysite/categorymodel.py", line 1, in class Category(models.Model): NameError: name 'models' is not defined (myproject) D:\project\mysite\mysite>:/Users/BTN-2/envs/myproject/Scripts/python.exe d:/project/mysite/mysite/categorymodel.py (myproject) D:\project\mysite\mysite>C:/Users/BTN-2/envs/myproject/Scripts/python.exe d:/project/mysite/mysite/categorymodel.py Traceback (most recent call last): File "d:/project/mysite/mysite/categorymodel.py", line 1, in class Category(models.Model): NameError: name 'models' is not defined -
why djnago save method not works? why it create new once?
I'm trying to build a to do app by django, inserting data works fine but when want to update it not updates, it create new once, here's my code. from django.urls import path, include from . import views urlpatterns = [ path('',views.index, name='list'), path('update/<str:pk>/', views.update, name='update') ] views code from django.shortcuts import render, redirect from .models import * from .forms import * # Create your views here. #index function def index(request): tasks = Task.objects.all() form = TaskForm() if request.method =='POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context ={'tasks': tasks, 'form':form} return render(request,'index.html', context) #update function def update(request,pk): tasks = Task.objects.get(id=pk) form = TaskForm(instance=tasks) if request.method == 'POST': form = TaskForm(request.post, instance=tasks) if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request,'update_task.html',context) update_task.html code is <body> <h3>Update</h3> <form method="POST" action="/"> {% csrf_token %} {{ form }} <input type="submit" name="submit"> </form> </body> when want to update it not updates, it creates new once. wheres my problem? help me please. Thanks