Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python 2D Data Dictionary using Django model query
I am trying to create a 2D python data dictionary using the output of Django Querysets. I have a data model that looks like this; class vascProsthesis(models.Model): prosthesisID = models.IntegerField(primary_key = True) prosthesisCategory = models.CharField(max_length=255, blank=True, null=True) prosthesisSubCategory = models.CharField(max_length=255, blank=True, null=True) prosthesisCompany = models.CharField(max_length=255, blank=True, null=True) prosthesisName = models.CharField(max_length=400, blank=True, null=True) prosthesisDetails = models.TextField( blank=True, null=True) class Meta: ordering = ['-prosthesisID'] I want to create an ordered "Tree structure" using the data in the model that looks like this; -prosthesisCategory1 |__prosthesisCompany1 | |__prosthesisName1 | |__prosthesisName2 |__prosthesisCompany2 | |__prosthesisName3 To achieve this, I tried to create a Python 2D Data dictionary that I can pass as to my template to generate the tree structure. proc = {} prosth = vascProsthesis.objects.order_by().values_list('prosthesisCategory', flat=True).distinct() companyList = vascProsthesis.objects.order_by().values_list('prosthesisCompany', flat=True).distinct() for procCat in prosth: proc[procCat] = {} for company in companyList: proc[procCat][company] = vascProsthesis.objects.filter(prosthesisCategory=procCat, prosthesisCompany=company).values('prosthesisID', 'prosthesisName') But I keep getting a "KeyError". What is the mistake I am making? Is there a better way to achieve this? I am using JS and CSS to generate my tree view. <ul class="tree"> <li> <input type="checkbox" checked="checked" id="c1" /> <label class="tree_label" for="c1">Level 0</label> <ul> <li> <input type="checkbox" checked="checked" id="c2" /> <label for="c2" class="tree_label">Level 1</label> <ul> <li><span class="tree_label">Level 2</span></li> … -
how do I add emojis to django url patterns?
I want to make an api that has the heart emoji in it , for example api.com/❤ it is possible , check this out for instance https://techmighty.in/%E2%9D%A4-emoji-use-in-domain-name-or-urls-of-website-%E2%9D%A4/ this is what my urlpatterns are like urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('<slug:slug>', views.index2) ] I tried going to localhost:8000/omg21😊 and this is the error that I get Not Found: /omg21😊 [04/Nov/2022 22:24:03] "GET /omg21%F0%9F%98%8A HTTP/1.1" 404 2378 as you can see, the emoji gets converted to its hex form , that's why slug:slug is supposed to pick it up , but it simply doesn't I tried searching the following on google "how to add an emoji to a url in django in 2022" "how to add an emoji to a url in django in 2021" "how to add an emoji to a url in django in 2020" "how to add the heart emoji to a url in django" and got nowhere -
Chave primaria composta em Django (Python)
Eae galera, preciso urgente entender como faz para ter chave primaria composta em nos models do Django. Também precisaria fazer esses dois campos virarem chave estrangeira de outra Tabela. Meus models estão assim até agr, porem a unica chave primaria ainda é o Id. class Create_CRM(models.Model): STATUS = ( ('Em processo', 'em processo'), ('Finalizadas','finalizadas'), ('Pendentes', 'pendentes') ) COMPLEXIDADE = ( ('Alta', 'alta'), ('Media','media'), ('Baixa', 'baixa') ) class Meta: db_table = 'create_crm' constraints = [ models.UniqueConstraint(fields = ['id', 'versao'], name ='double_constraint') ] id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') versao = models.IntegerField(null=False, default=1) data_criacao = models.DateField() descricao = models.TextField() objetivo = models.TextField() justificativa = models.TextField() dependencia = models.BooleanField(default=False) mostrar_crm = models.BooleanField(default=True) empresa = models.CharField(max_length=50) status_crm = models.CharField(max_length=50, choices=STATUS, default='Pendentes') complexidade_crm = models.CharField(max_length=50, choices=COMPLEXIDADE, blank=True) file = models.FileField(blank=True, upload_to='files/%Y/%m/',) solicitante = models.ForeignKey(CustomUser, on_delete=models.CASCADE) setor = models.ManyToManyField(Setor, related_name='setores_crm') def __str__(self): return f'CRM - {self.id}' E eu precisaria fazer os campos id e o campo versão virar chave estrangeira de outra tabela Tem como fazer isso? E se tiver, como? E eu precisaria fazer os campos id e o campo versão virar chave estrangeira de outra tabela Tem como fazer isso? E se tiver, como? -
The nonetype value comes from the django form
I am a beginner in Django. I have a form with a field "count_cont" . And i want to get integer value from this field, but i have "nonetype". count_cont = forms.IntegerField(max_value=5, min_value=1) And i want to get integer value from this field, but i have "nonetype". n=int(str(request.POST.get("count_cont"))) I try to convert it with int() and str() functions, but i get error "invalid literal for int() with base 10: 'None'" -
Django - SubQuery e function F()
I have 2 models (author and book). I want to annotate in the author model the highest book price for every authors (in order to manipulate it later). I would like to make a query with an internal sub-query using the F() function but the problem is that the F() is refered to the book model but I would like to refer it to the author model. I'll show that with an example. The models are shown below: class author: authorID = models.AutoField(primary_key = True, auto_created = True, unique = True) name = models.CharField(max_length=100) surname = models.CharField(max_length=100) class book: ownerID = models.ForeignKey(author, on_delete = models.CASCADE, related_name='hook') title = models.CharField(max_length=100) price = models.IntegerField() The query in question is as follows: value = author.objects.annotate(maxPrice = (book.objects.filter(ownerID = F('authorID')).order_by('-price') [0])) F('authorID') is refered to the book DB and so Django returns an error but I want to refer it to the author DB to achieve my goal. How can I do that? Thanks -
TypeError at /vendor/add-Menuproduct/ __init__() takes 2 positional arguments but 3 were given
form.py from django.forms import models from django.forms import ModelForm, Textarea from product.models import Product,MenuProducts from django import forms class ProductForm(ModelForm): class Meta: model = Product fields = ['category', 'image', 'title', 'description', 'price','stock'] class MenuProductForm(ModelForm): # Time = models.DateTimeField(widget=forms.DateInput(attrs={'class': 'form-control'})) class Meta: model = MenuProducts fields = [ 'YourProduct', 'Stock', 'Day', 'Time','city', 'address', 'ingredientA', 'ingredientB', 'ingredientC', 'PriceRange','city'] def __init__(self, user, **kwargs): super(MenuProductForm, self).__init__(**kwargs) self.fields['YourProduct'].queryset = Product.objects.filter(vendor__name=user) # widgets = { # 'Time': forms.DateInput(attrs={'class': 'form-control'}) # } form.py @login_required def add_Menu_product(request): if request.method == 'POST': print("Add Menu Product") print(request.user.vendor) form = MenuProductForm(request.POST, request.FILES) if form.is_valid(): Menuproduct = form.save(commit=False) # Because we have not given vendor yet Menuproduct.vendorfk = request.user.vendor # Menuproduct.slug = slugify(Menuproduct.title) Menuproduct.save() #finally save return redirect('vendor:vendor-admin') else: print("Form ") form = MenuProductForm(user=request.user.vendor) print(request.user.vendor) return render(request, 'vendor/add_menu_product.html', {'form': form}) What should be done in order to resolve this issue TypeError at /vendor/add-Menuproduct/ init() takes 2 positional arguments but 3 were given What should be done in order to resolve this issue TypeError at /vendor/add-Menuproduct/ init() takes 2 positional arguments but 3 were given -
query to get every user data belong
I want to write Query Set that show every User Access To Own IP and Asset_Name from django.db import models from django.contrib.auth.models import User class Asset(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) IP = models.GenericIPAddressField() Asset_name = models.CharField(max_length=255) I want every user see details(IP,Asset_Name) in own user Profile The problem comes when trying to query the database, and using a string compared to an auth.User object. I do not know how to get around this? -
How to create model object that via user foreignkey, FOREIGN KEY constraint failed?
In my view I am creating the object, and in this model that I am creating is one field, name=models.ForeignKey(User, on_delete=models.CASCADE). And I am using ForeignKey because in this oject can be made multiple time by a single user. And I get an error django.db.utils.IntegrityError: FOREIGN KEY constraint failed Here is the model: from django.contrib.auth.models import User ... class Customer_status(models.Model): name = models.ForeignKey(User, null=True, on_delete=models.CASCADE) creation_date = models.CharField(max_length=28) status=models.CharField(max_length = 8) def __str__(self): return str(self.name) + '_' +str(self.id) And in this view I am creating this model: def status_create(request): Customer_status.objects.create ( name=request.user, creation_date=datetime.datetime.now(), status='Pending' ) The thing is that I had OneToOne field on name and I had Unique integrity error, after I changed it to ManyToMany I have the this error django.db.utils.IntegrityError: FOREIGN KEY constraint failed. I am thinking that the error is causing the "name=request.user" in creating step -
How can I implement delete action in viewset in django?
Here is my view file. import json from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.parsers import JSONParser from django.http import JsonResponse from django.core import serializers from .serializers import TodoSerializer from .models import Todo # Create your views here. class TodoView(APIView): def post(self, request): serializer = TodoSerializer(data=request.data) if serializer.is_valid(): serializer.save() print(serializer.data) return JsonResponse(serializer.data, status=200) def get(self, request): obj_list = [] for item in Todo.objects.all(): if item.todo_delete is False: obj_list.append({"todo_id": item.todo_id, "todo_desc": item.todo_desc, "todo_complete": item.todo_complete, "todo_delete": item.todo_delete}) return JsonResponse({"todo": obj_list}, status=200) def update(self, request): return Response("Hello") def delete(self, request): print (request.data) return Response("Hello") I am going to implement delete action for specific todo by passing id. Front End Part is here. try { const res = await axios.delete(`${BASE_URL}/api/todo/${id}/`) } catch (e) { return { success: false, error: e } } And url file is here path('todo/', TodoView.as_view()), But I can see this error Not Found: /api/todo/e709750f-5bb6-4dba-b6b1-966beeeb9c3d/ How can I fix this error? How to set correct delete endpoint and get id from client? -
Django - How to redirect users without hard-coding URLS
I am creating Django Application. We want user to be redirected to new screen on button click, but we don't want to have to hardcode URL. We have a top level screen, and we want to redirect user to screens after they click a button on the Level screen, However, we have multiple level screens so it would't make sense to hardcode each URL for each section of the Level screen. Here is the view for the Level1 Screen as an example: def level1(request): return render(request, 'Levels/level/Welcome1.html') As you can see, we render out Welcome1.html, however, we also have other Welcome screens assosiated with level 1, like Welcome2.html and Welcome3.html. This is the URL for level 1: path('levels/level1/', views.level1, name = "level1") Again, it would't make sense for us to have a URL for each level (level 1, level2) and then all the subscreens for them such as Welcome1, Welcome2. How can I make it so I can associate different screens with a URL and not have to render them out individually? I am not sure how to go about doing this problem. We are working on big project and can give part of budget to someone who helps solve. -
Printing username on stdout with Django + Gunicorn Application
Right now my Django + Gunicorn app is printing only this info: [03.10.2022 19:43:14] INFO [django.request:middleware] GET /analyse/v2/ping - 200 If request is authorized, I would like to show also user (username/email) behind the status code, something like: [03.10.2022 19:43:14] INFO [django.request:middleware] GET /analyse/v2/ping - 200 - useremail@outlook.com If the request is not authorized then write UNAUTHORIZED: [03.10.2022 19:43:14] INFO [django.request:middleware] GET /analyse/v2/ping - 200 - UNAUTHORIZED How can I achieve this with a combination of Django and Gunicorn? Thank you -
Django-filter package how to render fields choices value dynamically?
I'm using Django-filter,I hard coded the model fields choices: models.py MSG_TYPE_CHOICES = ( ('success','success'), ('error','error'), ('warning','warning'), ) class Mymodel(models.Model): typeLevel = models.CharField(max_length=50, blank=True, null=True,verbose_name='MSG TYPE',choices=MSG_TYPE_CHOICES) # eg:exception Notice:the value of MSG_TYPE_CHOICES are the same as the values in typeLevel ,it means value of typeLevel are:success,error,warning . filter.py: class MyFilter(django_filters.FilterSet): class Meta: model = Mymodel fields = ['typeLevel'] views.py: def product_list(request): f = MyFilter(request.GET, queryset=Product.objects.all()) return render(request, 'my_app/template.html', {'filter': f}) template: <form method="get"> {{ filter.form}} </form> My question is instead of hard coded the MSG_TYPE_CHOICES in models.py ,is there any way I can get those value dynamically from the model filed typeLevel ,because I need the value of MSG_TYPE_CHOICES always keep the same with fields typeLevel ,if the value of typeLevel changes ,the MSG_TYPE_CHOICES need change too. -
How to change visibility on div multiple times with javascript and css?
I have a popup in my app: <div id="modal"></div> let modal = document.getElementById('modal') modal.innerHTML = ` <button class="close-button" onclick="close_modal()">Close</button> ` #modal{ width: 30em; height: 24em; overflow: hidden; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); visibility: hidden; } When I click certain button function is triggered which has modal.classList.add('open-modal') in it. .open-modal{ visibility: visible !important; } close_modal function is: function close_modal(){ modal.classList.add('close-modal') } CSS: .close-modal{ visibility: hidden !important; } It works just fine once(i can open and close popup but when I try to open it second time it doesn't. Why is this happening and how to fix it? -
a music app ,where i was trying to display the album detail once it is newlycreated using reverse...recieving the below mentioned error please assist
Traceback (most recent call last): File "C:\Users\Sanath\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\base.py", line 142, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\edit.py", line 184, in post return super().post(request, *args, **kwargs) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\edit.py", line 153, in post return self.form_valid(form) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\edit.py", line 136, in form_valid return super().form_valid(form) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\edit.py", line 65, in form_valid return HttpResponseRedirect(self.get_success_url()) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\views\generic\edit.py", line 125, in get_success_url url = self.object.get_absolute_url() File "C:\Users\Sanath\Desktop\website\music\models.py", line 12, in get_absolute_url return reverse('music:detail',kwargs = {'pk' : self.pk}) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\urls\base.py", line 88, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\Sanath\anaconda3\lib\site-packages\django\urls\resolvers.py", line 828, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'detail' with keyword arguments '{'pk': 11}' not found. 1 pattern(s) tried: ['music/(?P<album_id>[0-9]+)/\\Z'] urls.py from django.urls import path from . import views app_name = 'music' urlpatterns = [ #music/ path('', views.index,name = 'index'), #music/71/ path('<int:album_id>/', views.detail,name = 'detail'), path("register/",views.UserFormView.as_view(),name = 'register'), path("album/add/",views.albumcreate.as_view(),name = 'album-add'), #url pattern for the view albumcreate ] models.py from django.db import models from django.urls import reverse # Create your models here. class album(models.Model): #inherit from models.Model artist = models.CharField(max_length=250) #when migrated to db it will … -
django query with manytomany as list
I'm working with django (4.1) and I have a problem with a QuerySet. models.py class Publication(models.Model): title = models.CharField(max_length=30) class Meta: ordering = ['title'] def __str__(self): return self.title class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) class Meta: ordering = ['headline'] def __str__(self): return self.headline python manage.py shell >>> from many2many.models import Article, Publication >>> qsA = Article.objects.values("id","headline","publications") >>> qsP = Publication.objects.values("id","title") >>> for a in qsA: ... print(a) ... {'id': 1, 'headline': 'A', 'publications': 1} {'id': 1, 'headline': 'A', 'publications': 2} {'id': 2, 'headline': 'B', 'publications': 3} {'id': 2, 'headline': 'B', 'publications': 4} >>> for a in qsP: ... print(a) ... {'id': 1, 'title': 'tA1'} {'id': 2, 'title': 'tA2'} {'id': 3, 'title': 'tB1'} {'id': 4, 'title': 'tB2'} >>> I'd like to have a QuerySet that returns the "headline" of the Articles, and the list of the "title" of the Publication. Something like {'headline': 'A', 'list_publications': 'tA1 tA2'} {'headline': 'B', 'list_publications': 'tB1 tB2'} -
How to translate the route system in django 1 to django 2,3?
In tutorial the author used an old version of urls.py in urlpatterns and I cannot translate url(r'^image/(?P<width>[0-9]+)x(?P<height>[0-9]+)/$') this into path() Thanks a lot I would like to resolve this issue -
! [remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/mighty-island-82287.git' error
I enter git push heroku main and so: Total 0 (delta 0), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-22 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: Traceback (most recent call last): remote: File "/tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/vendor/runtime-fixer", line 8, in <module> remote: r = f.read().strip() remote: File "/usr/lib/python3.10/codecs.py", line 322, in decode remote: (result, consumed) = self._buffer_decode(data, self.errors, final) remote: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte remote: /tmp/codon/tmp/buildpacks/0f40890b54a617ec2334fac0439a123c6a0c1136/bin/steps/python: line 9: warning: command substitution: ignored null byte in input remote: ' is not available for this stack (heroku-22). remote: ! For supported versions, see: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 50c9a488b59502f133b3cce812e40e89000d2414 remote: ! remote: ! We have detected that you have triggered a build from source code with version 50c9a488b59502f133b3cce812e40e89000d2414 remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different … -
when I want to deploy my djnago project to aws elastic beanstalk it gives me error
when I want to deploy my Django project to AWS elastic beanstalk it gives me the error this is my error and I do not know how to fix it -
How to implement async await function in Django application when retrieving information from remote database
I have a Django application where I am retrieving information from remote Oracle database and I populate those information in chart using Chart.js. As you can see in my code, I am calling two times connection to database since I am popul.ating two charts The point is that process of retrieving information sometimes is taking so much time, and I read there is option to include async await option , where I can decrease I/O time. (attach and gngp_ntp is query that I am taking from other .py file) Can someone help me how to make simple async below function. def index(request): cursor1=connections['default'].cursor() cursor1.execute(attach) // execute the query r1= dictfetchall(cursor1) cursor2=connections['default'].cursor() cursor2.execute(gngp_ntp)// execute the query r2= dictfetchall(cursor2) return render(request,'app_sins/ps_capacity.html', {"all_post" : r1,"jokso" : r2}) -
django-imagekit - do not crash when source file does not exist
I have a Django model that has an image and an autogenerated thumbnail: img = ImageField(upload_to=..., max_length=64) img_thumbnail = ImageSpecField([ResizeToFit(width=64, height=64)], source='img') For a number of reasons, the img field may contain a filename that is no longer present in the filesystem. When the file is not there, the view crashes with a FileNotFoundError - No such file or directory: '....png' Is it possible to configure the img_thumbnail field / django-imagekit to fail silently? Also without writing having to catch the exception in the view. -
API Query in Django Rest Framework
I have created an API from Database, I can view the API but I am unable to do a query via URL for example: 127.0.0.1:8000/author?author_id=9, I am not sure where to add the query code. I want to filter using fields. Here is my models.py class AuthorAPI(models.Model): author_id=models.IntegerField() name=models.TextField() author_img_url=models.TextField() title=models.TextField() first_published_at=models.DateTimeField() excerpt=models.TextField() class Meta: db_table = 'view_author' serializers.py from rest_framework import serializers from .models import SortAPI, AuthorAPI class AuthorAPISerializer(serializers.ModelSerializer): class Meta: model=AuthorAPI fields='__all__' views.py from .serializers import APISerializer,AuthorAPISerializer from .models import SortAPI, AuthorAPI from rest_framework.response import Response from rest_framework.decorators import api_view @api_view(['GET']) def getauthor(request): if request.method == 'GET': results = AuthorAPI.objects.all() serialize = AuthorAPISerializer(results, many=True) return Response(serialize.data) -
Django serializer possibility of either creating new object or using an existing
Below is an example input: 'abc_obj': { "comments": string, "ref": string, "customer": 1, "address": { "street": string, "country": string, } } This is the serializer: class ABCObjSerializer(ModelSerializer[ABCObj]): address: AddressSerializer = AddressSerializer(required=False) customer: CustomerSerializer = CustomerSerializer(required=False) class Meta: model = ABCObj fields = "__all__" extra_kwargs = { "created_by": {"read_only": True}, } Is it possible with the existing serializer that I reuse / link the customer with the id=1. And in the next request if there is customer data (like address data in this request) then I create a new customer. The purpose is to enable the user to either create a new record or use an existing one. -
Display selection field in Django template
I 'm trying to find a workable solution for my problem. I have found two similar questions answered before, but still I can't solve it. If we have a class like this: from django.db import models class Consumer(models.Model): SIZES = ( ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ) name = models.CharField(max_length=60) size = models.CharField(max_length=2, choices=SHIRT_SIZES) And I did in my view and template like this (Learned from one tutorial) ***view with combined queries*** def staff_filter(request): qs = Consumer.objects.all() shirt_size= request.GET.get('size') # I have some other queries in between .... if is_valid_queryparam(size) and size!='Choose...': qs = qs.filter(size=consumer.get_size.display()) return qs def filter(request): qs=admin_staff_filter(request) context={ 'queryset':qs, 'consumer':consumer.objects.all() } return render(request, 'filter.html',context) **template*** <div class="form-group col-md-4"> <label for="size">size</label> <select id="size" class="form-control" name="size"> <option selected>Choose...</option> {% for size in consumer.get_size.display %} <option value="{{ size }}">{{size}}</option> {% endfor %} </select> </div> How should I correct it? Thanks! Display selection field in Django template -
Django model: get QuerySet from OneToOne
Let's say I have this model: class Place(models.Model): name = models.CharField(max_length=50) class Restaurant(models.Model): place = models.OneToOneField(Place, on_delete=models.CASCADE) And I have this QuerySet: <QuerySet [<Place: 123>, <Place: 456>]> I would like to get the list of Restaurants associated with the Place. I tried: restaurant_list = Restaurant.objects.filter(place__in=queryset) but it returns me a QuerySet of Place, not Restaurant: <QuerySet [<Place: 123>, <Place: 456>]> How can I get the Restaurant associated with the Place of my QuerySet? -
Changing the order of django objects in site using javascript
On the html page I have a list of songs {% for comp in composition %} .... <p>{{ comp.title }}<p> .... {% endfor %} also each track has two buttons: up and down. How to make it so that when you press the up or down button, the track changes with the neighboring track and so that the position of the tracks also changes in the django database.