Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any way to make this postgres query faster?
So I have this query; SELECT * FROM api_points WHERE cat_level_5 = ANY(ARRAY['7223b580c20758c7','3e23543ccb9a2ef4','bbaec92cedb8a3bc',...]) AND NOT cat_level_5 = ANY(ARRAY['8ccb9d2231a318e4']) And there are about 2~3 million of records about geospatial points. The categories are hierarchical, there are 5 columns named as cat_level_1, cat_level_2, cat_level_3, cat_level_4 and cat_level_5. This query, with many level 5 categories specified, takes about 1-2 minutes to complete. I switched from using IN operator to = with arrays. I can change the category structure or category data type for faster indexing. When I add an index with btree(cat_level_1, cat_level_2, cat_level_3, cat_level_4, cat_level_5) it doesn't make much of a difference by the way. Here is the result of EXPLAIN(ANALYZE, BUFFERS) Edit I edited the SQL query to this and the result is this. EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM ( SELECT * FROM unnest(ARRAY['7223b580c20758c7','3e23543ccb9a2ef4','bbaec92cedb8a3bc',...]) cat_level_5 WHERE cat_level_5 NOT IN ( SELECT * FROM unnest(ARRAY['8ccb9d2231a318e4']) ) ) categories JOIN api_point USING (cat_level_5) The table structure is defined by this django model; class Point(models.Model): poi_id = models.TextField(primary_key=True) poi_name = models.TextField(default = "") poi_address = models.TextField(default = "") location = models.TextField(default = "") location_info = models.TextField(default = "") history = models.DateField(default = datetime.date.today) city_code = models.IntegerField() town_code = models.IntegerField() quarter_code = models.IntegerField() icon_url … -
Develop OSM Map editing facility and Map screen sharing System
I am new to OSM Map API but I have already used GIS Application development using Openlayer 6, Mapnik, Mapproxy, django and PostgreSQL with postgis. Now I want a view of OpenStreetMap and Map screen sharing system for online review of maps with OpenStreetMap editing facility. -
DJANGO and static css/js files
I'm trying to build my first webpage after follow cs50w free course. I've extract the html (and js) code from nicepage.com and using django, I'm experiencing some problems to reflect the wanted style. On layout.html I wrote {% load static %} and my index.html extend the layout.html Basically the references to the static folder are not working. Any input is appreciated. Thanks This is layout.html enter image description here This is index.html enter image description here This is the django tree enter image description here This is what I expect enter image description here This is the result enter image description here -
Django -- Pagination
I'm currently working on To-Do App using Django web framework. I have two separate containers(list) which are upcoming items and completed to-do items. Furthermore, I'm not sure how to add this feature which was If I click page-3 in upcoming Item, and then I click page-2 in completed Items I'm redirecting to page-1 in upcoming Items and page-2 in completed Items. I don't want like this. I wanted like page-3 in upcoming and page-2 in completed. Is there any method I can do it with Django or JavaScript. I have also attached the image of app I have created. models.py class Todo(models.Model): date_created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) title = models.CharField(max_length=200) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title views.py def home(request): todo_form = TodoForm() current = timezone.now() todo_items_upcoming = Todo.objects.filter(user_id=request.user, completed=False).order_by('-date_created') todo_items_completed = Todo.objects.filter(user_id=request.user, completed=True) pagi1 = Paginator(todo_items_upcoming, 4) pagi2 = Paginator(todo_items_completed, 4) page_num = request.GET.get('upcoming', 1) page_num2 = request.GET.get('completed', 1) page_obj = pagi1.get_page(page_num) page_obj2 = pagi2.get_page(page_num2) if request.method == "POST": todo_form1 = TodoForm(request.POST) if todo_form1.is_valid(): data = todo_form1.cleaned_data.get('title') obj = Todo.objects.create(date_created=current, title=data, user_id=request.user) context = {'todo_form':todo_form, 'page_obj':page_obj, 'page_obj2':page_obj2, 'pagi1':pagi1, 'pagi2':pagi2, 'page_num2':int(page_num2),'page_num':int(page_num)} return render(request, 'todo/main.html', context) main.html {% extends 'todo/index.html' %} {% load crispy_forms_tags %} {% block content %} … -
How I can get the number of online users in Django
How I can get the (count) number of online users in Django and display the number in the admin screen should I add Boolean field in the models is_online = models.BooleanField() or there is another way -
single Omr quries
There are thousands of values in the DB for this model. I would like to efficiently and elegantly use that QuerySets alone to get the job done, how can I write the queries?? from django.contrib.auth.models import User from django.db import models class CUser(User): score = models.IntegerField() The custom user has an additional field (“score”), we want to do the following operations using ORM queries only. : Calculate the mean score of all users. Find the user with the highest score. Find if there is any user with score less than 2 (return True/False) Find all the users which have score exactly equal to the mean score. Change the score value of all users in a single query to 100 (one hundred) Find all the users which don't have score 10 or 20 Print a list of all the score values from all users excluding the first 10 users. -
What is the current solution to monitoring and managing Celery in Django Admin?
I am using: Django==3.0.4 Celery==4.3.0 I am looking for a tool or guidance on implementing the ability to manage (revoke, suspend, etc) and monitor Celery Tasks in Django Admin. I see that in older versions of Django, we could use django-celery which added Djcelery to the Admin tables. Is there anything that is similar to django-celery but compatible with my versions? I currently use Flower, but am looking for something in Django Admin as well. Right now it seems my path to doing this is just to create my own models that track Celery tasks but I'd like to avoid this if there is a better or more complete way. -
How to create Authentication & Authorization in Django Rest Framework using Viewsets
I am working with Django Rest Framework where I have created few APIs for fetching record from the database. Now I also want to have Login with Permissions for different kind of Custom Users (like Teacher, Student etc.). I am working with viewsets.py and router.py where I have created classes for fetching record from the database. Here is my sample code: models.py from django.db import models class userRegistrationModel(models.Model): email = models.EmailField(max_length=200, blank=False, null=True) password = models.CharField(max_length=200, blank=False, null=True) def __str__(self): return self.email serializers.py from rest_framework import serializers from myapp.models import * class userRegistrationModelSerializer(serializers.ModelSerializer): class Meta: model = userRegistrationModel fields = '__all__' viewsets.py from rest_framework import viewsets from . import models from . import serializers class userRegistrationModelViewset(viewsets.ModelViewSet): queryset = models.userRegistrationModel.objects.all() serializer_class = serializers.userRegistrationModelSerializer router.py from myapp.viewsets import * from rest_framework import routers router = routers.DefaultRouter() router.register('userRegistrationModel', userRegistrationModelViewset), I am able to get the record from my database in JSON form. Can anyone help me out that how to create classes/functions in viewsets.py for Authentication & Authorization so that I can get that functionality in my application. If any Github source or Any code you can write here for me. Thanks -
send parameters from django updateview to model form
in function based view it's easy to pass parameters to form instances as form = FormName(user_id=..) and do other staffs, but I'm wondering how to do this in django update view It's my view class MedicalrecordUpdate(UpdateView): model = MedicalRecords form_class = EditMedicalRecord success_url = "." template_name = "medicalrecord/edit_medicalrecord.html" # ?? no idea how to pass user id to EditMedicalRecord form forms.py class EditMedicalRecord(forms.ModelForm): def __init__(self, *args, **kwargs): user_id = kwargs.pop("user_id") super(EditMedicalRecord, self).__init__(*args, **kwargs) ... ... -
After reinstalling Django due to computer crash, I am getting following error when I try to access the models in my app
After reinstalling Django due to computer crash, I am getting following error when I try to access the models in my app. What could be possible solution ? Please note that previously I did not set any environment variable but still working fine. Kindly suggest a fix. Because of this I am not able to proceed further. File "C:\Users\VaibhavK\AppData\Local\Programs\Python\Python38\lib\site-packag es\django\conf_init_.py", line 63, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, b ut settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
AttributeError: 'datetime.date' object has no attribute 'tzinfo' Datetime Django
Im having a trouble how to set default date in my models, the format should I have in my database is date not datetime but the resources mostly I find is the code below, Is there any way how to set my models into date? Thanks in advance! The output/format saved in database should like this 2020-11-24 Format of my date in sql from datetime import datetime class Person(models.Model): date_upload = models.DateTimeField(default=datetime.now().strftime ("%Y-%m-%d"), blank=True) -
["'11/ 4/ 1998' value has an invalid date format. It must be in YYYY-MM-DD format."]
How do i convert the date format from this 11/ 4/ 1998 to 11-4-1998? views.py birthday = request.POST['birthday'] student = StudentProfile( birthday=birthday,) models.py birthday = models.DateField(null=True, blank=True) -
How to render to template with dropdownbox in django?
I'm a beginner Django. And I got a problem with rendering to template. I have a model(models.py) which has class "FuelInfo" ; includes ForeignKey. from django.db import models class Traveler(models.Model): traveler_name = models.CharField(max_length=10) def __str__(self): return self.traveler_name class FuelInfo(models.Model): name = models.ForeignKey(Traveler, on_delete=models.SET_NULL, null=True) car = models.CharField(null=True, max_length=50) efficiency = models.FloatField() def __str__(self): return str(self.name) Also views.py is like : from django.shortcuts import render, get_object_or_404 from .models import FuelInfo def traveler_list(request): travelers = FuelInfo.objects.all() context = {'travelers':travelers} return render(request, 'fuelcost/home.html', context) def traveler_detail(request, pk): traveler = get_object_or_404(FuelInfo, pk=pk) return render(request, 'fuelcost/calfuel.html', {'traveler': traveler}) And urls.py is : from django.urls import path from . import views app_name = 'fuelcost' urlpatterns = [ path('', views.traveler_list, name='home'), path('<int:pk>/', views.traveler_detail, name='calfuel'), ] I want to make a dropdown that is render to template "calfuel.html" in home.html. So I made a template("home.html") like : {% extends "base_generic.html" %} {% block content %} <body> {% if travelers %} <form method="POST" action="{% url 'fuelcost:calfuel' pk=traveler.pk %}"> {% csrf_token %} <select name="traveler"> {% for traveler in travelers %} <option value="{{ traveler.id }}">{{ traveler.name }}</option> {% endfor %} </select> <input type="submit" value="Select" /> </form> {% else %} <p>No travelers are available</p> {% endif %} </body> {% endblock %} But … -
Invalid Response in Ajax POST Django
In trying to post data using Django class-based views (CreateView), I encountered an issue. Ajax is unable to post data. models.py class UserProfile(geo_models.Model): user = geo_models.OneToOneField(User, on_delete=geo_models.CASCADE) user_loc = geo_models.PointField(null=False, srid=20137) post_date = geo_models.DateTimeField(default=timezone.now()) USERNAME_FIELD ='' def get_absolute_url(self): return reverse('rent_app:user-create', kwargs={'pk': self.pk}) def __unicode__(self): return self.id views.py class UserProfileCreate(CreateView): model = UserProfile form_class = UserProfileModelForm success_url = reverse_lazy('home') template_name = 'rent_app/filter_by_distance.html' <head> {% load static %} {% load leaflet_tags %} {% load geojson_tags %} {% block extra_assets %} {% leaflet_js %} {% leaflet_css %} {% endblock %} </head> {% block content %} <body> {% leaflet_map "map" callback="ourfunction" %} </body> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script> var csrftoken = "{{ csrf_token }}"; function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); function ourfunction(map, options) { map.locate({setView: true, maxZoom: 16}); map.on('locationfound', onLocationFound); function onLocationFound(e) { var radius = e.accuracy; var lat = e.latlng.lat; var lng = e.latlng.lng; var user_loc = "Point ("+lat+" "+lng+")" var counter = 0; //var user_loc=(e.latlng.lat+e.latlng.lng,srid=20137); postdate = new Date(); var datetime = postdate.getDate() + "/" + (postdate.getMonth()+1) + "/" + postdate.getFullYear() + " @ " + postdate.getHours() + … -
request.is_ajax() not working in Django Version 3.1.1
In the following code, I am getting redirect to this text {'saved': 1} instead of the template which is rendered by the view, here, I used request.is_ajax() function. and I am using Django Version: 3.1.1 Views.py def add_Patient(request): if request.is_ajax(): add = Patient( name=request.POST['name'], gender=request.POST['gender'], birthdate=request.POST['birthdate'], age=request.POST['age'] ) add.save() return JsonResponse({'saved': 1}) return render(request, 'Patient_template/add_patient.html') add_patient.html <script> const form = document.getElementById("patient"); form.addEventListener("submit", submitHandler); function submitHandler(e){ e.preventDefault(); $.ajax({ url : {% url 'Patient:add' %}, type : 'POST', data : $("#form").serialize(), dataType: 'json', success: function(msg){ if (msg.saved === 1){ alert("Data Saved"); form.reset(); } } }); } </script> So help me to find an alternative solution or solve this problem. -
How to Get Data Join Django Rest Framework
I want to join two tables, i have model : Employee : class Employee(models.Model): employee_identity = models.CharField(max_length=255, blank=True, null=True) full_name = models.CharField(max_length=255, blank=True, null=True) place_birth = models.CharField(max_length=255, blank=True, null=True) date_birth = models.DateField(blank=True, null=True) role = models.CharField(max_length=255, blank=True, null=True) no_hp = models.CharField(max_length=255, blank=True, null=True) address = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'employee' Penalty : class Penalty(models.Model): employee = models.ForeignKey(Employee,on_delete=models.CASCADE) type = models.CharField(max_length=255, blank=True, null=True) start_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) doc = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'penalty' My EmployeeSerializer : class EmployeeSerializer (serializers.ModelSerializer): class Meta: model = Employee fields = '__all__' My PenaltySerializer: class PenaltySerializer (serializers.ModelSerializer): class Meta: model = Penalty fields = ('employee','type','start_date','end_date') My expected Penalty result : "results": [ { "employee": 14871, "type": "low", "start_date": "2018-10-15", "end_date": "2018-10-16", "employee_identity": "A1738129", "full_name": "Full name here", "role": "staff" } ] I have tried to using this in my serializer class PenaltySerializer (serializers.ModelSerializer): a = EmployeeSerializer(many=True,read_only=True) class Meta: model = Penalty fields = ('employee','type','start_date','end_date','a') but the result of 'a' not showed up. -
Display Value in Django template every time for loop runs
I am trying to print values in my template every time for loop runs. My code: for a in result: b = [] for i in test: b.append(x[i]) return render(request, 'test.html', {'b': b} I know above code is wrong but how can I print or send data to django template every time loop runs. I want to send them to seperate table every time for loop runs. I can't append all of them to same list and print all at the same time. -
How do i compute the age and posts it in the template using django
I have this code in views.py from datetime import date def selectrecord(request): myID = request.GET.get("StudentID") myrecord=StudentsEnrollmentRecord.objects.filter(id=myID) today = date.today() born = myrecord.birthday //this is the field studentage = today.year - born.year - ((today.month, today.day) < (born.month, born.day)) //I dont know to get the year, month and day in my database the data -
Django REST Framework corsheaders
I just hosted an API in PythonAnywhere for a web app that we're building with a friend for fun, and when we send any request from the web app frontend (for now, in our localhost) to the api we're getting: Access to XMLHttpRequest at 'http://******.pythonanywhere.com/api/users/login/' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: Request header field access-control-allow-headers is not allowed by Access-Control-Allow-Headers in preflight response. We did two things so far: First, adding the header to the POST ajax request: const loginForm = document.querySelector('#login-form'); const login_URL = 'http://***.pythonanywhere.com/api/users/login/'; let xmlHttp = new XMLHttpRequest(); loginForm.addEventListener('submit', (event) => { event.preventDefault(); formData = new FormData(loginForm); xmlHttp.open("POST", login_URL, true); xmlHttp.setRequestHeader("Access-Control-Allow-Headers", "Accept"); //also tried with "*" instead of "Accept" xmlHttp.send(formData); xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4) { alert(xmlHttp.responseText); } } }) Second, in the backend I ran pip3 install django-cors-headers, which is recommended in the official DRF documentation. And in the settings.py I added: INSTALLED_APPS = [ # ... 'corsheaders', # ... ] In the MIDDLEWARE list I put 'corsheaders.middleware.CorsMiddleware' first of all. And lastly: from corsheaders.defaults import default_headers ALLOWED_HOSTS = ['***.pythonanywhere.com', 'localhost', '127.0.0.1'] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_URLS_REGEX = r'^/api/.*$' # tried with and without this. Is the path of … -
Why is my urls.py file not being detected?
I just created a new app for my django project and have created a urls.py, models.py, views.py, and serializers.py. However, my project is not detecting the URLs in the urls.py file. If I go to a different app in my project and edit the urls.py file, the system detects it. However, it will not detect it in the new one. Here is the urls.py file: from django.conf.urls import url from . import views urlpatterns = [ url(r'^knorket-kaitongo-integration/$', views.KnorketKaitongoIntegration.as_view(), name='knorket_kaitongo_integration'), ] Does anyone know why this wouldn't be detected? It's not showing up on the API screen either. -
Django Models not updating tables on MySql
I'm building this app in Django and I'm having an issue when I changed the models if I add a new field or removed it. I save, then makemigrations and migrate. However, the changes are not reflected inside MySql or inside the database tables. If I delete the database and do everything from the start then I see the changes. What I'm doing wrong? I don't believe I have to delete the whole database every time I changed or add something in models.py I connect Django to MySql using XAMPP 7.3.27, All CRUD is working fine. The issue appears whenever I change the structure in models.py. This is what I have in models.py from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class Category(models.Model): name = models.CharField(max_length=200,db_index=True) slug = models.SlugField(max_length=200,unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('category_detail',args=[self.slug]) class Product(models.Model): category = models.ForeignKey(Category,related_name='products',on_delete=models.CASCADE) author = models.ForeignKey('Author',related_name='authors',on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='products/%Y/%m/%d',blank=True) image2 = models.ImageField(upload_to='products/%Y/%m/%d',blank=True) image3 = models.ImageField(upload_to='products/%Y/%m/%d',blank=True) publisher = models.CharField(max_length=100, db_index=True) release_date = models.DateTimeField(null=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) created = models.DateTimeField(default=timezone.now) updated … -
Is there a way to compute this amount of data and still serve a responsive website?
Currently I am developing a django + react website, that will (I hope) serve a decent number of users. The project demo is mostly complete, and I am starting to think about the scale required to put this thing into production The website essentially does three things: Grab data from external APIs (i.e. Twitter) for 50,000 unique keywords (the keywords dont change). This process happens every 30 minutes Run computation on all of the data, and save that computation to the database When a user visits the website it should serve a pretty graph/chart of all of the computational data per keyword The issue being, this is far too intense a task to be done by the same application that serves the website, users would be waiting decades to see their data. My current plan is to have a separate API made that services the website with the data, that the website can then store in it's database. This separate API would process the data without fear of affecting users, and it should be able to finish its current computation in under 30 minutes, in time for the next round of data. Can anyone help me understand how I can … -
Get more information from a object in serializer and not just the id
I have a Serializers and View which work perfectly well, the only problem now is that I want to be able to get the entire data it contains and just the id number. Let me show you: This is my view: @api_view(['GET']) def TicketListView(request, *args, **kwargs): queryset = Order.objects.filter(ordered=True) username = request.GET.get('username') if username != None: queryset = queryset.by_username(username) # serializer = PostSerializer(queryset, many=True) serializer = TicketListSerializer( queryset, many=True, context={'request': request}) return Response(serializer.data, status=200) Serializers: class TicketListSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' This is the output: [ { "id": 2, "ref_code": "42764745463765476", "start_date": "2021-02-24T01:23:27.135638Z", "ordered_date": "2021-02-24T01:23:13Z", "ordered": true, "being_delivered": false, "received": false, "refund_requested": false, "refund_granted": false, "transaction_id": "w4234", "qr_code": "http://127.0.0.1:8000/media/qrcode/qr_code-42764745463765476_zaqc1a7.png", "user": 1, "shipping_address": null, "billing_address": null, "payment": 1, "coupon": null, "items": [ 2, 1 ] } ] Now, instead of the items to show [2,1], i want it to show the actual data it contains something like this for 1. "item": { "id": 1, "category": "Music", "label": "PopSocial", "likess": 0, "title": "fe", "caption": "asfwa", "photo": "/media/posts/Premium_SUndays_XhustW8.jpg", "date_of_event": "2021-02-24T01:15:10Z", "location": "SRID=4326;POINT (5.712891 7.885147)", "latitude": "7.885147", "longitude": "5.712891", "date_posted": "2021-02-24T01:15:11Z", "likes": 0, "price": "10000.00", "discount_price": 343.0, "digital": false, "slug": "11", "author": 1, "bookmark": [] }, "final_price": 686.0, -
Please see the error in date format. django monthfield error
Refer to this site https://github.com/clearspark/django-monthfield models.py pro_entdate = MonthField(null=True) As in the code above, the model was built and the migration was completed. The creation and modification in "admin" is fine, but if you make partial corrections like this in "postman", "PATCH" ("pro_entdate": "2020-05"), the following error appears. "Date is in the wrong format. Please use one of these formats: YYYY-MM-DD. I don't know why you are looking for "data filed format" before the past revision. I only want the year and month to be entered and modified without the date. -
django going back directories to download file
I have a simple django project structured like this: Root > main (this is the project app) > manage.py v homeview (this is an app) > views.py (and admin.py, urls.py, ... etc) v templates v homeview > downloading.html > ... > flag.txt In my downloading.html file, I want the user to be able to download the flag.txt file that is 3 directories back. This is what downloading.html looks like: <html> ... <a href = '' download> Download </a> </html> I cannot figure out what I need to put in the href attribute to get access to the flag.txt file. I have tried just going back directories from download.html like href='../../../flag.txt' but this does not seem to work.