Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Multi Combination Model Joins
Currently experiencing a problem where my models aren't joining on the foreign key properly, Doctors can only have one toolset, essentially I need to return [DoctorName, Category, Type, Subtype, Syringe, Bandage] ToolSetCategoryID, ToolSetTypeID, ToolSetSubTypeID all join on each other's respective tables and all join back to ToolSets an example of the models would be: class Doctor(models.Model): DoctorID = models.AutoField(db_column='DoctorID', primary_key=True) ToolSetID = models.ForeignKey("ToolSets", db_column='ToolSetID', on_delete=models.CASCADE) DoctorName = models.CharField(db_column='DoctorName', max_length=100) class Meta: managed = False db_table = 'tblDoctors' default_permissions = ['add','edit','delete'] class ToolSetCategories(models.Model): ToolSetCategoryID = models.AutoField(db_column='ToolSetCategoryID', primary_key=True) Category = models.CharField(db_column='Category', max_length=100) class Meta: managed = False db_table = 'tblToolSetCategories' default_permissions = ['add','edit','delete'] class ToolSetTypes(models.Model): ToolSetTypeID = models.AutoField(db_column='ToolSetTypeID', primary_key=True) ToolSetCategoryID = models.ForeignKey("ToolSetCategories",db_column='ToolSetCategoryID',on_delete=models.CASCADE) Type = models.CharField(db_column='Type', max_length=100) class Meta: managed = False db_table = 'tblToolSetTypes' default_permissions = ['add','edit','delete'] class ToolSetSubTypes(models.Model): ToolSetSubTypeID = models.AutoField(db_column='ToolSetSubTypeID', primary_key=True) ToolSetTypeID = models.ForeignKey("ToolSetTypes",db_column='ToolSetTypeID',on_delete=models.CASCADE) ToolSetCategoryID = models.ForeignKey("ToolSetCategories",db_column='ToolSetCategoryID',on_delete=models.CASCADE) SubType = models.CharField(db_column='SubType', max_length=100) class Meta: managed = False db_table = 'tblToolSetSubTypes' default_permissions = ['add','edit','delete'] class ToolSets(models.Model): ToolSetID = models.AutoField(db_column='ToolSetID', primary_key=True) ToolSetCategoryID = models.ForeignKey("ToolSetCategories",db_column='ToolSetCategoryID',on_delete=models.CASCADE) ToolSetTypeID = models.ForeignKey("ToolSetTypes",db_column='ToolSetTypeID',on_delete=models.CASCADE) ToolSetSubTypeID = models.ForeignKey("ToolSetSubTypes",db_column='ToolSetSubTypeID',on_delete=models.CASCADE) Syringe = models.CharField(db_column='Syringe', max_length=100) Bandage = models.CharField(db_column='Bandage', max_length=100) class Meta: managed = False db_table = 'tblToolSets' default_permissions = ['add','edit','delete'] -
Django dev server does not automatically reload after saving files
I tested Django 3 a few months ago, and it all worked well. The browser refreshed itself after I made a change to files (.html and .py). Now I have an issue with a newly created Django project, the browser doesn't automatically reload after I saved a change that I made on my local machine. OS: Windows 11 Editor: PyCharm / VS Code Django 4.0.4 Python 3.10.4 Directory structure project/ ├── project/ │ ├── ... │ ├── settings.py │ ├── urls.py │ └── ... ├── first_app/ │ ├── ... │ ├── urls.py │ ├── views.y │ └── ... ├── templates/ │ └── first_app/ │ └── index_view.html └── manage.py Default settings.py file with .... INSTALLED_APPS = [ ... 'first_app', ... ] 'DIRS': [BASE_DIR / 'templates'] .... project/urls.py .... urlpatterns = [ path('', include('first_app.urls') ] .... first_app/views.py .... class IndexView(generic.TemplateView): template_name = 'first_app/index_view.html' ... first_app/urls.py .... urlpatterns = [ path('', views.IndexView.as_view(), name='index') ] .... templates/first_app/index_view.html .... <p> Test paragraph 1 </p> .... I run the server locally with py manage.py runserver When I change 'paragraph' to 'example' in index_view.html and save it, it is supposed to automatically refresh the browser and display Test example 1. But the browser doesn't reload. I have … -
Google maps doesn't zoom on polyline in modal with django
I have page that contains information about clients. In this page a have a button that open a modal with some specific information and another button that open another modal that contains google map. In this map I draw a polyline and I want to zoom in this polyline. When the button to open the modal with the map is clicked, I get information about the polyline with ajax and load the map. The this modal is open in the web page it has no zoom. Here is my code: HTML definition of modal: <!-- Div class to show path map with modal --> <div class="modal fade" id="modalPath" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg modal-dialog-centered" id="modal-path-type"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Tratte</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body" id="modal-body-for-path"> <div class="container shadow-lg p-3 mb-5 bg-body rounded-3 border border-secondary" id="map" style="width: 100%; height: 400px;"></div> <div id="map"> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-toggle="modal" data-bs-target="#modalPathsList" id="go_back">Indietro</button> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> Here javascript code to get data with ajax and load the map: function get_and_show_route(path_id, pilot_id){ const modal_body = document.getElementById('modal-body-for-path'); $.ajax({ type: 'GET', // Request's type url: '/modal-path-info/' + path_id, // Request's url … -
How to authenticate Django URLs using bearer token generated by Angular Azure AD?
I have a situation, currently, my application is built using Django and Angular for UI and Backend. In Angular UI I'm using Azure AD for user login to access the application, then it generates the bearer token. I have written all the APIs in Django which are unprotected/less secured Now my question is how can I use the "Bearer token" which got generated by Angular UI for all the Django API calls or Django URLs? How can I validate the Django URLs using Azure AD??? -
[Pyinstaller][Django] Overwrite file in third-party libraries only for exe
I need to overwrite third-party library to working with pyinstaller. I need this only for compile my django project to working as exe on windows so i don't wanna overwite all packages in my project, just change this one file for compilation purpose. In coreschema witch use one of the package required for django i need to change (path _MEIPASS witch is use for pyinstaller) : loader = jinja2.PackageLoader('coreschema', 'templates') to if getattr(sys, 'frozen', False): # we are running in a bundle bundle_dir = sys._MEIPASS loader = jinja2.FileSystemLoader(bundle_dir) else: loader = jinja2.PackageLoader('coreschema', 'templates') env = jinja2.Environment(loader=loader) How to do this ? -
Project django files(or path) in frontend
I have a model Flights : class Flights(models.Model): field = models.ForeignKey(Field, on_delete=models.CASCADE) datetime = models.DateTimeField(blank=True, null=True, default=timezone.now()) nir = models.FileField(upload_to = user_directory_path_flights, null=True, blank=True) red = models.FileField(upload_to = user_directory_path_flights, null=True, blank=True) rededge = models.FileField(upload_to = user_directory_path_flights, null=True, blank=True) green = models.FileField(upload_to = user_directory_path_flights, null=True, blank=True) which have a lot of Filefields. Im trying to print all the flights in a datatable and i have no idea how to implement something like that for so many files. I tried : <tbody> {% for flight in flights%} <tr> <td>{{flight.datetime}}</td> {% for file in request.FILES%} <th>{{flight.request.FILES.name}} </th> {% endfor %} <td><button type="button" class="stressbtn btn btn-danger"</td> </tr> {% endfor %} </tbody> but it doesnt work . I can access the files when im POSTing them in the db, but now i want to retrieve them so i can put them in the datatable,either just the path or the whole image . -
Django Rest Framework app security preparation for production
Intro I've built a web application with multiple services: frontend (react) backend (API and admin panel) (Django Rest Framework + simple jwt auth) Redis, DB, Nginx and etc Kubernetes cluster The app isn't small like 60k+ lines of code. It's a startup. I mentioned it to let you know that probably I wouldn't have that much attention from hackers or traffic at all. Hence I have a space to improve gradually. The auth is done with DRF simple jwt library. Expiring Access + Refresh token. Problem statement I did a security audit and found imperfections from the security architecture perspective. I don't know how those issues are crucial, how should I fix them, or what issues can be fixed later. So I'm seeking solutions and advice. I would prefer an optimal proportion between the speed and quality rather than quality only (If I miss about that let me know) hence if something is "nice to have" rather than "important" I would put it to the backlog of next releases. The actual list of issues Let's refer by its number if you want to. #1 Authentication methods My current setup: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', … -
Django - Datatable multiple models with json format
I'm able to use datatable with one class model by getting json data. https://datatables.net/ However, I would like to add another class with foreign key to models.py. Something like this: class AnotherModel(models.Model): description = models.CharField(max_length=256) ibvs = models.ForeignKey(Ibv, on_delete=models.CASCADE) How I can arrange json get_data function and ajax? And, I am super confused about json file format & how to pass AnotherModel values to the table.(I'd like to show all models in one table) MODELS.PY class Ibv(models.Model): MUESTRAS = ( ('cDNA', 'cDNA'), ('RNA', 'RNA'), ) # id = models.IntegerField(primary_key=True) code = models.CharField(max_length=256) muestra = models.CharField(max_length=256, null=True, choices=MUESTRAS) ship = models.CharField(max_length=256) num = models.CharField(max_length=256) enc = models.CharField(max_length=256) obv = models.CharField(max_length=256) result = models.TextField() created_at = models.DateField(auto_now=True) def __str__(self): return self.result # json def get_data(self): return { 'id': self.id, 'code': self.code, 'muestra': self.muestra, 'ship': self.ship, 'num': self.num, 'enc': self.enc, 'obv': self.obv, 'result': self.result, 'created_at': self.created_at, } VIEWS.PY def ibv_json(request): ibvs = Ibv.objects.all() data = [ibv.get_data() for ibv in ibvs] response = {'data': data} return JsonResponse(response) BASE.HTML var table = $('#example').DataTable({ // json to fill the table rows and columns "ajax": { url: "/json", type: "GET" }, "columns": [ {"data": "id"}, {"data": "code"}, {"data": "muestra"}, {"data": "ship"}, {"data": "num"}, {"data": "enc"}, {"data": "obv"}, … -
How to insert data in child table from react to django rest framework models
I'm new to React and Django rest framework. I want to insert profile data into the Django model using fetch API in react. I'm continuously getting response header as: {"user":["Incorrect type. Expected pk value, received str."]} I've checked by printing response on console, and it gives status code '200 OK'. But it didn't update the database as well. My submit form function in react is: const handleSubmit = (e) => { e.preventDefault(); const profile = profileObj(selectedProfileImg, contact, city, country, address); localStorage.setItem('profile', JSON.stringify(profile)) let form_data = new FormData() // ************************* // this is the foreign key in the model and it gives the problem. // ************************* form_data.append('user',JSON.parse(localStorage.getItem('data')).id) // (foriegn key value) User added by signing up form_data.append('profile_img', profile.prof_img) form_data.append('contact',profile.contact) form_data.append('city',profile.city) form_data.append('country',profile.country) form_data.append('address',profile.address) form_data.append('store_title','storename') // (foriegn key value) Data with this key exists in database form_data.append('cus_status',profile.cus_status) // ********************************* // Also I want to know what the boundary means in content // type. As I see it on google so I used it but removing it // gives another boundary error. // ********************************* fetch('http://localhost:8000/customer_apis/addCustomer/', { method: 'POST', headers: { 'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' }, body: form_data }) .then(res => { console.log(res) console.log(res.status) if (res.status !== 200) document.getElementById('text-error').innerHTML = res.statusText else { navigate('/create_store') } }) … -
Uploading images with HTMX in django
I am trying to implement image adding functionality through HTMX. Adding the photo is no problem. However, once the photo is added in the view, the image link does not show up. It looks like no photo has been added but when I hit the refresh button, the link is being displayed. What I am trying to achieve is that, once the photo is uploaded and the form is saved, I want the link to show up to confirm for the user that their photo is uploaded. This is my form template <form action='' method="POST" class="form" hx-post='' hx-swap='outerHTML' enctype="multipart/form-data" hx-post="{{request.path}}" hx-encoding="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form-group"> {{field}} </div> {% endfor %} <div class='htmx-indicator'>Loading...</div> <div class="text-center"> <button class='htmx-inverted-indicator' style='margin-top:10px;' type='submit' >Save</button> </div> {% if message %} <p>{{ message }}</p> {% endif %} </form> I am then including this template in the update template. Is there anyway to get the wished result without using JavaScript? -
Getting null when doing request from browser but it is not null when same is done using postman
I am using django as a backend, React as frontend and cloud firestore is my DB. I am setting the batch id as the django session whenever any user login or create an account and the sending the request from the frontend to know which batch is currently logged in. This is my backend code class UserInHomepage(viewsets.ModelViewSet): def list(self, request, format=None): print("abc",self.request.session.get('batch_code')) if not self.request.session.exists(self.request.session.session_key): self.request.session.create() data={ 'code': self.request.session.get('batch_code') } print(self.request.session.get('batch_code')) if data['code'] == None: return JsonResponse(data, status=status.HTTP_400_BAD_REQUEST) return JsonResponse(data, status=status.HTTP_200_OK) And this is my frontend througn which i am requesting which user is currently logged in useEffect(async ()=>{ fetch('/student/user-in-homepage/') .then((response) => response.json()) .then((data) => { console.log(data.code) }) },[]) But it prints null And the same request on postman gives the batch id which is currently logged in. -
Is there any solution to encrypt integer in Django using Django Cryptography package
I am trying to encrypt Django Integer Choices field using Django Cryptography package, here is the documentation: https://django-cryptography.readthedocs.io/en/latest/examples.html. Here is my code. from django_cryptography.fields import encrypt class NumberOfCars(models.IntegerChoices): One_Vehicle = 1 Two_Vehicle = 2 Three_To_Four = 4 Five_To_Eight = 7 More_than_Eight = 9 NumberOfCars = encrypt(models.IntegerField(choices=NumberOfCars.choices)) I am using Mysql database, Python==3.10 Django==4.0.4 While running migrations i got this error: PS C:\Users\lumkile\Desktop\Django\thariauth> py manage.py makemigrations Traceback (most recent call last): File "C:\Users\lumkile\Desktop\Django\thariauth\manage.py", line 22, in <module> main() File "C:\Users\lumkile\Desktop\Django\thariauth\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 455, in execute self.check() File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 487, in check all_issues = checks.run_checks( File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\model_checks.py", line 36, in check_all_models errors.extend(model.check(**kwargs)) File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 1442, in check *cls._check_fields(**kwargs), File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\base.py", line 1554, in _check_fields errors.extend(field.check(**kwargs)) File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django_cryptography\fields.py", line 121, in check errors = super().check(**kwargs) File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 1931, in check *super().check(**kwargs), File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 252, in check *self._check_validators(), File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", line 413, in _check_validators for i, validator in enumerate(self.validators): File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\lumkile\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\__init__.py", … -
Django ORM - Condition or Filter on LEFT JOIN
I will try to be precise with this as much as possible. Imagine these two models. whose relation was set up years ago: class Event(models.Model): instance_created_date = models.DateTimeField(auto_now_add=True) car = models.ForeignKey(Car, on_delete=models.CASCADE, related_name="car_events") ... a lot of normal text fields here, but they dont matter for this problem. and class Car(models.Model): a lot of text fields here, but they dont matter for this problem. hide_from_company_search = models.BooleanField(default=False) images = models.ManyToManyField(Image, through=CarImage) Lets say I want to query the amount of events for a given car: def get_car_events_qs() -> QuerySet: six_days_ago = (timezone.now().replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=6)) cars = Car.objects.prefetch_related( 'car_events', ).filter( some_conditions_on_fields=False, ).annotate( num_car_events=Count( 'car_events', filter=Q(car_events__instance_created_date__gt=six_days_ago), distinct=True) ) return cars The really tricky part for this is the performance of the query: Cars has 450.000 entries, and Events has 156.850.048. All fields that I am using to query are indexed. The query takes around 4 minutes to complete, depending on the db load. This above ORM query will result in the following sql: SELECT "core_car"."id", COUNT("analytics_carevent"."id") FILTER (WHERE ("analytics_carevent"."event" = 'view' AND "analytics_carevent"."instance_created_date" >= '2022-05-10T07:45:16.672279+00:00'::timestamptz AND "analytics_carevent"."instance_created_date" < '2022-05-11T07:45:16.672284+00:00'::timestamptz)) AS "num_cars_view", LEFT OUTER JOIN "analytics_carevent" ON ("core_car"."id" = "analytics_carevent"."car_id") WHERE ... some conditions that dont matter GROUP BY "core_car"."id" … -
Is it possible to make 'cart' with django Class Based View?
I am trying to make a simple e-commerce website and followed some tutorials. However, the author of the book used complicated function based view to make cart function.. there are bunch of session stuffs.. and I don't understand the logic.. and I am trying to think the other way.. what about use database to store all the cart related data, and use CBV to build it? for example, CartListView to see the contents of the cart, and CartUpdateView to change the quantity.. then are they going to be two different pages? separated page that user should go to the different page to change the value?? please help me T T -
How to clear this user-role permissions overlap in my Django API project?
Project setup: I am working on a project where we’re developing a role-based access for users. This means that user_1 is role (group) “Supervisor” and has certain permissions, whereas user_2 is role “User” and has less permissions. These permissions are already defined (we were given a matrix of the permissions of each role). A permission is a collection of endpoints. Models: The User model is in a M2M relation with the Group and Permission models. The Group model is in a M2M relationship with the Permission model and the Permission model itself is in a M2M relationship with the Endpoint model. Flow: Users are assigned 0 or more groups. A group is consisted of 0 or more permissions. A permission is consisted of 0 or more endpoints. Tech stack: Django (DRF API) as a backend, vue.js frontend. Problem: Upon visiting "Page X" on the front end, the app hits endpoints "/api/endpoint-1" and "/api/endpoint-2/" in order to collect the necessary data. The user with role "User" should see all contents of this page. However, then the user with role "User" decides to visit "Page Y". There the app hits the same endpoint "/api/endpoint-1/" but the user should have no access to … -
Access custom Mixin's method from view - DRF
I have custom mixin, which has a method with headers and fields parameter: class CustomMixin: @action(detail=False, methods=['get']) def do-method(self,request,params): //some stuff here also I have view set: class ModulViewSet(ModelViewSet,CustomMixin): //some stuff here I'm interested how to pass 'params' parameter to do-method in ModulViewSet Thanks in advance -
When request can be None in django-filter
In documentation of django-filter in part with ModelChoiceFilter met this: def departments(request): if request is None: return Department.objects.none() company = request.user.company return company.department_set.all() class EmployeeFilter(filters.FilterSet): department = filters.ModelChoiceFilter(queryset=departments) But how request could be None? We always have request. Thats how request/response model work -
How can I make web video capture in Django project
I am working on a Django Web project. I'm trying to embed the youtube video on my website and click button to capture the video image with dragging the part of it. I followed some codes which use 'canvas2html' in javascript, but it failed catching the video image for some reason. This is my goal. see the embed youtube video on our site and stop the video when we want to capture. click 'capture' button below and it activates mouse to drag and take the part of image we want to download. capture that part of image and download in our local directory. How can I solve this challenging situation? -
Django modal not load js
I would like to execute a js function within a Bootstrap modal with a Django filter form. The modal works fine and i can see the form but some js functionality not works, only if i add again the js inside the filter.html. base.html: {% load static %} <!DOCTYPE html> <html lang="es"> <body> <div class="modal fade" id="custom-modal" role="dialog"></div> {% block content %} {% endblock %} <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script> <script src="{% static 'js/functions.js' %}"></script> <body> </html> list.html: {% extends "base.html" %} {% load static %} {% load app_tags %} {% load widget_tweaks %} {% block content %} ... <button type="button" class="btn card_header_button" onclick="return openCustomModal('{% url element_filter %}')" data-toggle="tooltip" data-placement="top" title="Filtrar"> <span class="fas fa-filter custom_icon"></span> </button> ... {% endblock content %} filter.html: {% load static %} {% load app_tags %} {% load widget_tweaks %} <div class="modal-dialog modal-lg"> <!-- Here show the form --> </div> Any idea how to solve this ? Thanks in advance. -
Flask : Development mode vs Production mode (uWSGI)
I wanted to know the benefits of running Flask in production mode using uWSGI versus running it in development mode. What are the benefits you gain by using production mode? Scaling? Utilize all CPU cores? I would really appreciate it if someone could point out the benefits and differences. -
How to filter using get_queryset in Django Rest Framework?
Currently, the API I'm pulling is as such: http://127.0.0.1:8000/api/locs/data/2 and the output is as such: { "id": 2, "date": "2019-01-07", "hour": null, "measurement": null, "location": 6 } What I want is actually filtering by the location value, so from the API url above, I would love to pull all the data that is from location: 2. How can I achieve that? What I have so far: views.py class LocationDataView(viewsets.ModelViewSet): serializer_class = LocationDataSerializer permission_classes = [IsAuthenticated] authentication_classes = [TokenAuthentication] def get_queryset(self): queryset = LocationData.objects.all() pk = self.kwargs['pk'] queryset = queryset.filter(location=pk) def perform_create(self, serializer): serializer.save() and urls.py from django.urls import path, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'locs', views.LocationListView, 'locs') router.register(r'locs/data', views.LocationDataView, 'locs/data') urlpatterns = [ path('', include(router.urls)), path('locs/forecast-data/', views.getForecastData, name='forecast-data'), ] My question is that, how can I access the pk for the location? -
How to set CSS classes of all form inputs in FormView?
class PetAddView(CreateView,LoginRequiredMixin): model = Pet fields = ['name','animal_type','breed','color','age','height','price','city','sex','photo'] template_name = 'pets/pet-add.html' def get_form(self, form_class=None): form = self.get_form_class()(**self.get_form_kwargs()) form.fields['photo'].widget.attrs.update({'onchange':'preview();'}) for field in form.fields: form.fields[field].widget.attrs.update({'class':'form-control'}) return form There's how i deal with this, but I'm looking for more elegant solution. I need to set all input classes as 'form-control'. And would be great to do this in one line. -
How to change folium map in html
I want to use the HTML button or slider to retrieve the values of the Folium map array received from views.py one by one. <div id="maps" style="width:800px;height:800px;"> <div id="map_on" style="width:800px; height:800px; display:inline;" > <div id="map_on_1h" style="width:800px; height:800px; display:inline;" > {{map.0|safe}} </div> <div id="map_on_2h" style="width:800px; height:800px; display:none;" > {{map.1|safe}} </div> <div id="map_on_3h" style="width:800px; height:800px; display:none;" > {{map.2|safe}} </div> <div id="map_on_4h" style="width:800px; height:800px; display:none;" > {{map.3|safe}} </div> <div id="map_on_5h" style="width:800px; height:800px; display:none;" > {{map.4|safe}} </div> <div id="map_on_6h" style="width:800px; height:800px; display:none;" > {{map.5|safe}} </div> <div id="map_on_7h" style="width:800px; height:800px; display:none;" > {{map.6|safe}} </div> <div id="map_on_8h" style="width:800px; height:800px; display:none;" > {{map.7|safe}} </div> <div id="map_on_9h" style="width:800px; height:800px; display:none;" > {{map.8|safe}} </div> </div> map is folium map array This code does not seem appropriate. when i push the button or change slider, i want to change array index <div id="maps" style="width:800px;height:800px;"> <div id="map_on" style="width:800px; height:800px; display:inline;" > <div id="map_on_1h" style="width:800px; height:800px; display:inline;" > {{map.0|safe}} <--map.index--> </div> </div> please help me -
React&Django stack. Deploy on Heroku when Set Debug = False app Show blank page but admin page working
Problem: When i set DEBUG = False and deployed myapp to the heroku. myapp page is not show anything(blank page) but in "https://myappname.heroku/admin" it's working, and if i run on my locallhost (python manage.py runserver)there's no any problem Setting.py: import os from pathlib import Path import django_heroku import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-()1p5aqa_pt&hjn29=k$%t&hjn29=k$t&hjn29=k$' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['https://sbuilt-react-django.herokuapp.com/', 'http://127.0.0.1:8000/'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', 'rest_framework', 'corsheaders' ] CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "whitenoise.middleware.WhiteNoiseMiddleware", '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", "django.middleware.common.CommonMiddleware", ] STATICFILES_STORAGE = "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" ROOT_URLCONF = 'sbuilt.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ './build', ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'sbuilt.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } DATABASES['default'] = dj_database_url.config( default='postgres://fetjtshpanyppx:76cbb8ac254c5a81c5d96e05c7a22c17af991796cdad577e7fc20ad5f957416c@ec2-54-165-178-178.compute-1.amazonaws.com:5432/dfv2autarb32ks') # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators … -
Django blog ProgrammingError/TemplateDoesNotExist error
Am making a django blog at the moment and i get errors with my code when i try to go in to the superuser admin panel and make a post. When i enter the python runserver i get error. I followed along: https://djangocentral.com/building-a-blog-application-with-django/ If i missed any info for you to help me solve it ask and i will provide it asap. The Errors raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) django.template.exceptions.TemplateDoesNotExist: index.html, APP_project4/post_list.html When i login to superuser and try to click Posts i get error: django.db.utils.ProgrammingError: relation "APP_project4_post" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "APP_project4_post" ^ In the APP folder views.py from django.views import generic from .models import Post class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' urls.py from django.urls import path from . import views urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] Models.py from django.db import models from django.contrib.auth.models import User STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title …