Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
All the datas are populated into a single row
I am a beginner in scraping. I have scraped some data. Here are two problems: All of the data are populated into a single row and every time when I refresh the page, each time the data is saved into the database. import requests from django.shortcuts import render, redirect from bs4 import BeautifulSoup from .models import Content toi_r = requests.get("some web site") toi_soup = BeautifulSoup(toi_r.content, 'html5lib') toi_headings = toi_soup.findAll("h2", {"class": "entry-title format-icon"})[0:9] toi_category = toi_soup.findAll("a", {"class": ""})[0:9] toi_news = [] toi_cat =[] for th in toi_headings: toi_news.append(th.text) for tr in toi_category: toi_cat.append(tr.text) #saving the files in database n = Content() n.title = toi_news n.category = toi_cat n.save() -
Django rest: Dynamically include or exclude Serializer class fields
I want filds of serializer dynamical include or exclude.In application after each lesson there will be a quiz but there are moments there are no quiz of the lesson, for this I need to create dynamic fields for Serializers. I try by docs DRF. But my code doesnt work quiz/models.py class Quiz(TrackableDate): name = models.CharField(max_length=100) description = models.CharField(max_length=70) slug = models.SlugField(blank=True, max_length=700, default=None) is_active = models.BooleanField(default=False) def __str__(self): return self.name course/views.py class AuthLessonDetailSerializer(AuthLessonSerializer): quiz = serializers.CharField(source='quiz.slug') class Meta(LessonSerializer.Meta): fields = AuthLessonSerializer.Meta.fields + \ ('description', 'link', 'quiz') def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super( ).__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) error Got AttributeError when attempting to get a value for field `quiz` on serializer `AuthLessonDetailSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Lesson` instance. Original exception text was: 'NoneType' object has no attribute 'slug'. -
Can't import ObtainAuthToken
I am new to Django. In the course that i'm using he is importing ObtainAuthToken like this: from rest_framework.authtoken.views import ObtainAuthToken But when i try to do the same thing i get this exception: Abstract base class containing model fields not permitted for proxy model 'TokenProxy'. What am i doing wrong? I have added both my app and 'rest_framework' to my Installed_Apps. If this needs clarification i can send my views and urls files also. Thanks :) -
How do websites like ytmate download the video in the browser
I have been trying to make a web app for a little college project. The app is just like ytmate.com where you can download youtube or other platform’s video on your local machine. I am using Django and pytube to make the app. The problem is, the app does not download the video from the browser. It just downloads it in the path the app is in. The problem with this is that when the app will be deployed, anyone who uses it will keep on downloading the app on the external server the app has been hosted on. How can I make sure it downloads in the browser of the user and not on the server? I already thought of first downloading the app on the server and return the file in the user’s browser by using content headers. But that’s not the optimal solution and it will slow down the process. I just need some guidance on how this app can be implemented. Sorry about not posting the code. I just need to know how this app could be implemented. -
How to generate a MongoDB file from Postgres data
how to generate a MongoDB file from Postres data Or more exactly generate a JSON file (from Django using Postgres as Database) to integrate it via an API-Rest in a MongoDB database. -
Apache logs with WSGI ModuleNotFoundError
According to Bitnami's documentation, I've followed their desired steps Enable WSGI configuration for the Django application Enable predefined virtual hosts for a Django project Configure Django project for public access Create a custom virtual host In the end of the documentation, it states You should now be able to browse to your project at http://SERVER-IP/PROJECT/APP. In this case SERVER-IP: 35.178.211.120 PROJECT: tutorial APP: hello_world If I go to the following locations http://35.178.211.120/ http://35.178.211.120/tutorial/ http://35.178.211.120/tutorial/hello_world I get Internal Error 500. If I check the logs /home/bitnami/stack/apache2/logs [Tue Sep 29 18:33:16.858668 2020] [wsgi:error] [pid 1473] [remote 109.51.236.49:57609] ModuleNotFoundError: No module named 'PROJECT' -
Django URL tag not working - NoReverseMatch
I know we aren't supposed to use stackoverflow for debugging but i've been trying to fix this in the last 10 hours and I feel hopeless, my apologies. #main project urls.py: urlpatterns = [ ... path('accounts/',include('employee.urls')), ... ]... #employee.urls: urlpatterns = [ ... path('employees/', views.display_employees), path('edit/<str:employee_ssn>/', views.edit_employee), ... ] #views.py - edit_employee being used only for testing by now def display_employees(request): logged_user = request.user queryset = Employee.objects.filter(company=logged_user.company) context = { 'employees': queryset } return render(request, 'employees.html', context) def edit_employee(request, employee_ssn): context = {} emp = Employee.objects.filter(ssn=employee_ssn) context = { 'employee_list': emp } return render(request, 'edit-employee.html', context) #employees.html <ul> {% for obj in employees %} <li>{{ obj.name }}</li> <li>{{ obj.ssn }}</li> <li>{{ obj.email }}</li> <li><a href="{% url '/accounts/edit/' obj.ssn %}">edit</a></li><br> {% endfor %} </ul> #edit-employee.html <ul> {% for obj in employee_list %} <li>{{ obj.name }}</li> <li>{{ obj.ssn }}</li> <li>{{ obj.email }}</li> {% endfor %} </ul> When it is clicked on edit it says: Exception Type: NoReverseMatch Exception Value: Reverse for '/accounts/edit/' not found. '/accounts/edit/' is not a valid view function or pattern name. But if the url http://localhost:8000/accounts/edit/<employee_snn>/ is typed on the browser, edit-employee.html renders normally. It also says the error is in my base template at line 0 -
Float() argument errors in Django
I was trying to integrate the Machine Learning algorithm in Django. But I am having the following error: I don't know why I am getting this error though I have passed the value properly as far as I am aware of. Here I have included the codes too: Index.html file: Views.py file: Please help me out with this problem. -
Django changing datefield to arrayField
I'm currently migrating my whole project to PostgreSQL. I have 2 fields that I'd like to change to ArrayField, but I encountered this error. Here's the former code: weight = models.FloatField(max_length=20, blank=True, null=True) date = models.DateField(auto_now_add=True) Here's what I've changed: weight = ArrayField( models.FloatField(max_length=20, blank=True, null=True) ) date = ArrayField( models.DateField(auto_now_add=True) ) (ArrayField is imported) When I'm trying to use makemigrations there are no errors. But, when I use the migrate command I get this error django.db.utils.ProgrammingError: cannot cast type date to date[] -
how to repeat a peice of code in django html?
i am new to django and i have a peice of code that i need to repeat it for 10 times but i dont know how to make it repeatable. here you can see the code i wanna use 10 times.it is for <<region 1>> and i want to use it to make region 1 to region 10.all the "1"s in "href" and "id" and ... should be replaced by 2,3,4,...,10 . <div class="card"> <div class="card-header background"> <a class="card-link text-dark" data-toggle="collapse" href="#collapseOne"> Region 1 </a> </div> <div id="collapseOne" class="collapse show" data-parent="#accordion" > <table class="table table-striped table-condensed "> <thead> <tr> <td scope="col" class="text-secondary"></td> <td scope="col" class="text-secondary ">MeterNumber</td> <td scope="col" class="text-secondary text-center">Data</td> <td scope="col" class="text-secondary text-center">Chart</td> <td scope="col" class="text-secondary text-center">Detail</td> </tr> </thead> <tbody> {% for each in objectlist %} {% if each.region == 1 %} <tr> <td style="width: 7%" scope='row' class="align-middle pl-3"> {% load static %} <img src="{% static "images/meter.svg" %}" alt="My image" height="35" width="35">{% if each.mode == 2 %}<span class="dot-online padding-0 align-bottom"></span>{% endif %}{% if each.mode == 1 %}<span class="dot-notconf align-bottom"></span>{% endif %}{% if each.mode == 3 %}<span class="dot-maintenance align-bottom"></span>{% endif %} <td style="width: 12%" class="text-secondary align-bottom table-row" id="{{ each.id }}" data-href="http://127.0.0.1:8000/specificMeter/" ><h6> {{ each.MeterBodyNumber }} </h6></td> <td style="width: 22%" class="text-secondary … -
Logout button is not showing in Django Todowoo app
Logout button i s not showing up in my Browser -
ForeignKey relationship on two fields which are unique together
I'd like to make a relationship like so in django: class ColorModel(models.Model): article = models.ForeignKey(ArticleModel, to_field='name', on_delete=models.CASCADE) color = models.CharField(max_length=10) class Meta: unique_together = ('article', 'color') class TaillesModel(models.Model): article = models.ForeignKey(ColorModel, on_delete=models.CASCADE) color = models.ForeignKey(ColorModel, on_delete=models.CASCADE) size = models.CharField(max_length=10) quantity = models.IntegerField() So each article has multiple colors, and each of those colors has multiple sizes in different quantities. However, this gives me those errors: Reverse accessor for 'TaillesModel.article' clashes with reverse accessor for 'TaillesModel.color'. HINT: Add or change a related_name argument to the definition for 'TaillesModel.article' or 'TaillesModel.color'. front.TaillesModel.color: (fields.E304) Reverse accessor for 'TaillesModel.color' clashes with reverse accessor for 'TaillesModel.article'. HINT: Add or change a related_name argument to the definition for 'TaillesModel.color' or 'TaillesModel.article'. I don't understand what related_name is supposed to be set to here. Thanks in advance for your help. -
Trouble Uploading files with Django Rest Framework GenericViewSet class
I know there are lots of questions with answers about uploading files with Django but none of the ones I have read have helped me. Many answers say I need to get my uploaded files from request.FILES but I have seen answers saying that's deprecated. Django Rest Framework 3: Uploading files without request.FILES. Anyways here is my code: My model: class DamagePhoto(models.Model): ... omitted for brevity ... damage = models.ForeignKey(Damage, related_name='photos', on_delete=models.CASCADE) photo = models.ImageField(max_length=256, upload_to=get_image_path, blank=True, null=True) side = models.CharField(max_length=16, choices=choices) My view: class VehicleDamagePhotoViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): serializer_class = DamagePhotoSerializer queryset = DamagePhoto.objects.all() lookup_field = 'uid' lookup_url_kwarg = 'uid' lookup_value_regex = '[0-9a-f-]{36}' ordering_fields = ['modified', ] ordering = ['modified'] def get_serializer_context(self): print(f"get_serializer_context() called. request.FILES is {self.request.FILES}.") return {'request': self.request} def get_damage(self, damage_uid): return Damage.objects.get(uid=damage_uid) def get_queryset(self): return self.queryset.filter(damage__uid=self.kwargs['damage_uid']) def perform_create(self, serializer): print(f"preform_create() called request.FILES is {self.request.FILES}.") return serializer.save(damage=self.get_damage(self.kwargs['damage_uid'])) The serializer: class DamagePhotoSerializer(serializers.ModelSerializer): @transaction.atomic def create(self, validated_data, *args, **kwargs): request = self.context['request'] print(f"serializer create request.FILES is {request.FILES}.") return super(DamagePhotoSerializer, self).create(validated_data=validated_data, *args, **kwargs) class Meta: model = DamagePhoto fields = ('__all__') The part of my unit test that fails: url = reverse("vehicle:damagephoto-list", kwargs={'damage_uid': new_damage.uid}) image_path_1 = '/Users/red/myproject/test_data/photos/test_image.jpg' file_ob = {'photo': ('test_image.jpg', open(image_path_1, "rb"))} data = { 'file': file_ob, … -
Django as backend for React native mobile app, How can we authenticate users with social media signup?
Using Django Rest framework we can support mobile apps, for websites Django can authenticate users based on social media using Allauth library. When user signup with Facebook ,a new tab opens and authenticate user with permission. How can we do this for mobile apps ? I think Standard packages like AllAuth wont support it. I do not need the codes, but any guidance will be useful -
How can I update multiple models using Django's class based views?
I have seen similar questions but the question was not explained in a way that explains my current scene. I have this in my models.py: class CustomUser(AbstractUser): USER_TYPE = ((1, 'HOD'), (2, 'Staff'), (3, 'Student')) user_type = models.CharField(default=1, choices=USER_TYPE, max_length=1) class Student(models.Model): course = models.ForeignKey( Course, on_delete=models.DO_NOTHING, null=True, blank=False) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) gender = models.CharField(max_length=1, choices=GENDER) address = models.TextField() profile_pic = models.ImageField(upload_to='media') session_start_year = models.DateField(null=True) session_end_year = models.DateField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) In my forms.py, I have this: class StudentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StudentForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' class Meta: model = Student fields = ['course', 'gender', 'address', 'profile_pic', 'session_start_year', 'session_end_year'] widgets = { 'session_start_year': DateInput(attrs={'type': 'date'}), 'session_end_year': DateInput(attrs={'type': 'date'}), } class CustomUserForm(forms.ModelForm): email = forms.EmailField(required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) password = forms.CharField(widget=forms.PasswordInput) widget = { 'password': forms.PasswordInput() } def __init__(self, *args, **kwargs): super(CustomUserForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' def clean_email(self): if CustomUser.objects.filter(email=self.cleaned_data['email']).exists(): raise forms.ValidationError("The email is already registered") return self.cleaned_data['email'] class Meta: model = CustomUser fields = ('first_name', 'last_name', 'email', 'username', 'password', ) help_texts = {'username': None} I created a form using this context: context = {form': [CustomUserForm(), StudentForm()]} Now, I am trying to … -
How to fix locking failed in pipenv?
I'm using pipenv inside a docker container. I tried installing a package and found that the installation succeeds (gets added to the Pipfile), but the locking keeps failing. Everything was fine until yesterday. Here's the error: (app) root@7284b7892266:/usr/src/app# pipenv install scrapy-djangoitem Installing scrapy-djangoitem… Adding scrapy-djangoitem to Pipfile's [packages]… ✔ Installation Succeeded Pipfile.lock (6d808e) out of date, updating to (27ac89)… Locking [dev-packages] dependencies… Building requirements... Resolving dependencies... ✘ Locking Failed! Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/pipenv/resolver.py", line 807, in <module> main() File "/usr/local/lib/python3.7/site-packages/pipenv/resolver.py", line 803, in main parsed.requirements_dir, parsed.packages, parse_only=parsed.parse_only) File "/usr/local/lib/python3.7/site-packages/pipenv/resolver.py", line 785, in _main resolve_packages(pre, clear, verbose, system, write, requirements_dir, packages) File "/usr/local/lib/python3.7/site-packages/pipenv/resolver.py", line 758, in resolve_packages results = clean_results(results, resolver, project) File "/usr/local/lib/python3.7/site-packages/pipenv/resolver.py", line 634, in clean_results reverse_deps = project.environment.reverse_dependencies() File "/usr/local/lib/python3.7/site-packages/pipenv/project.py", line 376, in environment self._environment = self.get_environment(allow_global=allow_global) File "/usr/local/lib/python3.7/site-packages/pipenv/project.py", line 366, in get_environment environment.extend_dists(pipenv_dist) File "/usr/local/lib/python3.7/site-packages/pipenv/environment.py", line 127, in extend_dists extras = self.resolve_dist(dist, self.base_working_set) File "/usr/local/lib/python3.7/site-packages/pipenv/environment.py", line 122, in resolve_dist deps |= cls.resolve_dist(dist, working_set) File "/usr/local/lib/python3.7/site-packages/pipenv/environment.py", line 121, in resolve_dist dist = working_set.find(req) File "/root/.local/share/virtualenvs/app-lp47FrbD/lib/python3.7/site-packages/pkg_resources/__init__.py", line 642, in find raise VersionConflict(dist, req) pkg_resources.VersionConflict: (importlib-metadata 2.0.0 (/root/.local/share/virtualenvs/app-lp47FrbD/lib/python3.7/site-packages), Requirement.parse('importlib-metadata<2,>=0.12; python_version < "3.8"')) (app) root@7284b7892266:/usr/src/app# What could be wrong? -
Viewing Answer To Previous Question in Django using POST and AJAX
So I am trying to make a Quiz website for which I have chosen django as backend and sqlite as database temporarily. I have set a pager and previous and next button in the page. Now for going forward There is no problem but when I go backwards I want the server to remember what the user answered before and make that radio button active. I am very new in web dev and I am sry if this question is obvious. Also I am eager to use AJAX calls so that the page doesn't refresh when I change the Question.Also pls feel free to recommend a better method of achieveing the above -
Django Flatpage Catchall URLConf and Name for `url` Templatetag
I've gone back and forth between these two flatpage URL patterns: urlpatterns += [ # path('about', views.flatpage, {'url': '/about'}, name='about'), re_path(r'^(?P<url>.*)$', views.flatpage), ] When using the explicit path, I can use the name in my templates like so: <a href="{% url 'about' %}">About</a> But when using the catchall, I can't figure out whether this is possible. I've got quite a few flatpages (maybe a dozen or more, and I'll likely add more later), so having the catchall is an attractive option. However, I really like being able to use the url templatetag. Can I get the best of both worlds? -
Restart Apache in Lightsail Terminal
As I found a blocker in one approach to make a Django app production ready I've gone with a different approach documented here. In particular, this question is about this step where it says «Restart Apache for the changes to be taken into effect» and has the following associated command sudo /opt/bitnami/ctlscript.sh restart apache Thing is, ctlscript.sh isn't in that folder but in /opt/bitnami/stack. Then, when running in that forder sudo ctlscript.sh restart apache I get this error sudo: ctlscript.sh: command not found The file is there so I thought it would be something related with permissions (as pointed here). So, ran The script is in the right folder, so the problem points to incorrect permissions. sudo chmod 755 ctlscript.sh but running the command to restart Apache got me into the same "command not found" error. -
Django do not reload fixture for some test cases
For every test class I generated base .json fixture with data. It is pretty clear and fast way, because I do not need to spent time to generate data. Any additional data I can generate with factories directly in test. class ProfileViewTests(MyProjectTestCase): fixtures = [os.path.join('compiled', 'test_companies_and_users.json')] def test1(self): pass def test2(self): pass The issue that the loading of some fixtures is takes up to 15 sec., because they creating a huge piece of test data environment. And now 70% of time I'm wasting to loading fixtures after every test case. The upside is because when we update objects we do not need care about flushing this data, but downside that time is increasing with every test. I can move some data to setUpTestData, but revisit all this data for all this tests is almost impossible. My question is there a decorator to say some tests cases do not reload fixtures, if they not modify data. @do_not_flush_data_from_database_for_next_test_case_from_this_class def get_users_test(self): pass Or any other way to speed up this -
Django user authentication not working on every subpage
i have strange (and probable simple) problem with user authentication in Django. I added to base.html file this code: {% if user.is_authenticated %} <p>{{user.get_username}} is logged in</p> <a href="{% url 'logout' %}">logout</a> {% else %} <p>You are not logged in!</p> <a href="{% url 'login' %}">login</a></a> {% endif %} Then i added this line to every other template: {% extends "base.html" %} It looks good because every subpage display this lines of code, unfortunately sometimes is displaying code when user is authenticated and sometimes where he is not authenticated.For example when i switch between two subpages once i get information that user with his login is logged, on this second webpage i get information that i am not logged in and when i come back to that first subpage i am again authenticated... How could i change it? What could be a problem? my views about login: def login_user(request): login_user = {} login_user.update(csrf(request)) return render_to_response('login.html', login) def auth_view(request): username = request.POST.get('username', '') password = request.POST.get('password', '') user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: auth.login(request, user) return redirect('loggedin') else: return HttpResponseRedirect('invalidlogin') def logged_in(request): return render_to_response('loggedin.html', {'user': request.user}) and my 'login' urls: path('login', views.login, name='login'), path('authorized', views.auth_view, name='authorized'), path('loggedout', … -
rendering forms into inherited html take me to the base html page
I'm new to Django. I've a base HTML page "base.html" in my templates folder which contains a navbar, when I tried to inherit this page to another page that renders a database or forms it's take me back to the "base.html" page. Here's my base page <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>base</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> </head> <body> <nav class="nav"> <a class="nav-link active" href="{% url 'index' %}">HOME</a> <a class="nav-link" href="{% url 'admin:index' %}">admin</a> <a class="nav-link" href="{% url 'my_app:database' %}">database</a> </nav> {% block content_block %} {% endblock %} </body> </html> so in the bar a database button where anchor inside this database page , this anchor tag navigate to my form <!DOCTYPE html> {% extends 'base.html' %} {% block content_block %} <div class='container'> <a href="{% url 'my_app:form' %}">Form</a> </div> {% endblock %} and here's my page where i want to render my form in it <!DOCTYPE html> {% extends 'base.html' %} {% block content_body %} <form method="POST"> {{form.as_p}} {% csrf_token %} <input type="submit" name='submit'> </form> {% endblock %} when I navigate to my form it's navigate to the home page however the link is how I expected http://127.0.0.1:8000/data/form/ but it … -
ObtainAuthToken in django
I am following a Django course and the teacher is simply importing ObtainAuthToken from rest_framework.authtoken.views. When i import that i get this exc: raise TypeError( TypeError: Abstract base class containing model fields not permitted for proxy model 'TokenProxy'. Tracing the exception got me to this line from rest_framework.authtoken.views import ObtainAuthToken I think it's not that complicated but if it needs clarification i will add my views and urls. Thanks in advance. -
migrate django model primary key UUID field to CharField
I need to change the id field size on an oracle database to support storing longer id's. By default using the UUIDField in django creates a table with varchar field of 32 bytes but we now need it to store ids generated by uuid.uui4 and of supplied id's of character lengths up to 80. What is the least hacky way to do this in django so that the migrations are consistent across environments while keeping foreign key relationships in other models? class CurrentModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class desiredModel(models.Model): id = models.CharField(max_length=80, primary_key=True, default=uuid.uuid4) -
Bootstrap data table not working on refreshing table using Ajax in Django project
I had success to refresh the table using Ajax. However, the bootstrap datatable can't apply to my refreshing table. If I not using this method to refresh the table. Bootstrap can work properly applied. I just want to refresh my table and paging table. I am beginner on coding please help. base.html ... <html> <head> <link rel="stylesheet" href="{% static 'plugins/datatables-bs4/css/dataTables.bootstrap4.min.css' %}"> <link rel="stylesheet" href="{% static 'plugins/datatables-responsive/css/responsive.bootstrap4.min.css' %}"> </head> ... <body> ... <script src="{% static 'plugins/datatables/jquery.dataTables.min.js' %}"></script> <script src="{% static 'plugins/datatables-bs4/js/dataTables.bootstrap4.min.js' %}"></script> <script src="{% static 'plugins/datatables-responsive/js/dataTables.responsive.min.js' %}"></script> <script src="{% static 'plugins/datatables-responsive/js/responsive.bootstrap4.min.js' %}"></script> <script> $(function () { $('#Table').DataTable({ "paging": true, "lengthChange": false, "searching": false, "ordering": false, "info": false, "autoWidth": false, "responsive": false, }); }); </script> </body> </html> table.html {% extends "base.html" %} {% block content %} {% load static %} <head> <title>table</title> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> function playSound() { var audio = new Audio("../../media/juntos.mp3"); audio.play(); } var cacheData; var data = $('#div_refresh').html(); var auto_refresh = setInterval( function () { $.ajax({ url:'refresh', type: 'GET', data: data, dataType: 'html', success: function(data) { if (data !== cacheData){ playSound(); cacheData = data; $('#div_refresh').fadeOut("slow").html(data).fadeIn("slow"); } } }) }, 2000); </script> </head> <body> <div id='div_refresh'> </div> </body> {% endblock content %} refresh_table.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> …