Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Young developer facing the multitude of frameworks. What to do?
Hello everyone in the community, I am a young developer in the last year of level 3 engineering and for more than 3 months I have seen several job offers in development just as varied as each other. I use the Django, React, Ionic frameworks and I have some knowledge in java, android, Bootstrap, PHP development. I would like to know what is the attitude to adopt when I find myself facing more and more variable demand requiring other knowledge such as angular, laravel, Hibernate, Spring boot, jQuery, symfony, mongo db, MSSQL, PostgreSQL and sometimes all this is found on the same job offer. Thank you -
Django REST framework catches redirects before URLs names
I have a strange issue: Django REST framework appears to steal my URLs on redirect, even when the URL names are in my urls.py file and are before the REST routers. This is my code: views.py: def project_delete_view(request, id): obj_project = get_object_or_404(Project, id=id) if request.method == "POST": obj_project.delete() return redirect('my-projects') context = { 'project': obj_project.id, } return redirect('my-projects') urls.py: from rest_framework import routers from django.urls import re_path router = routers.DefaultRouter() router.register(r'projects', ProjectViewSet) urlpatterns = [ path('private/my-projects/', my_projects_list_view, name='my-projects'), ] If I comment router.register(r'projects', ProjectViewSet) the redirect works fine. Hardcoding the URL (return redirect('/private/my-projects')) doesn't help. When I click 'delete' in my template and the view is called, I get redirected to /api/projects/36/delete/ , no matter what. The view gets called correctly and the project gets deleted, the issue is only the URL to which the view redirects after the .delete() function. -
How to i go live from localhost with python files??? it is not working just like other normal html php files
I tried uploading my website created with python in localhost with django framework, but it is not working but showing the directories. Usually when a website is developed in PHP, when we upload with the index files the hosting auto fetches which is not happening here. the site made with python has also the index.html file but i have it inside sub folders. So the summarized question is how to move my python website from local server to live? -
`Return` gives wrong json data in output
I am trying to send JSON data from a django rest framework API but the output is modified by the return Response The API: class TransportDirectoryAPIView(APIView): def get(self, request, format=None): state = request.GET["state"] city = request.GET["city"] data = pd.read_csv(r"Suppliers.csv", error_bad_lines=False) data = data.fillna("-") data = data[(data["State"]==str(state)) & (data["City"]==str(city))].reset_index().to_json(orient='records') print("data ", data) return Response(data) now the print gives the following output: data [{"index":296,"Id":297,"Company Name":"ABC","Contact Person Name":"ABC", "Primary Contact Number":"999", "Contact Number 1":9999, "Contact Number 2":"-", "Contact Number 3":"-", "Contact Number 4":"-", "Primary Email":"-", "Secondary Email":"-", "Address":"ABCDE","City":"ABC","Pin Code":"-","State":"ABC","Services":"SXYZYZYZ"},....] But when I check in Postman it seems like this: "[{\"index\":296,\"Id\":297,\"Company Name\":\"abc\",\"Contact Person Name\":\"abc\", \"Primary Contact Number\":\"9999\", \"Contact Number 1\":9999, \"Contact Number 2\":\"-\", \"Contact Number 3\":\"-\", \"Contact Number 4\":\"-\", \"Primary Email\":\"-\",\"Secondary Email\":\"-\",\"Address\":\"ABC\",\"City\":\"ABC\",\"Pin Code\":\"-\",\"State\":\"ABC\",\"Services\":\"XYZYXY\"},.. Why the backslashes are added to the output and how can I correct it ? -
How do i send the data of a form (retrieved from a function of an HTML page) to a function of another HTML page in Django/Python?
The sequence is: - The user fills the 'a' form in the 'A' HTML page.(URL: AppName/A) - The user is directed to 'B' HTML page with other forms to fill.(URL: AppName/A/B) In the python code, How do i send the data of the 'a' form (retrieved from the function corresponding to the 'A' HTML page) to the function corresponding to the 'B' HTML page in views.py ? Notes: I do not want to retrieve the data from the 'A' HTML page in the 'B'HTML page but in the function corresponding to the 'B' HTML page as the user goes from 'A' to 'B' HTML page. Thank you. -
How to make min() and F() work together in Django?
Python 3.7.7, Django 3.0.6 I have this method, that works: def Proliferate (): models.Token.objects.filter(amount__gte=2).update(amount=F('amount') + 2) I also have this method, that technically works: @staticmethod def Cull (): tokens = models.Token.objects.all() for token in tokens: token.amount = min(token.amount, token.county.max_population) token.save() However I assume that the second one is actually making one query for every line, making it extremely unoptimised. I'd like to convert the Cull method to be like Proliferate (which I assume that runs a single query, otherwise what's the point of update?). I've tried this: models.Token.objects.all().update(amount=min(F('amount'),F('county.max_population'))) But it complained that: '<' not supported between instances of 'F' and 'F' So I've browsed for documentation and sites, but I wasn't able to find a simple obvious way to do this. Note: please notice that the min() has to be run between token.amount itself, and token.county.max_population, i.e. from a different table. Here's the model: class Token (models.Model): county = models.ForeignKey(County, on_delete=models.CASCADE) amount = models.PositiveSmallIntegerField() -
what is the best way to add an upvoting function to django
I would appreciate if any one could help me out as i'm new to learning python django. this is my code, i would like someone to give me help, with implementing the best way to add an upvoting function to my code. I would like the user to vote on the post and show the count for each post on index page and detail page one vote per user. this is my code views def index(request): links = Link.objects.order_by('-posted')[:10] context = {'links': links} return render(request, 'links/index.html', context) def detail(request, link_id): link = get_object_or_404(Link, pk=link_id) return render(request, 'links/detail.html', {'link': link}) models from django.db import models from django.contrib.auth.models import User class Link(models.Model): submitter = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) url = models.URLField(blank=True) text = models.TextField(blank=True) votes = models.IntegerField(default=1) posted = models.DateTimeField(auto_now_add=True) edited = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Vote(models.Model): link = models.ForeignKey(Link, related_name='link_votes', on_delete=models.CASCADE) voter = models.ForeignKey(User, related_name='link_voter', on_delete=models.CASCADE) def __str__(self): return self.link.title urls from django.urls import path from . import views app_name = 'links' urlpatterns = [ # ex: /links/ path('', views.index, name='index'), # ex: /links/5/ path('<int:link_id>/', views.detail, name='detail'), # ex: /links/5/vote/ # path('<int:link_id>/vote/', views.vote, name='vote'), ] index page {% if links %} <ol> {% for link in links %} … -
Choices in inherited field
class WagonOptimal(models.Model): ... CAPACITY_CHOICES = [ (5, 5), (6, 6), (7, 7), (8, 8) ] capacity = models.IntegerField(null=True, blank=False, choices=CAPACITY_CHOICES) class WagonBelMix(WagonOptimal): BELMIX_CAPACITY_CHOICES = WagonOptimal.CAPACITY_CHOICES + [ (9, 9), (10, 10), (11, 11), (12, 12), (13, 13) ] Lets say i have something like above. Is it possible to change choices in inherited capacity field? (for BELMIX_CAPACITY_CHOICES). -
How to display the names instead of pk in the list viewset in Django Rest Framework?
I've designed an API to add songs and create a playlist. models.py: class Song(models.Model): title = models.CharField(null=False, blank=False, max_length=400) artist = models.CharField(null=False, blank=False, max_length=400) def __str__(self): return f"{self.title} by {self.artist}" class Playlist(models.Model): name = models.CharField(null=False, blank=False, max_length=100) songs = models.ManyToManyField('Song', blank=True, related_name='playlists') serializers.py: class SongSerializer(serializers.ModelSerializer): class Meta: model = Song fields = ['title', 'artist'] extra_kwargs = {'playlists': {'required':False}} class PlaylistSerializer(serializers.ModelSerializer): class Meta: model = Playlist fields = ['name', 'songs'] extra_kwargs = {'songs':{'required':False}} views.py: class SongViewSet(viewsets.ModelViewSet): queryset = Song.objects.all() serializer_class = SongSerializer class PlaylistViewSet(viewsets.ModelViewSet): queryset = Playlist.objects.all() serializer_class = PlaylistSerializer But when I do a get request on the Playlist, I get the results as the following: { "name": "Classic Hits", "songs": [ 1, 3, 4 ] } I want the songs' names to be displayed instead of their PKs in the playlist.How do I do that? -
AttributeError: type object 'Like' has no attribute 'like'
** how i solve this error i dont know In views.py", line 120, in likePost Like.like(post,user) AttributeError: type object 'Like' has no attribute 'like' ............................................................................................................................................................................... ** views.py #############Like def likePost(request): post_id=request.GET.get("likeId",'') print(post_id) post=Post.objects.get(pk=post_id) user= request.user like=Like.objects.filter(post= post,user= user) liked=False if like: Like.dislike(post,user) else: liked=True Like.like(post,user) resp={ 'liked':liked } response=json.dumps(resp) return HttpResponse(response,content_type="application/json") template.html <button type="button" class="btn-xs btn-info like btn-sm "id="{{i.id}}"> {% if i in liked_post %} <a href="{%url 'like_dislike_post'%}" style="color: white;" id="like_text">Liked</a> </button> {% else %} <a href="{%url 'like_dislike_post'%}" style="color: white;" id="like_text">Like</a> </button> {% endif %} $(".like").click(function(e){ var id=this.id;//$(this).attr(.id); var href=$('.like').find('a').attr('href'); console.log(href,id) e.preventDefault(); $.ajax({ url:href, data:{'likeId':id}, success:function(response) { if (response.liked) { $('#like_text').html("Liked") } else { $('#like_text').html("Like") } } }) }); models.py class Like(models.Model): user = models.ManyToManyField(User,related_name="linkingUser") post = models.OneToOneField(Post,on_delete=models.CASCADE) @classmethod def liked(cls,post,liking_user): obj,create= cls.objects.get_or_create(post=post) obj.user.add(liking_user) @classmethod def liked(cls,post,disliking_user): obj,create= cls.objects.get_or_create(post=post) obj.user.remove(disliking_user) # @classmethod # def def __str__(self): return str(self.post) -
from_db_value() missing 1 required positional argument: 'context'
Trying to create google login for django using googleapiclient and oauth2client. I am able to open home page, and getting redirected to google login successfully. Once after sign-in, it is redirecting to home page where I'm receiving this error. Reference link/tutorial views.py import httplib2 from googleapiclient.discovery import build from django.http import HttpResponseBadRequest from django.http import HttpResponseRedirect from .models import CredentialsModel from gfglogin import settings from oauth2client.contrib import xsrfutil from oauth2client.client import flow_from_clientsecrets from oauth2client.contrib.django_util.storage import DjangoORMStorage from django.shortcuts import render from httplib2 import Http def home(request): print("*****home*****") status = True if not request.user.is_authenticated: return HttpResponseRedirect('admin') storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() print(f"credential: {credential}") print(f"storage: {storage}") try: access_token = credential.access_token resp, cont = Http().request("https://www.googleapis.com/auth/gmail.readonly", headers={'Host': 'www.googleapis.com', 'Authorization': access_token}) except: status = False print('Not Found') return render(request, 'index.html', {'status': status}) ################################ # GMAIL API IMPLEMENTATION # ################################ # CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this # application, including client_id and client_secret, which are found # on the API Access tab on the Google APIs # Console <http://code.google.com/apis/console> FLOW = flow_from_clientsecrets( settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, scope='https://www.googleapis.com/auth/gmail.readonly', redirect_uri='http://127.0.0.1:8080/oauth2callback', prompt='consent') def gmail_authenticate(request): print("*****gmail_authenticate*****") storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() print(f"credential: {credential}") if credential is None or credential.invalid: … -
Configuring loggers in Django + django_extensions is overrides by django_extensions
I've built a server using Django, and I configured the logging of the server to have different logs for ERROR, WARNING, and INFO, and a log in the console (in INFO level). Until I added django_extensions to the modules of the project, everything worked fine, but now the INFO log configuration is not what I configured. I think that the configuration is overridden by django_extensions, but I can't find a place to change it back. The configuration: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '[{asctime}] [{levelname}]: {message}', 'style': '{', }, 'vv': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', }, 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'info.log', 'formatter': 'verbose', }, 'error_file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': 'error.log', 'formatter': 'verbose', }, 'warning_file': { 'level': 'WARNING', 'class': 'logging.FileHandler', 'filename': 'warning.log', 'formatter': 'verbose', }, }, 'loggers': { 'django': { 'handlers': ['console', 'file', 'error_file', 'warning_file'], 'level': 'DEBUG', 'propagate': True, }, }, } INSTALLED_APPS: INSTALLED_APPS = [ 'abc.apps.ABCConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'django_user_agents', ] I'm using python 3.7.6, Django 2.2.9, django-extensions 2.2.9. -
Django query Many to Many fields and get queryset based on each filter
I have the following problem to filter my group table with its realizations so that I only get the data set that matches the filter settings. My models look like this: Group: class Group(models.Model): name = models.CharField(max_length=35) products = models.ManyToManyField('Product') subgroups = models.ManyToManyField('Subgroup') user = models.ForeignKey(User, on_delete=models.CASCADE) is_hidden = models.BooleanField(default=False) Subgroup: class Subgroup(models.Model): name = models.CharField(max_length=35) products = models.ManyToManyField('Product') order = models.IntegerField(null=True) is_hidden = models.BooleanField(default=False) Product: class Product(models.Model): name = models.CharField(max_length=35) is_hidden = models.BooleanField(default=False) Currently, my query returns all groups that match at least one of the filters, but I want to apply the filter per model. non_hidden_groups = Group.objects.filter(user=user, is_hidden=False).filter(subgroups__is_hidden=False).filter(products__is_hidden=False) The problem is that I get a queryset back that exclude groups that are not hidden, but for example contains subgroups that are hidden. I only want to exclude: all groups that are marked as is_hidden all subgroups in the group that are marked as is_hidden all products in the group that are marked as is_hidden all products in a subgroup in a group that are marked as is_hidden Has anyone an idea how to do this without converting the queries into a list? -
Running selenium chromedriver on heroku w/ django management command
I have already tried a few different things to figure out this issue. I try to run a custom django management command which is supposed to run a selenium task using chromedriver. However, when I run the command on heroku, I get the following error: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 76, in start stdin=PIPE) File "/app/.heroku/python/lib/python3.6/subprocess.py", line 729, in __init__ restore_signals, start_new_session) File "/app/.heroku/python/lib/python3.6/subprocess.py", line 1364, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: '/app/../chromedriver': '/app/../chromedriver' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/app/games/management/commands/new_data.py", line 6, in handle updater = UpdateData() File "/app/games/management/commands/update_data.py", line 27, in __init__ self.browser = webdriver.Chrome(executable_path=self.path, options=self.options) File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 73, in __init__ self.service.start() File "/app/.heroku/python/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 83, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home Which leads me to believe that I must have … -
AJAX pagination in my Django project pointing to 'page not found'
My django app has a favorite section with a favorite list for the user to save favorite products in it. For now the user can navigate through the favorite list using regular Django pagination set on 5 items per page. But I want a smoother user experience and I want to use AJAX to display the content. views.py: def pagination(request): model = SavedProduct.objects.all() number_of_item = 5 paginatorr = Paginator(model,number_of_item) first_page = paginatorr.page(1).object_list page_range = paginatorr.page_range context = { 'paginatorr':paginatorr, 'first_page':first_page, 'page_range':page_range } if request.method == 'POST': page_n = request.POST.get('page_n', None) serializer = pagination_ser(paginatorr.page(page_n).object_list, many=True) return JsonResponse(serializer.data, safe=False) return render(request, 'register/ajax.html',context) urls.py: app_name = 'register' urlpatterns = [ path('pagination/', views.pagination, name='pagination'), ] ajax.html: <body> <div id="register_list"> {% for i in first_page %} <h2>{{i.sub_product.real_name}}</h2> {% endfor %} </div> {% for i in page_range %} <a id='fav_nav' href="{{i}}">{{i}}</a> {% endfor %} <script> $('#fav_nav').on('click',function(event) { event.preventDefault(); console.log('ok') var page_n = $(this).attr('href'); $.ajax({ type: "POST", url: "{% url 'register:pagination' %}", data : { page_n : page_n, csrfmiddlewaretoken: '{{ csrf_token }}', }, success: function (resp) { $('#register_list').html('') $.each(resp, function(i, val) { $('#register_list').append('<h2>' + val.name + '</h2>') }); }, error: function () {} }); }); </script> </body> But event.preventDefault() is not working, whenever I click on a … -
Popup Django with url
I want to create specific popup that also can be opened by URL. Let us say, there "example.com/gallery". On this page there are some small-sized pictures. As for now, I use JavaScript to open popup by clicking on picture, and redraw image in it. But I cannot open it by URL. So how to use URL to get to gallery page and and open exact popup. "example.com/gallery/picture-1" or "example.com/gallery?picture=1" -
OSError: [Error 24] Too many open files: || Slow Application
My app got too many requests to celery and each request basically opens a headless chrome using pyppeteer and does some operations. Now when i saw celery logs, following is the error i got. So, there were too many socket connections created which made the entire application slow (**VERY VERY SLOW).** Can someone please suggest a workaround to close all these open socket connections because i cannot afford to restart the machine as its in production. -
DRF what's the difference between serializers(many=True) vs ListField(serializer())
When should I use each of the following? * MySerializer(many=True) * serializers.ListField(child=MySerializer()) -
Django fetch data from table that refers the given table as foreign key
I have seen several examples of using select_related to query foriegn key related data in queryset. Including this example. But I want to do it in reverse way as explained below. name = models.CharField(max_length=50) author = models.ForeignKey(Author) class Author(models.Model): name = models.CharField(max_length=50) I have seen queryset to fetch the data while querying the Book because Author is specified in books.Like this books = Book.objects.all().select_related("author") But I need to query Author and then get all the books related with it.Is there any way to do that. -
Page not found at /posts even though View, template and Url config in defined
I'm building a simple blog app and trying to use slugs in the URL. I have defined the URL as well as the view and the template, however when I try to access the URL /blog/posts, it throws a 404 that too from an entirely different view. All other URLs work, just having an issue with above mentioned one. url.py urlpatterns = [ path('',views.IndexView.as_view(),name='index'), path('create/',views.PostCreateView.as_view(),name='blog-create'), path('posts/',views.UserPosts.as_view(),name='user-posts'), path('<slug:slug>',views.PostDetailView.as_view(),name='blog-detail'), path('list/',views.PostListView.as_view(),name='blog-list'), path('<slug:slug>/comment/',views.create_comment,name='comment'), ] Associated Views in order class PostDetailView(LoginRequiredMixin,generic.DetailView): model = Post template_name = 'blog/post_detail.html' context_object_name = 'post' slug_url_kwarg = 'slug' slug_field = 'slug' class UserPosts(LoginRequiredMixin,generic.ListView): model = Post context_object_name = 'posts' template_name = 'blog/user_post_list.html' def get_queryset(self): posts = super().get_queryset() queryset = posts.objects.all(user= self.request.user) return queryset the 404 error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/posts Raised by: blog.views.PostDetailView No post found found matching the query template directory tree blog/ templates/ blog/ user_post_list.html Also earlier I had a problem with path('/list') as well however it got solved when I removed the '/' from the slug URL, I don't know why it worked, can anyone explain? -
DJANGO - How to display a text form field next to checked checkboxes
I am creating an application that allows you to add predefined services to an invoice. When creating a new invoice, you can select services using checkboxes. I would like to add the text field to specify the quantity after selecting the checkbox. So you check the checkbox and text field appears next to it where you can enter the quantity. I would like to store this data in the database after creating a new invoice. I am not sure how can I achieve this. Do I need JS or only Django is enough? models.py class Service(models.Model): nazwa = models.CharField(max_length=100) cena = models.FloatField() def __str__(self): return f'{self.nazwa} - cena: {self.cena}zł' class Invoice(models.Model): forma_platnosci_wybor = [ ('przelew', 'przelew'), ('gotowka', 'gotówka') ] numer = models.CharField(max_length=30) firma = models.ForeignKey(Company, on_delete=models.CASCADE) forma_platnosci = models.CharField(verbose_name='forma płatności', max_length=75, choices=forma_platnosci_wybor) data_badania = models.DateField() data_wystawienia_faktury = models.DateTimeField() usluga = models.ManyToManyField(Service, verbose_name='usługi') rabat = models.IntegerField(verbose_name='rabat [%]', blank=True, null=True) def __str__(self): return self.numer forms.py class NewInvoiceForm(forms.ModelForm): class Meta: model = Invoice fields = '__all__' exclude = ['numer', 'data_wystawienia_faktury'] widgets = { 'usluga' : forms.CheckboxSelectMultiple, 'data_badania' : DateInput(), } -
Send CSV to JSON Converted data in django rest framework
I am trying to work on a directory in which the csv is read by pandas and then after applying some filters the data is converted into json and send the same to the frontend: Here's how I am doing it class TransportView(APIView): def get(self, request, format=None): state = request.GET["state"] city = request.GET["city"] data = pd.read_csv(r"abc.csv", error_bad_lines=False) data = data.fillna("-") data = data[(data["State"]=="foo") & (data["City"]=="bar")].reset_index().to_json(orient='records') print("data ", data) return Response(data) How can I do it more efficiently such that the data being sent is in much more cleaner Format? -
Insert data into sqlite using dump file
I have a mysql dump file and for some reason in need to migrate to django sqlite. Not sure how to restore the data using dump file in sqlite. Everywhere I can find restoring in mysql psql..... -
how to create serializer of registering new user
How can I write this code in a serialized view its code to register the new user but I don't know how to work with 2 models in same serializers. def createDonerView(request): template = 'doner/create_doner.html' form1 = CreateUserForm() form2 = CreateDonerForm() if request.method == 'POST': form1 = CreateUserForm(request.POST) form2 = CreateDonerForm(request.POST) if form1.is_valid() and form2.is_valid(): user = form1.save() profile = form2.save(commit=False) profile.user = user profile.save() return redirect('index') -
Django script does not refresh html page with jQuery
I have created a django app that give me the possibility to collect data (using a form) and display it in a table. In the table I have a button, "EDIT" that give me the possibility, using jQuery, to edit the value filled. To do that I have created a table using a includes html property as following: <table class="table table-sm" id="myTable" style="width:100%"> <thead> <tr> <th>Codice Commessa</th> <th>Ragione Sociale/Nome e Cognome</th> <th></th> </tr> </thead> <tbody> {% include 'commesse/includes/partial_book_list.html' %} </tbody> <tfoot> </tfoot> </table> The partial_book_list.html have the following code: {% for commessa in commesse %} <tr> <td>{{commessa.codice_commessa}}</td> <td>{{commessa.nome_cliente}}</td> <td> <button type="button" class="btn btn-warning btn-sm js-update-book" data-url="{% url 'book_update' commessa.id %}"> <span class="glyphicon glyphicon-pencil"></span> Edit </button> </td> </tr> {% endfor %} The edit button is linked to an ajax call that give me the possibility to modify the data. All works great but when I try to save the edit form instead refresh the partial_book_list.html, all data in table disappear and I have to refresh the page to show them again. Where is the issue in my code: var saveForm = function () { var form = $(this); $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function (data) { …