Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
way to implement Django case insensitive for login without using get_by_natural_key?
Need to make user login case insensitive without overiding the function get_by_natural_key, any way to achieve that with __iexact? Overiding any internal functions cant be done ,also note that we users are added from django admin so I just want to make the use login case insensitive -
"nie mo" after python3 manage.py startserver
I'm trying to start local server by using python django, and pycharm returns "nie mo" after python3 manage.py runserver command. Any idea what's the problem? -
Getting 'ModelBase' object is not iterable
I'm creating the following view to get the list of fruits and I got this type error message. I don't know what I missed here: TypeError: 'ModelBase' object is not iterable views.py class FruitsList(APIView): # To list fruits def get(self, request): fruits = Fruit.objects.all() serializer = FruitSerializer(Fruit, many = True) return Response(serializer.data) serializers.py: class FruitSerializer(serializers.ModelSerializer): class Meta: model = Fruit fields = [ 'id', 'name', 'customers', ] models.py: class Fruit(models.Model): """represents customer fruits""" name = models.CharField(max_length = 100) customers = models.ManyToManyField(Customer) def __str__(self): return self.name Your help is much appreciated! -
convert dropdown to text box when other option is selected
I have a dropdown which displays choices right now it works as just dropdown but when i select the option Other which is a choice when selected it should become textbox. models.py class MyModel(models.Model): task_name = models.CharField(blank=true, choices=somechoiceClass, default='') <div class="col-md-4"> <div class="form-group label-static" :class="{'has-error': errors.task_name && errors.task_name.length > 0}"> <label class="typo__label control-label">Task Name&nbsp;<span class="req">*</span></label> <multiselect v-model="form.task_name" :options="taskNameChoices" :multiple="false" :close-on-select="true" :clear-on-select="true" :preserve-search="true" placeholder="Select" label="text" track-by="id" :hide-selected="false" :show-labels="false"> </multiselect> <span class="help-block" v-show="errors.task_name" v-text="errors.task_name && errors.task_name[0]" v-cloak></span> </div> </div> <script> taskNameChoices: instanceData.case && instanceData.case.task_names || [], this.taskNameChoices = selectedOption.task_names; </script> -
''QuerySet' object has no attribute 'enter_the_destination_account_number'
Can anyone tell me what's wrong with my code? I am trying to use filter but its showing ''QuerySet' object has no attribute 'enter_the_destination_account_number'. I tried get() but it shows, get() returned more than one MoneyTransfer -- it returned 14!. here's some snap of code. Thanks in advance models.py class Status (models.Model): user_name = models.CharField(max_length=150, default=None) account_number = models.IntegerField() balance = models.IntegerField() phone_number= models.CharField(max_length=20, default=0) class MoneyTransfer(models.Model): enter_your_user_name = models.CharField(max_length = 150, default = None) enter_the_destination_account_number = models.IntegerField() enter_the_destination_phone_number=models.CharField(max_length=20, default=None) enter_the_amount_to_be_transferred_in_INR = models.IntegerField() views.py def TransferMoney(request): if request.method == "POST": form = forms.MoneyTransferForm(request.POST) if form.is_valid(): form.save() curr_user = models.MoneyTransfer.objects.filter(enter_your_user_name=request.user) dest_user_acc_num = curr_user.enter_the_destination_account_number #dest_phone number add korte hobe dest_phone_num= curr_user.enter_the_destination_phone_number temp = curr_user # NOTE: Delete this instance once money transfer is done dest_user = models.Status.objects.get(account_number=dest_user_acc_num) # FIELD 1 dest_phn= models.Status.objects.get(phone_number= dest_phone_num) transfer_amount = curr_user.enter_the_amount_to_be_transferred_in_INR # FIELD 2 curr_user = models.Status.objects.get(user_name=request.user) # FIELD 3 # Now transfer the money! curr_user.balance = curr_user.balance - transfer_amount #dest_phn.balance = dest_phn.balance + transfer_amount dest_user.balance = dest_user.balance + transfer_amount # Save the changes before redirecting curr_user.save() dest_user.save() temp.delete() # NOTE: Now deleting the instance for future money transactions return redirect(index) else: form = forms.MoneyTransferForm() return render(request, "epayapp/Transfer_money.html", {"form": form}) -
How to print query of Django ORM
I am using Django ORM query with Extra params. when I try to print the SQL query relevant to that ORM Query,i am getting the below Error message. ORM Query: Record = SAMPLE_TABLE.objects.extra(where=["REPLACE(Message,' ','') "+whereCaseSensitive+" like %s "+query],params=[duplicateCheckMessage]).filter(~Q(iStatus=2),~Q(iAppStatus=2),iEntityID=entityId,iTemplateType=1).first() Message - FieldName , whereCaseSensitive - '', query - ( FIND_IN_SET("test",Testfield)) I am trying to fetch the sql query related to this using print(Record.query) when i run this i am getting Exception as 'NoneType' object has no attribute 'query' Can any one help on this ? -
I am learning Django very hardly [closed]
I am stuck in Django Templates views (parameter) request: Any "request" is not accessedPylance No quick fixes available -
Using d Django Abstract Base User model to enable Profile tab
Using Django Abstract Base User model, How do I make the Profile tab show when a user is logged in. Should I create a model/form for Profile, This is the image of the html file. The backend for signup and login works perfectly fine but when a user signs up or logs in, the nav bar doesn't change at all. Please help {% extends 'base.html' %} {% block title %}Profile{% endblock %} {% block content %} <h1>Hello World</h1> {% if user.is_authenticated %} <a href="{% url 'profile' %}" type="button" class="btn btn-primary">Profile</a> <a href="{% url 'logout' %}" type="button" class="btn btn-primary">Logout</a> {% else %} <a href="{% url 'signup' %}" type="button" class="btn btn-primary">Sign Up</a> <a href="{% url 'login' %}" type="button" class="btn btn-primary">Log In</a> {% endif %} {% endblock %} -
Redirection from the link itself
I have auto logged-in URL for external service but it's one link open on the home page but I want to redirect the user to another page. Is there any way to open the logged-in link at first to save the credentials and then redirect the user to the desired page? -
Getting error on installing a python package regarding mysqlclient
I am currently working on a new project. Trying to install the requirements using pip but getting this error. Using python version 3.6.9 This is the error message I am getting. Collecting en-core-web-sm@ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.4.0/en_core_web_sm-3.4.0-py3-none-any.whl Downloading https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.4.0/en_core_web_sm-3.4.0-py3-none-any.whl (12.8 MB) |████████████████████████████████| 12.8 MB 5.9 MB/s ERROR: mysqlclient-1.4.6-cp36-cp36m-win_amd64.whl is not a supported wheel on this platform. Any help would be highly appreciated and thank you in advance to anyone who looks into this. -
Point is not stored in database
I have a location based geodjango project. I got latitude and longitude from user and tried creating a point latitude = float(request.POST.get('latitude')) longitude = float(request.POST.get('longitude')) form.point = Point((latitude, longitude)) but data is not stored into the database, what is the real issue? -
django.core.exceptions.SynchronousOnlyOperation
Upgraded python from 3.6 to 3.8. Getting this error when I tried to connect to Django Admin. Is this because of version change? django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 410, in login return LoginView.as_view(**defaults)(request) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/contrib/auth/views.py", line 63, in dispatch return super().dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/edit.py", line 141, in post if form.is_valid(): File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 177, in is_valid return self.is_bound and not self.errors File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line 172, in errors self.full_clean() File "/usr/local/lib/python3.8/site-packages/django/forms/forms.py", line … -
pip install PyDictionary : python setup.py egg_info did not run successfully. │ exit code: 1 [27 lines of output]
PS D:\projects\english-dictionary-with-django> pip install PyDictionary Collecting PyDictionary Using cached PyDictionary-2.0.1-py3-none-any.whl (6.1 kB) Requirement already satisfied: bs4 in c:\users\benard.byakatonda\appdata\local\programs\python\python310\lib\site-packages (from PyDictionary) (0.0.1) Requirement already satisfied: requests in c:\users\benard.byakatonda\appdata\local\programs\python\python310\lib\site-packages (from PyDictionary) (2.28.0) Collecting goslate Using cached goslate-1.5.4.tar.gz (14 kB) Preparing metadata (setup.py) ... done Collecting click Using cached click-8.1.3-py3-none-any.whl (96 kB) Requirement already satisfied: beautifulsoup4 in c:\users\benard.byakatonda\appdata\local\programs\python\python310\lib\site-packages (from bs4->PyDictionary) (4.11.1) Requirement already satisfied: colorama in c:\users\benard.byakatonda\appdata\local\programs\python\python310\lib\site-packages (from click->PyDictionary) (0.4.5) Collecting futures Using cached futures-3.0.5.tar.gz (25 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [27 lines of output] Traceback (most recent call last): File "", line 2, in File "", line 14, in File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools_init_.py", line 189, in monkey.patch_all() File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\monkey.py", line 99, in patch_all patch_for_msvc_specialized_compiler() File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\monkey.py", line 169, in patch_for_msvc_specialized_compiler patch_func(*msvc14('get_vc_env')) File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\monkey.py", line 149, in patch_params mod = import_module(mod_name) File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\importlib_init.py", line 126, in import_module return bootstrap.gcd_import(name[level:], package, level) File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools_distutils_msvccompiler.py", line 20, in import unittest.mock File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\unittest\mock.py", line 26, in import asyncio File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\asyncio_init.py", line 8, in from .base_events import * File "C:\Users\benard.byakatonda\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 18, in import concurrent.futures File "C:\Users\benard.byakatonda\AppData\Local\Temp\pip-install-zhu28thw\futures_997bcda2ca314b4a8559d52198da1259\concurrent\futures_init.py", line 8, in from concurrent.futures._base import (FIRST_COMPLETED, File "C:\Users\benard.byakatonda\AppData\Local\Temp\pip-install-zhu28thw\futures_997bcda2ca314b4a8559d52198da1259\concurrent\futures_base.py", line 357 raise type(self._exception), self._exception, self._traceback ^ … -
Django Loop Through Objects After Bulk .update()
This code runs on cron. So I want to update the status of the objects immediately so that these objects don't get picked up again if a second cron starts before the current one finishes (which will eventually start to happen with my app.) # Grab all pending emails. emails = delivery_que.objects.filter(status='PENDING') emails.update(status='SENDING') # Loop through the pending emails. for email in emails: The current code doesn't work, as I seem to no longer have access to the objects after I .update() them. This is the workaround I implemented: # Grab all pending emails. emails = delivery_que.objects.filter(status='PENDING') emails.update(status='SENDING') emails = delivery_que.objects.filter(status='SENDING') # Loop through the pending emails. for email in emails: Is there another better solution I'm missing? I'd prefer not to query the database again to reselect the objects that I should already have access to from the first query. -
Django - filtering related objects
I have a puzzle. These are my models: class StatusGroup(models.Model): name = models.TextField() def __str__(self): return self.name class StatusDetail(models.Model): action = models.CharField(choices=[("CORRECT", "CORRECT"), ("INCORRECT", "INCORRECT")], max_length=64) status_group = models.ForeignKey(to=StatusGroup, on_delete=models.CASCADE, related_name="status_details") def __str__(self): return f"Detail: {self.action}" serializers: class StatusDetailSerializer(serializers.ModelSerializer): class Meta: model= models.StatusDetail fields = "__all__" class StatusGroupSerializer(serializers.ModelSerializer): status_details = StatusDetailSerializer(many=True) class Meta: model = models.StatusGroup fields = [ "pk", "status_details", "name" ] And a view: class Status(viewsets.ModelViewSet): queryset = models.StatusGroup.objects.all() serializer_class = serializers.StatusGroupSerializer authentication_classes = [] permission_classes = [permissions.AllowAny] filter_backends = (DjangoFilterBackend,) filterset_fields = ['status_details__action'] When I hit localhost:8000/api/status?status_details__action=INCORRECT I get: [ { "pk": 2, "status_details": [ { "id": 3, "action": "CORRECT", "status_group": 2 }, { "id": 4, "action": "INCORRECT", "status_group": 2 } ], "name": "Mixed" } ] Whereas I would like to have: [ { "pk": 2, "status_details": [ { "id": 4, "action": "INCORRECT", "status_group": 2 } ], "name": "Mixed" } ] How do I force Django to filter the related objects? I can get the result I want in SQL console, but Django adds, all the related objects that belong to the StatusGroup. I have a misconception, but I don't know what that is. -
How to implement Django case insensitive for login without overriding the function get_by_natural_key
I want to make user login case insensitive without overiding the function get_by_natural_key , is there is any way to achieve that with __iexact ? I dont want to overide any internal functions,also note that we add users from django admin so i just want to make the use login case insensitive -
search functionality in Django ORM
if there is two type of data in table :'ABC-DE' and 'ABCDE' if someone search with space and underscore or hyphen so how to search for it without the regular expression -
Deploying Django application using openlitespeed and Gunicorn
Can I deploy a django application using gunicorn and openlitespeed ? Gunicorn can be used with LiteSpeed as mentioned here. But I am not getting any resource for openlitespeed. -
Image is not showing in DRF
I get the serializer data properly but when I click the url of the image it shows error even that image stores properly to the directory. I am not getting what is the issue here. Please suggest me what should I do to show the image. models.py: class TutorProfile(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) travelling_distance = models.CharField(_("Traveling Distance"),max_length=255,null=True,blank=True) where_tutoring = models.CharField(_("Where Tutoring"),max_length=255,null=True,blank=True) taken_out_to_store_account = models.BooleanField(_("Taken To Store Credit Card"),default=False) account_number = models.PositiveIntegerField(_("Account Number"),default=0) routing_number = models.PositiveIntegerField(_("Routing Number"),default=0) upload = models.FileField(null=True, blank=True,upload_to="uploads/%Y/%m/%d", validators=[FileExtensionValidator( ['pdf','jpg','jpeg','pjp','pjpeg','jfif','png','webp'] ) ]) university = models.CharField(_("University"),max_length=255,null=True,blank=True) years_of_experience = models.CharField(_("Years Of Experience"),max_length=255,null=True,blank=True) professional_photo = models.ImageField(upload_to = user_directory_path) bio_teacher = models.TextField() tutor_profile_completed = models.BooleanField(default=False) tutoring_subject = models.ForeignKey( TutoringSubject, on_delete=models.CASCADE,blank=True, null=True) tutor_availablility = models.ManyToManyField( Day) booking_date = models.CharField(_("Booking Date"),max_length=255,null=True,blank=True) def save(self, *args, **kwargs): self.user_type = 'Teacher' # if self.brief_description_of_child is not Null if self.bio_teacher: self.tutor_profile_completed = True super(TutorProfile, self).save(*args, **kwargs) def __str__(self): return self.travelling_distance serializers.py class TutorProfileSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault(),source = 'user.username') image_url = serializers.SerializerMethodField('get_image_url') class Meta: model = TutorProfile fields = '__all__' def get_image_url(self, obj): request = self.context.get("request") return request.build_absolute_uri(obj.professional_photo.url) viewsets.py @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) class TutorprofileViewSet(ModelViewSet): serializer_class = TutorProfileSerializer http_method_names = ["post","delete","get"] queryset = TutorProfile.objects.all() def perform_create(self, serializer): serializer.save(user=self.request.user) def get_queryset(self): """ This view should return a list of all … -
How to map URLs to views in django?
Goal: 127.0.0.1:8000/about Should give: welcome to to about us page 127.0.0.1:8000/contact Should give: welcome to contact page Problem: Both are giving "page not found at /" This error: https://imgur.com/a/P0uWhWl This is my folder structure: https://imgur.com/a/84uc5Pw This is my main project "taskmate"'s urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('task/',include('todolist_app.urls')), path('todolist/',include('todolist_app.urls')), ] And for todolist_app, these are my details: Urls.py: from django.urls import path from todolist_app import views #from . import views urlpatterns = [ path('', views.todolist), path('contact', views.contact,name='contact'), path('about', views.about, name="about"), #the path can be anything. ] Views.py: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def todolist(request): context={'welcome_text':"welcome to todo list app"} return render(request, 'html/todolist.html',context) def contact(request): context={'welcome_text':"welcome to contact page"} return render(request, 'html/contact.html',context) def about(request): context={'welcome_text':"welcome to to about us page"} return render(request, 'html/about.html',context) I'm suspecting that the problem is in my main project urls.py as I've not included any details about contact and about URLs there. So, I did this there. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('task/',include('todolist_app.urls')), path('todolist/',include('todolist_app.urls')), path('about/',include('todolist_app.urls')), ] The website runs but the goal isn't achieved. Which is obvious because about/ is getting … -
How do i successfully push my app to heroku using git without getting the 'src refspec does not exist' error?
Wanted to deploy my app on heroku using Git but whenever I try running the command "git push heroku main", I get the following error; error: src refspec main does not match any error: failed to push some refs to 'https://git.heroku.com/edgarcollections.git' -
Django ORM multiple chained JOIN equivalent and aggregation
Given the following Django models (lots shown just as an example, could be more or less nested): class ModelA(models.Model): value = models.IntegerField() class ModelB(models.Model): modelA = models.ForeignKey(ModelA, on_delete=models.CASCADE) value = models.IntegerField() class ModelC(models.Model): modelB = models.ForeignKey(ModelB, on_delete=models.CASCADE) value = models.IntegerField() class ModelD(models.Model): modelC = models.ForeignKey(ModelC, on_delete=models.CASCADE) value = models.IntegerField() class ModelE(models.Model): modelD = models.ForeignKey(ModelD, on_delete=models.CASCADE) value = models.IntegerField() # etc... How can we use the Django ORM to do the following operations: e.g. all ModelE for a given modelA, SQL equivalent: SELECT ModelE.* FROM ModelA JOIN ModelB ON ModelB.modelA = ModelA.id JOIN ModelC ON ModelC.modelB = ModelB.id JOIN ModelD ON ModelD.modelC = ModelC.id JOIN ModelE ON ModelE.modelD = ModelD.id WHERE ModelA.id = 1 e.g. group all records by some model, SQL equivalent: SELECT ModelC.*, SUM(ModelE.value) FROM ModelA JOIN ModelB ON ModelB.modelA = ModelA.id JOIN ModelC ON ModelC.modelB = ModelB.id JOIN ModelD ON ModelD.modelC = ModelC.id JOIN ModelE ON ModelE.modelD = ModelD.id WHERE ModelA.id = 1 GROUP BY ModelC.id The specific query I'm trying to get is equivalent to the following: SELECT ModelC.value * SUM(ModelE.value) FROM ModelA JOIN ModelB ON ModelB.modelA = ModelA.id JOIN ModelC ON ModelC.modelB = ModelB.id JOIN ModelD ON ModelD.modelC = ModelC.id WHERE ModelA.id = 1 AND ModelD.value … -
How to make django form.errors display only error and not input field affected
Basically, what i am trying to achieve is to remove the name of the input field which in this case is tel and display only the error message using {{ form.errors }} -
AJAX request returns HTML file instead of data. ( Django & Python )
I have a profile page with user posts. People can like/dislike the posts. It works well but it reloads the page, that is why I am implementing AJAX. The route goes like this. Inside the profile view is the "like POST" request ending with a data = { 'likes':post.likes.all().count() } return JsonResponse(data,safe=False)" When clicking on the like button, I can see the data on a blank page if I want to. So I know it is receiving it. Unfortunately, when using AJAX, instead of returning the data. it returns the profile view's return render(request, "profile.html", context) Here is my AJAX code const post_id = $(this).attr('id') const likeText = $( `.like_button${post_id} `).attr('name') const trim = $.trim(likeText) const url = $(this).attr('action') let res; const likes = $(`.like_count${post_id}`).text() || 0 const trimCount = parseInt(likes) $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(), 'post_id':post_id, }, success: function(data){ console.log('success', data) }, error: function(data){ console.log('error', data) } }) Any help would be much appreciated. First time using AJAX, so as much details would be appreciated. -
Django Filtering between dates
I am creating a filter in heatmap where the filter will only extract the date from and to date transaction only. I am not sure with the codes on the filter date but I have not received an error, It only goes top of the page. My HTML for date is MM/DD/YYYY. I am not sure if it helps. But how can I embed filter between dates? Thank you Views def index_map(request): if request.method == "POST": fromdate = request.POST.get('fromdate') todate = request.POST.get('todate') df = pd.DataFrame(IncidentGeneral.objects.filter(user_report__date__date__range=(fromdate, todate)).values('user_report__latitude', 'user_report__longitude', 'accident_factor')) print(df) # coordenadas = list(IncidentGeneral.objects.values_list('user_report__latitude','user_report__longitude'))[-1] map1 = folium.Map(location=[14.676208, 121.043861], zoom_start=12, ) # df = df.dropna(axis=0, subset=['user_report__latitude', 'user_report__longitude', 'accident_factor', 'user_report__date']) # mapquestopen fg3=folium.FeatureGroup(name='Map with Markers', show=True) map1.add_child(fg3) # marker_cluster = MarkerCluster().add_to(fg) folium.TileLayer(('openstreetmap'), attr='openstreetmap').add_to(map1) # folium.TileLayer('mapquestopen', attr='mapquestopen').add_to(map1) # folium.TileLayer('MapQuest Open Aerial', attr='MapQuest Open Aerial').add_to(map1) folium.TileLayer('cartodbpositron', attr='cartodbpositron').add_to(map1) folium.TileLayer('cartodbdark_matter', attr='cartodbdark_matter').add_to(map1) plugins.Fullscreen(position='topright').add_to(map1) folium.LayerControl().add_to(map1) for id,row in df.iterrows(): folium.Marker(location=[row['user_report__latitude'],row['user_report__longitude']], icon=folium.Icon(icon="car", prefix='fa') ,popup=row['accident_factor']).add_to(fg3) # folium.Marker(coordenadas).add_to(map1) # df['user_report__date'] = df['user_report__date'].sort_values(ascending=True) # data = [] # for _, d in df.groupby('user_report__date'): # data.append([[row['user_report__latitude'], row['user_report__longitude'], row['accident_factor']] for _, row in d.iterrows()]) map1 = map1._repr_html_() context = { 'map1': map1 } return render(request, 'index1.html', context) Views class UserReport(models.Model): PENDING = 1 APPROVED = 2 REJECTED = 3 STATUS = ( (PENDING, 'Pending'), (APPROVED, …