Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Firebase JWT to django credential login
it is possible to login a user from firebase jwt to django if so, what is the tools needed to login a user? Thanks -
Django REST Serializer not getting data from request
I have the following serializer setup to take in a postcode and return a list of service objects: class ServiceSearchSerializer(Serializer): area = CharField(max_length=16) services = DictField(child=JSONField(), read_only=True) def validate_area(self, value): if re.match('^[A-Z]{1,2}[0-9][A-Z0-9]? ?([0-9][A-Z]{2})?$', value) is None: raise ValidationError("This is not a valid postcode.") And I tried to use this to create an API endpoint which out take in the area. class ServiceSearchAPI(GenericAPIView): serializer_class = ServiceSearchSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): area = serializer.data['area'] return Response(area) However, when trying to get the area from the serializer, it returns None. But the value for request.data['area'] is correct. Does anyone know why this is happening? -
Prevent Django from localizing numbers in templates
I have a Django template and am using localization by loading the packages and applying translate like this: {% load i18n %} {% load l10n %} .... {% translate "Menu" %} At some point I have a visual element where I provide the CSS width as a float variable from the view. Now when I change the language from en-us to de (German), the dot in the float is replaced with a comma and the value is not valid CSS anymore. This is the element: <div class="progress-header progress-el" style="width: {{p.max_width}}%"></div> I am aware of this question: How to prevent Django from localizing IDs in templates? And I have tried enclosing the relevant element in these tags: {% localize off %} <div class="progress-header progress-el" style="width: {{p.max_width}}%"></div> {% endlocalize %} As well as applying filters: <div class="progress-header progress-el" style="width: {{p.max_width|unlocalize}}%"></div> And: <div class="progress-header progress-el" style="width: {{p.max_width|safe}}%"></div> No success so far - any suggestions? -
Django - when 1 user accesses the same view with different url kwargs - why am I getting cross over of data?
I have a django app that contains samples. On my home page, it displays a table with many samples, containing hyperlinks to the 'Sample page' - which is a view get request. When I click on several of these samples in tandem, to open new tabs, each to a specific tab - I am getting cross over of data - I.e the url sample_id kwargs is different, but the page is displaying the same results which is incorrect. When i refresh the page, the correct sample data appears. Is there any way around this happening is a user is to open several different sample tabs at the same time? This would impact on results and could cause errors in the workflow offered by the django app. *is this because my view is processing too much, so the different view request=s ends up over lapping ? -
How to convert function based views to class based views in Django RestFramework?
I am a beginner learning the Django RestFramework. I had created this for an blog post page for my project. I looked through different tutorials and posts but couldn't really figure out. Can you help me converting this functional view into a class view? Thanks from django.http.response import JsonResponse from django.shortcuts import render from django.http import JsonResponse from rest_framework import serializers from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import PostSerializer from .models import Post,categories # Create your views here. @api_view(['GET']) def apiOverview(request): api_urls={ 'List':'/article-list/', 'Detail View':'/article-detail/<str:pk>/', 'Create':'/article-create/', 'Update':'article-update/<str:pk>/', 'Delete':'/article-delete/<str:pk>/', } return Response(api_urls) @api_view(['GET']) def articleList(request): articles=Post.objects.all() serializers=PostSerializer(articles,many=True) return Response(serializers.data) @api_view(['GET']) def articleDetail(request,pk): articles=Post.objects.get(id=pk) serializers=PostSerializer(articles,many=False) return Response(serializers.data) @api_view(['POST']) def articleCreate(request): serializers=PostSerializer(data=request.data) if serializers.is_valid(): serializers.save() return Response(serializers.data) @api_view(['POST']) def articleUpdate(request,pk): articles=Post.objects.get(id=pk) serializers=PostSerializer(instance=articles,data=request.data) if serializers.is_valid(): serializers.save() return Response(serializers.data) @api_view(['DELETE']) def articleDelete(request, pk): articles=Post.objects.get(id=pk) articles.delete() return Response('The item has been deleted') -
Django Custom Template Filter - How To Mention Users And Categories
I am making a social networking site, and I want to be able to mention users or categories by using the # symbol. (Example: #User #Category #Other Category). Using a template filter, I want to first find all the # in the string, and then get the word after it. Then I would check in the models for categories: class Category(models.Model): name = models.CharField(max_length=250, unique=True) category_detail = models.TextField(max_length=1250, default='No information is known on this category.') created_date = models.DateTimeField(default=timezone.now) follow_count = models.IntegerField(default=0) followers = models.ManyToManyField(User, related_name='followers') And if it does not match a category I would check if the word after the # is a user. If It is a category, I want to link it using the <a> tag, and if it is a user I also want to link it using the <a> tag. The urls: urlpatterns = [ path('u/@<str:username>', UserPostListView.as_view(), name='user-posts'), # User Profile Link. Link This If After The # The Word Is A User path('c/<str:cats>/', views.category_view, name='category-detail'), # View Category Link. Link This If After The # The Word Is A Category ] Usage: Going back to the example, let's say I have a comment like this: This is such a great post! #some_user #category #other_category … -
Django Cassandra Engine with AWS Keyspace
I am trying to set a django app and connect it to aws keyspace. Trying to do it using django-cassandra-engine Can someone help me with entry for database in settings.py. -
How to add M2M data directly to form in Django
I have a form field which gets added through a Mixin. This field is not saved in the database. Instead, I need to take this field and convert it to a field in the form that will be saved in the database. The field in the database is named receiver: receiver = models.ManyToManyField(EmployeeType, related_name='policies_receiver') Instead of the user selecting the receivers, I would like them to use this new form field which has been added to the form via Mixin: class SelectEmployeeTypeFormMixin(forms.Form): """ Adds a "select_employee_type" radio field to a form. If checked, the appropriate employee types/roles will be applied to the object. """ CHOICES = ( ('this_department', 'Employees in my department.'), ('company_wide', 'All employees in this company.'), ) select_employee_type = forms.ChoiceField( widget=forms.RadioSelect(), choices=CHOICES, initial='this_department', label='Who is this for?' ) The select_employee_type form value needs to be converted to the receiver field in the view. I have done this by saving the form then updating the receiver in the form as such: updated_request = request.POST.copy() if policies_form.is_valid(): if request.user.role.supervisor is None or request.user is policies_form.sender: policies_form.save() if updated_request['select_employee_type'] == 'this_department': subs_id = request.user.subordinates.values_list('role', flat=True) sub_roles = EmployeeType.objects.filter(Q(pk__in=subs_id) | Q(pk=request.user.role.id)) policies_form.instance.receiver.set(sub_roles) policies_form.save() The problem I am having is that I use … -
Form is not being saved in Django admin page
I have faced a problem in my Django project where my form is not being saved as a new listing in my model(listing) and is not even showing on Django's admin page. my models.py : class listing(models.Model): title = models.CharField(max_length=64) describtion = models.CharField(max_length=300) bid = models.FloatField() category = models.ForeignKey(categories, default=1, verbose_name="Category", on_delete=models.SET_DEFAULT) user = models.ForeignKey(User,default='', verbose_name="User", on_delete=models.SET_DEFAULT) image = models.CharField(max_length=400) def __str__(self): return f"{self.title} " create a new listing form : class create(ModelForm): class Meta: model = listing fields = [ 'title', 'describtion','bid','category','image'] views.py : def CreateListing(request): user = request.user if request.method == "POST": form = create(request.POST, instance=user) if form.is_valid(): new_listing = form.save() new_listing.user = request.user new_listing.save() return render(request, "auctions/listing.html") else: return render(request, "auctions/Create.html",{ "form": create }) Ps: I have no problem with my urls.py -
docker-compose up --build states an error but it works after i use docker-compose up what is the problem which gives me the error
First i use docker-compose up --build and this is what i get: Building django_gunicorn Sending build context to Docker daemon 19.46kB Step 1/8 : FROM python:3.8.5-alpine ---> 0f03316d4a27 Step 2/8 : RUN pip install --upgrade pip ---> Using cache ---> ac5d6a64af93 Step 3/8 : COPY ./requirements.txt . ---> Using cache ---> 8dfb848be8a4 Step 4/8 : RUN pip install -r requirements.txt ---> Using cache ---> 0dee442b9c0a Step 5/8 : COPY ./ddc /app ---> 21c33e5463d8 Step 6/8 : WORKDIR /app ---> Running in 9153438d9466 Removing intermediate container 9153438d9466 ---> d27b60805a1b Step 7/8 : COPY ./entrypoint.sh / ---> e497fecdfb76 Step 8/8 : ENTRYPOINT ["sh", "/entrypoint.sh"] ---> Running in f6eb59759a71 Removing intermediate container f6eb59759a71 ---> 6db361baa8e8 Successfully built 6db361baa8e8 Successfully tagged django-docker-compose_django_gunicorn:latest Traceback (most recent call last): File "docker-compose", line 3, in <module> File "compose/cli/main.py", line 81, in main File "compose/cli/main.py", line 203, in perform_command File "compose/metrics/decorator.py", line 18, in wrapper File "compose/cli/main.py", line 1186, in up File "compose/cli/main.py", line 1182, in up File "compose/project.py", line 664, in up File "compose/service.py", line 348, in ensure_image_exists File "compose/service.py", line 1133, in build File "compose/service.py", line 1948, in build FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmp5cv0a52z' [22049] Failed to execute script docker-compose After that … -
how to make username unique only amongst active users
I want to make sure that the username field is unique, but only amongst active users. If an user is inactive, then their username can be used to create a new account. Is this possible in django? I am using MySQL by the way. I have read about a conditional unique constraint, but it only works on postgres. https://docs.djangoproject.com/en/3.2/ref/models/constraints/#condition -
I do not receive a message by mail when registering
I want to register by mail, I did everything according to this guide, only the setting.py is slightly different, I will show it below https://studygyaan.com/django/how-to-signup-user-and-send-confirmation-email-in-django The inspector does not show any red errors, for some reason the message does not come to the mail and registration takes place without confirmation of the mail setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' MAILER_EMAIL_BACKEND = EMAIL_BACKEND EMAIL_HOST = 'smtp.mail.com' EMAIL_HOST_PASSWORD = 'mypassfromemail' EMAIL_HOST_USER = 'myemail@mail.ru' EMAIL_PORT = 465 EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER models.py import kwargs as kwargs from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from datetime import datetime, date from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class Post(models.Model): published = None title = models.CharField(max_length=200) author = models.ForeignKey('auth.User', on_delete=models.CASCADE,) body = models.TextField() header_image = models.ImageField(blank=True, null=True, upload_to="images/") post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default='coding') def __str__(self): return self.title + '|' + str(self.author) def get_absolute_url(self): #return reverse('post_detail', args=[str(self.id)]) return reverse('home') class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): … -
Django login not changing URL
need help. I am using simple Django URL to log in user and send to a required page, but as user sign in URL does not change. Views.py from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return render(request, 'required.html') The URL does not change it remains http://127.0.0.1:8000/myApp/login/ Please suggest how to change the URL. -
Is the model definition correct in django
I have defined below models in my models.py file. I am trying to populate Allocation table only for the rows where member is null. from django.db import models from django.contrib.auth.models import User # Create your models here. class Member(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) DESIGNATION = [ ('Developer', 'Developer'), ('Tester', 'Tester'), ('Support', 'Support'), ] name = models.CharField(max_length=200, null=True) role = models.CharField(max_length=100, null=True, choices=DESIGNATION) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Task(models.Model): CATEGORY = [ ( 'Low', 'Low'), ('Medium', 'Medium'), ('Urgent', 'Urgent'), ] STATUS = [ ('Not Started', 'Not Started'), ('In Progress', 'In Progress'), ('Completed', 'Completed'), ] name = models.CharField(max_length=200, null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY) description = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) member = models.ForeignKey('Member', null=True, on_delete=models.CASCADE) task_status = models.CharField(max_length=200, null=True, choices=STATUS) def __str__(self): return self.name class Allocation(models.Model): member = models.ForeignKey('Member', null=True, on_delete=models.CASCADE) task = models.OneToOneField('Task', null=True, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.task.name And here is my view for task allocation def allocate_task(request, pk): task_details = Task.objects.get(id=pk) form = TaskAllocateForm(instance=task_details) if request.method == 'POST': form = TaskAllocateForm(request.POST, instance=task_details) if form.is_valid(): form.save() return redirect('/') I am creating new tasks with create method which is working fine. And I am trying to … -
How to convert nepali date to english date in drf [closed]
I am getting a problem in converting the Nepali date which I get from the user as input data to English date as output. Here in this code user pass month as user data and I got the Nepali date as output. But I expect to get output as an English date.This is View and the code is here: This is the view code: import datetime import pandas as pd from django.http import JsonResponse from nepali_datetime import REFERENCE_DATE_AD from api.utils.helpers import get_active_session import csv import nepali_datetime def get_first_last_date_month(request): """ function to receive the nepali month and return first and last date of that month """ month = request.GET.get("month") year = nepali_datetime.date.today().year with open("project/month_days.csv") as csvfile: reader = csv.DictReader(csvfile) if month: nep_year = nepali_datetime.date(year, int(month), 1) print(nep_year) no_of_days = [ row.get(str(nep_year.strftime("%B"))) for row in reader if row["Year"] == str(nep_year.year) ] print(no_of_days) if int(no_of_days[0]) > 0: nep_dates = [ str(nepali_datetime.date(nep_year.year, nep_year.month, i)) for i in range(1, int(no_of_days[0]) + 1) ] print(nep_dates) english_dates = str(nep_dates.to_english_date()) print(english_dates) return JsonResponse({"dates": english_dates}) This is the expected output: "dates": [ "2021-01-01", "2021-01-02", "2021-01-03", "2021-01-04", "2021-01-05", "2021-01-06", ] But I got this: "dates": [ "2078-01-01", "2078-01-02", "2078-01-03", "2078-01-04", "2078-01-05", "2078-01-06", "2078-01-07", "2078-01-08", "2078-01-09", "2078-01-10", "2078-01-11", "2078-01-12", "2078-01-13", "2078-01-14", … -
How to create Django project using windows os
I have tried using ...> django-admin startproject mysite but it showed '...' is not recognized as an internal or external command, operable program or batch file. what should I do -
how to display value as radio button using widget_tweaks
I facing a problem in displaying the stored “gender” value as a radio button in a template. I am using widget_tweaks, and this template will allow user to update and save data. To illustrate this problem I have the following: Model: class Student(models.Model): fname = models.CharField(max_length=50) lname = models.CharField(max_length= 50) gender = models.CharField(max_length= 1) # in the database it is either M or F def __str__(self): return '{} {} '.format( self.fname, self.lname) Form: class studentForm(forms.ModelForm): class Meta: model = Student fields = ( 'fname', 'lname', 'gender', ) labels = { 'fname': ('First name'), 'lname':( 'Last name'), 'gender': ( 'Gender'), } def __init__(self, *args, **kwargs): super(studentForm, self).__init__(*args, **kwargs) View: def studentDetails(request,id): oneStudent = get_object_or_404(Student,id=id) oneStudentForm = studentForm( instance= oneStudent) context = { "form":oneStudentForm } return render(request,"students/studentDetails.html",context) and I tried to show Gender in the HTML as the following, but the problem is that condition always False!!: <form method="POST" > {% csrf_token %} <div class="row"> <div class="form-group col-md-3"> <label for="{{ field.id_for_label }}" >{{ form.fname.label }}</label> {% render_field form.fname %} </div> <div class="form-group col-md-3"> <label for="{{ field.id_for_label }}">{{ form.lname.label }}</label> {% render_field form.lname class="form-control req" %} </div> </div> <div class=" col-md-3 mt-3" > {{form.gender}} <!-- this for debugging, to ensure the the value … -
Como verifico o valor de uma variável que uma função das views retorna DJANGO
Estou a criar uma web application com o django, que contem um pequeno formulário com 3 campos e quando o usuário os preenche é gerado um ficheiro excel, este ficheiro está associado a um botão de download que só fica ativo quando o ficheiro foi gerado. Neste momento eu tenho o ficheiro e o botão deveria estar ativo mas eu penso que o problema é que não estou a conseguir passar a informação para o html de forma correta. urls.py app_name = 'form' urlpatterns = [ path('', views.index, name='index'), path('find_csv/', views.valid_csv_exist, name='valid_csv_exist'), path('download/', views.download_csv, name='download_csv'), path('', execute.execute, name='execute'), ] função da qual necessito da variável no html def valid_csv_exist(): # Define o caminho onde procurar o ficheiro path_files = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + f'/form/Exports/{client}/{execute.date_folder}' # Array with names of files files = [f for f in listdir(path_files) if isfile(join(path_files, f))] if 'tasksinfo.csv' in files: csv_file = True else: csv_file = False return csv_file parte do ficheiro html onde quero usar o valor retornado pela função {% if csv_file is True %} <a href="{% url 'form:download_csv' %}" download><button class="btn"> <i class="fa fa-download"></i>Download CSV File</button> </a> {% else %} <a href="/form" download><button class="btn" disabled> <i class="fa fa-download"></i>Download CSV File</button> </a> {% endif %} O … -
Django cannot find the settings.py file
I forgot the password to my admin page. I found a solution but in order to change it I had to include DJANGO_SETTINGS_MODULE to system path and pointed it to settings.py file in my folder, I did so. Since then I'm getting this error ModuleNotFoundError: No module named 'C:\\Users\\manda\\PycharmProjects\\firstsite\\firstsite\\settings' I revert back all my changes I made in files and removed 'DJANGO_SETTINGS_MODULE' from environment variable but nothing happened. -
How to make a permission that just allow users to modify only their own data in DRF
I'm trying to create a custom permission that prevents user to modify others user data.So far I'd tried this but is not working. the idea is to compare user id taken from the token against the user id fk designated to the object. costume permission class SameUserTransactionPermission(BasePermission): message = 'hey usuario no autorizado' def has_object_permission(self, request, view, obj): if obj.user_id_id != request.user.id or request.user_id_id != request.user.id: return False return True Model class Transactions(models.Model): TRANSACTION_TYPE = [(1, "Ingresos"), (2, "Egresos")] type = models.IntegerField( choices=TRANSACTION_TYPE, verbose_name="Tipo", blank=False, null=False) user_id = models.ForeignKey( 'expenseApi.Users', verbose_name="Usuario", blank=False, null=False, on_delete=models.PROTECT) description = models.CharField( verbose_name="Concepto", blank=False, null=False, max_length=50) date = models.DateTimeField( verbose_name="Fecha", editable=False, auto_now_add=True) amount = models.FloatField(verbose_name="Monto", blank=False, null=False, validators=[MinValueValidator(MIN_AMOUNT)]) class Meta: ordering = ['-date'] def __str__(self): return '{}'.format(self.pk) I want it to affect all hhtp methods. -
(Angular + Django REST) Suppress Browser Auth Dialog?
I use JWT Authentication for my Angular + Django REST project. Recently the browser keeps showing the Basic auth dialog whenever the token expires. I know by removing/changing the WWW-Authenticate header can suppress the dialog but I could not get it to work. On Django, I have tried to use a custom Response object to force the response header: def BaseResponse(data, status=None, template_name=None, headers=None, content_type=None): response = Response(data, status, template_name, {'WWW-Authenticate': 'xBasic'}, content_type=None) response['WWW-Authenticate'] = 'xBasic' return response Also I have tried to use a middleware: AuthHeaderMiddleware.py class AuthHeaderMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_response(self, request, response): if response.status == 401: r = Response(response.data, response.status, response.template_name, {'WWW-Authenticate': 'xBasic'}, response.content_type) return response Middleware settings in settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'middleware.AuthHeaderMiddleware', ] The problem is the WWW-Authenticate header remains Basic for all 401 responses (but 'xBasic' for other statuses). I use the djangorestframework-simplejwt package in Django. On Angular, I have tried to force a blank token with the Bearer declaration for the Authorization header: add_header(request, token=null) { var r = request.clone({ setHeaders: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${request.withCredentials ? token : ''}` } }); return r; } … -
Count & Sum of Order Values for each customer (through iteration) in Django
I have Customer & Order models as below: class Customer(models.Model): name = models.CharField(max_length = 100) city = models.CharField(max_length = 100) class Order(models.Model): value = models.FloatField() customer = models.ForeignKey(Customer, on_delete=models.CASCADE) Now I would like to generate a table of (distinct) customers along with a count of number of orders placed by each of them and the sum of values of those orders. I tried this in the views.py: def customers(request): customer_orders = Order.objects.distinct().annotate(Sum('value')) Then in my html template, I tried the following: <ul> {% for customer in customer_orders %} <li>{{customer.customer}} - {{customer.value__sum}}<li> {% endfor %} </ul> After all this, instead of getting unique customers (and respective order records), I'm getting a list of all orders and customers are getting repeated (as shown below). Not sure what I'm missing here. Bosco-Ward - 16,700.0 Ernser PLC - 51,200.0 Murphy Ltd - 21,400.0 Kohler-Veum - 29,200.0 Schmidt-Legros - 96,800.0 Brown-Weissnat - 8,200.0 Bosco-Ward - 36,400.0 Ernser PLC - 66,600.0 Murphy Ltd - 84,200.0 Also wanted to know if there's a possibility to generate a table of city names with order count and total value of orders received from that city (note that my order model doesn't have city field). -
Cannot store image as binary in mysql django and also check the size of the image in forms.py
I am creating a website in django. I need to store the image as binary in mysql database as well as check its size before saving. Tried many ways nothing seems to help. views.py def client_create_view(request): base_form = ClientForm(None, initial=initial_data) context={ "form": base_form } if request.method == 'POST': form = ClientForm(request.POST,request.FILES) if form.is_valid(): form.save() return render(request,'cc.html',context) forms.py class ClientForm(ModelForm): def clean(self): super(ClientForm, self).clean() photo_image = self.cleaned_data['photo'].file.read() if photo_image.file_size > 0.250: raise ValidationError(['Image Size should be lower than 250kb']) html <form method="post" enctype='multipart/form-data'> #some data </form> -
How to filter data in the backend for displaying geotags via GeoJSONLayerView to the Map
I need to display weather stations only in the areas(filter by id_ugms) of the country that the user chooses. But the geodjango tools do not allow you to filter the data in the backend. GeoJSONLayerView extracts all the data from the table, and I have to filter the entire list in leaflet on the frontend. There are a lot of records in the table, which is why the response time is very long(it takes more than 5 minutes to display and filter), or it crashes from the server altogether. How do I do backend filtering? Maybe there's another way? I tried just to make a selection, and serialize the data via geojsonserializer - nothing worked, leaflet does not give an error of input data. Technology stack: Postgis, Django, Leaflet. There is a model of my entity: models.py class WeatherStation(gismodels.Model): id_station = models.IntegerField(primary_key=True) station_index = models.IntegerField(default = None) name_station_rus = models.CharField(default="", max_length=256) name_station_en = models.CharField(default="", max_length=256) id_ugms = models.ForeignKey(Ugms, on_delete=models.CASCADE, default = None) id_country = models.ForeignKey(Country, on_delete=models.CASCADE, default = None) id_subrf = models.ForeignKey(Subrf, on_delete=models.CASCADE, default = None) latitude = models.CharField(default ="", max_length=256) longitude = models.CharField(default ="", max_length=256) geom = gismodels.PointField(default ='POINT EMPTY',srid = 4326) objects = gismodels.Manager() height_above_sea = models.CharField(default="", max_length=256) … -
Open a file from a network drive django in a new tab
I'm trying to have a table that opens an invoice in a new tab but I'm not getting on how to use the url format to have the mapping done to a shared network folder. I'm trying by doing the following in the table definition <tbody> {% for datarow in dataset %} <tr> <td>{{datarow.supplierName}}</td> <td>{{datarow.invoiceNumber}}</td> <td>{{datarow.reference}}</td> <td><a href = "open(r'\\REMOTESERVER\Shared1\FOLDER\FOLDER Images\{{datarow.docId|urlize}}\file.tiff')">Open Invoice</a> {% endfor %} </tr> </tbody> however it doesn't open as the url still tries to map from localhost. Also in each folder I have one .tiff file but other files as well, I'm also looking into having a way to open that .tiff file (different name per folder) to be used in the url but I haven't got there yet.