Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Customize PointField serialization
I want to rename keys in PointField from drf_extra_fields.geo_fields import PointField E.g i want to rename key 'latitude' with 'lat' I found in github source code of PointField https://github.com/Hipo/drf-extra-fields/blob/252e681765645322113f69131e786664f815b919/drf_extra_fields/geo_fields.py and created my own class class MyPointField(PointField): """ Intended to rename fields 'longitude' -> 'lng' 'latitude' -> 'lat' """ def to_representation(self, value): """ Transform POINT object to json. """ if value is None: return value if isinstance(value, GEOSGeometry): value = { "lat": value.y, "lng": value.x } if self.str_points: value['lng'] = smart_str(value.pop('lng')) value['lat'] = smart_str(value.pop('lat')) return value I am using this field in serializers.py class ConstructionSerializer(serializers.ModelSerializer): coordinates = MyPointField() But I have an error "coordinates": [ "Enter a valid location." ] How can I fix the error? -
having problem in mapping my geojson data on html page using Django
how can I show my shape files- polygons on my website? I want to show my polygons on map but I cannot find the way. what should I do? Could you Please help me? Thanks These are my codes : my polygons/view.py( I want to show the "master_plan_dataset" on map): from django.http import HttpResponse from django.shortcuts import render from django.views.generic import TemplateView from django.core import serializers from .models import master_plan from djgeojson.views import GeoJSONLayerView class HomepageView(TemplateView): template_name = "index1.html" def master_plan_dataset(request): master_plans = serializers.serialize('geojson', master_plan.objects.all()) return render(request, 'layers.html', {'master_plans': master_plans}) my polygons/urls.py: from django.conf.urls import include, url from djgeojson import views from . import views urlpatterns = [ url(r'^$', views.HomepageView.as_view(), name='home'), url(r'^master_plan_dataset/$', views.master_plan_dataset, name='master_plan') ] my polygons/models.py: class master_plan(models.Model): id = models.IntegerField(primary_key=True) Landuse = models.CharField(max_length=100) Shape_Area = models.FloatField(null=False) Name_per = models.CharField(max_length=100, default=None) geom = models.MultiPolygonField(srid=4326) def __str__(self): return self.Name_per def __unicode__(self): return self.Name_per class Meta: verbose_name_plural = 'master_plan' and also my Html template => layers.html: <!DOCTYPE html> <html lang="en"> {%load static%} {%load leaflet_tags%} <head> {%leaflet_js%} {%leaflet_css%} <meta charset="UTF-8"> <title>homepage</title> <style type="text/css"> #gis {width:80%;height:500px;} </style> <script type="text/javascript" src="{% static 'dist/leaflet.ajax.js' %}"> </script> </head> <body> <h3> THE WEB SPATIAL DATABASE </h3> <br> <div> <script type = "text/javascript"> function display_layers(map, options) { var … -
Traefik and Django on a Subpath
Following setup I want to achieve inside Docker with Traefik and Django: http://domain/app1 http://domain/app2 My docker-compose.yml contains the following labels for the containers: traefik.http.routers.app1.rule=Host(my.host.de) && PathPrefix(/app1) traefik.http.routers.app1.middlewares=app1 traefik.http.middlewares.app1.headers.customresponseheaders.SCRIPT_NAME=/app1 I did the same for app2. In the settings.py of both apps I set: FORCE_SCRIPT_NAME = env('FORCE_SCRIPT_NAME', default=None) which then should get resolved via the ENV File where I have FORCE_SCRIPT_NAME=/app1. On Django side I always get a 404 with the message that this path does not exist and I should choose from an existing one. Django recognizes the URL as http://my.host.de/app1 and tells me The current path, app1, didn't match any of these. -
Sending a text + HTML email with a calendar ICS attachment in Django or Python
I've been searching for a library or at least functional snippet of code that lets me send an e-mail from Django (or at least in Python) with text content, HTML content, and an ICS calendar attachment that is recognized by every major e-mail client. For my particular use case it's enough if the user is offered an 'add to calendar' button. I feel like this should be a solved problem by now, but I'm only finding answers that refer to libraries that aren't being maintained or that are outdated or incomplete in some other way. I've tested a couple of snippets that will attach an ICS file, but G-mail doesn't give me the option of adding it to the calendar like it usually does. Is there a ready made solution that I'm missing? -
face detection using Django, Python, OpenCV
i want to run the camera on the browser and to use the device's camera to be able to access the attendance for many students from my pc .. but openCV using the main device camera so when i try to run share it with other pc it opens my camera not the one who using it -
How do I add a search TextField in Django?
I am using Django as my WebFramework. I have a Database that we want to search through. To enable a search with auto-completion we use ElasticSearch as library. There we have a method that takes a string as input and returns a list of relevant similar strings. Now we want to add a TextField on our website that displays these suggestions. As soon as the user enters a character into the textfield the function mentioned above should be called and the strings that come as return parameter should be displayed. The input should be updated after each additional character entered. In the following I have a small graphic to better illustrate my desired behavior. Is there a nice way to implement such a thing in django? If it doesn't work with django I would be happy if you steer me in the right direction which tools etc. I have to use. -
Deploy web application that has a .data-00000-of-00001
I have a django project that is basically a API for a chatbot, the chatbot uses tensorflow and it uses a extremely large file that ends in .data-00000-of-00001. I can not upload it to github because it is really big. Anyone knows how can I deploy my web application with this kind of file? -
django orm multiple filter on same many to many field
class Book(models.Model): title = models.CharField(max_length=50) authors = models.ManyToManyField(Author) class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) Suppose I want to get books having atleast two author's whose first names are Test and Tester.So I will proceed with Book.objects.filter(first_name='Test').filter(first_name='Tester') What if I have multiple first name(long list) to check,apart from running a for loop and rawsqlquery are there other options? queryset = Book,objects.all() for i in ['test','tester']: queryset = queryset.filter(first_name=i) -
Callback URL mismatch. Django.Auth0
enter image description here enter image description here enter image description here Please,solve it -
Is there python library or way to read text and image at once from database such as excel and sql? [closed]
For example, my database table looks like: Name Image tiger -
Data changing when multiple users are logged in
I'm making a Django app with Discord OAuth2 so users can log in. When 2 users log in, the data appears on both screens. So if you log in, it'll show your data but if you reload the page, it'll show another user's data. Does anyone know why this happens? Urls.py from django.urls import path from home import views urlpatterns = [ path('', views.main, name='home'), path('/logout', views.discord_logout, name="logout"), path('/settings', views.guild_dashboard, name='guild_dashboard'), path('/settings/edit', views.edit, name='edit'), path('/session_expired', views.session_expired, name='session_expired'), path('/authorize/user', views.main, name='get_authenticated_user'), path('/oauth2/login', views.discord_login, name='oauth2_login'), path('/oauth2/login/redirect', views.discord_login_redirect, name='discord_login_redirect'), ] Views.py from django.shortcuts import render from django.http import HttpResponse, HttpRequest, JsonResponse, HttpResponseRedirect from django.shortcuts import redirect from django.contrib.auth import authenticate, login, logout import requests from django.contrib.auth.models import User from home.auth import DiscordAuthenticationBackend from django.contrib.auth.decorators import login_required from .forms import Prefix import psycopg2 import aiohttp import matplotlib.pyplot as plt import numpy as np import time client_id = "client_id" @login_required(login_url="app/oauth2/login") def main(request: HttpRequest): username = user['username'] guild = [guild for guild in guilds if int(guild["permissions"]) & 0x00000020 == 32] try: connection = connection except: print("ERROR: unable to connect to the database") db = connection.cursor() query = db.execute("select server_count from info") servers = db.fetchone() servers = servers[0] query = db.execute("select user_count from info") users = db.fetchone() … -
Django cannot login with email
I'm trying to login with the email instead of the username. I don't know what I did wrong here. I filtered the DB from the Player instance in models.py which uses AbstractUser. import requests from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt from .forms import PlayerCreationForm from .models import Player # REGISTER VIEW def register_view(request): if request.method != 'POST': form = PlayerCreationForm() else: form = PlayerCreationForm(request.POST) if form.is_valid(): form.save() requests.post('http://127.0.0.1:5000/credentials', json={'email': form.cleaned_data['email'], 'username': form.cleaned_data['username'], 'password': form.cleaned_data['password2']}) return redirect('/login') context = {'form': form} return render(request, "register.html", context) # LOGIN VIEW def login_view(request): if request.user.is_authenticated: return redirect('/') if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') user = Player.objects.filter(email=email, password=password) if user is not None: login(request, user) return redirect('/') else: messages.info(request, 'Incorrect email or password') return render(request, 'login.html') # LOGOUT VIEW def logout_view(request): logout(request) return redirect('/') # HOMEVIEW def home_view(request): return render(request, "base.html") I was given the error of Internal Server Error: /login/ Traceback (most recent call last): File "/home/stevek/.local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/stevek/.local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/stevek/Projects/Python/CRAFTMINE/web/accounts/views.py", line 39, … -
Can I easily "rewrite" an extension using Django staticfiles?
I have a file within my Django project: my_app/static/my_app/bonus_feature.mjs which I have been using via: <script type="module" src="{% static "my_app/bonus_feature.mjs" %}"></script> This is not a public-facing part of the site and does not need to support older browsers, so it doesn't get transpiled or compressed or any fancy build process — I just need it served as a simple static file. Except, with one difference… It turns out the server does not know about the .mjs extension and serves this file as Content-Type: text/plain, causing browsers to refuse to run that code. Ideally/eventually the IT staff running the server can hopefully add the right MIME type but until then I'm looking for an easy workaround. The most obvious workaround would be to rename the file with a .js extension instead, but that introduces a headache on the development side as the linter is set up differently for .js files vs. .mjs files and will get upset with the code if it has a .js extension. Is there a way to tell the django.contrib.staticfiles app to rename the "as-served" extension to .js while keeping the "in-repo" extension as .mjs? The idea being that I could keep editing the file as a … -
How do I get cryptocurrency prices and make some calculations and post it in a list with Django?
I'm newby with Django and I have to deliver some homework. So I want to create a super simple web page that a user can come and write what cryptocurrency coin and how much of it he/she has bought and submits it. On the next page, there will be some posts that show that info again, cryptocurrencies price, and the website does some calculations that I determine and posts it(eg. 10% lower than buying price)...at last there will be a list of purchases that the user has submitted. I have stocked in this problem for weeks now, can you please guide me through it or write its code so I can study it? -
Django - How to trigger views function with html button action
I have another NoReverseMatch that I don't understand.+ In my eyes, what should be happening is: 1. User presses button to submit form <button type="submit" action="{% url 'APP_NAME:image_gen' %}">Run</button> 2. The request passes through my URL pattern, which triggers the views function. path('image_gen/', views.image_gen, name='image_gen'), 3. The action sends a request to the views function, which generates an image. def image_gen(request): save_image(path) return render(request, 'APP_NAME/page.html', {'title': 'page'}) There's a lot less going on here than in my actual site, but it works in the same way. Why isn't it working? -
Django Window functions
Question How do I calculate the delta of a column between two consecutive rows in my database using the Django ORM? Background I have the following model: class Foobar(models.Model): foo = models.IntegerField() I want to calculate the delta between foo for each row in the database. I found Django's support for Window functions and the Lag() function. With those in hand, I tried something like this: Foobar.objects.annotate(delta=Window(expression=F('foo') - Lag('foo'))) which gives the following error: Traceback (most recent call last): File "/usr/lib/python3.8/code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> File "/home/llund/.cache/pypoetry/virtualenvs/scraper-2Ye6bxs0-py3.8/lib/python3.8/site-packages/django/db/models/expressions.py", line 1275, in __init__ raise ValueError( ValueError: Expression 'CombinedExpression' isn't compatible with OVER clauses. So to simplify, I just tried to annotate each row with the value from the previous row: fs = Foobar.objects.annotate(prev=Window(expression=Lag('foo')) for f in fs: print(model_to_dict(f)) The resulting dicts in my print() statement don't have 'prev', though. What am I missing? What is the correct way to use Lag() to calculate the delta between each row? -
logging updates to fields of djagno model in a jsonfield
I have been using logging the updates to any field of a django model with a jsonfield. class User(models.Model): phone_number = models.CharField(max_length=15) email_field = models.TextField() updates_log = models.JSONField(default=list) def save_phone_update_log(self, old_phone, new_phone): self.updates_log.update({"old_phone":old_phone,"new_phone":new_phone, "updated_at":datetime.datetime.now()}) self.save(updated_fields=["updates_log"]) Now I want to do it for all the fields , what could be an optimized implementation? -
Queries related to Google cloud storage and Aws bucket for file storage
there.I am moving forward to use google cloud services to store Django media files. But one thing that stops me is about the Google and Amazon free tier. I had read the google cloud docs but I am confuse about many things. For free tiers, New customers also get $300 in free credits to run, test, and deploy workloads. What I want to know is if they are gonna automatically charge me for using the cloud-storage after 3 months of trial is over because I am gonna put my bank account. This case is same on Aws bucket which allows to store mediafiles for 1 year after then what's gonna happen. Are they auto gonna charge me? -
Download file from internet into server (django)
How to download a file from internet into server. I wanted to download a file from internet to my server and from server I would like to upload it to youtube or something else. Every thing should be done on server. -
Django return home page in get absolute url
My urls urlpatterns = [ path('', views.home, name='blog-home'), path('about/', views.about, name='blog-about'), path("post/new/", PostCreateView.as_view(), name="post-create"), ] Once I do a post my site crashes since I need to specify a get_absolute_url. I just want to return to the home page but trying redirect("") fails with error NoReverseMatch at /post/new/ Reverse for '' not found. '' is not a valid view function or pattern name. How can I return to the homepage ? -
Django one custom model field to two db columns
I would like to create a custom field that receives a datetime string and store data in two db columns. I am reading django doc but not getting how to do it with more than one db column. It is a legacy db, so I can not change db tables layout. I have this model right now. class MyModel(models.Model): mixing_datetime = models.DateTimeField() mixing_datetime_utc_offset_seconds = models.IntegerField() I would like to create a field that lets the front end (it is an API with DRF) just send a datetime string (instead of datetime and offset separately), and let the backend do the work behind the scenes. So the idea would be: class MyModel(models.Model): mixing_datetime = models.DateTimeField() mixing_datetime_utc_offset_seconds = models.IntegerField() datetime = MyCustomDatetimeField() # This also should not be sent to db How can I achieve it? -
Django return method parameter
I was watching a tutorial on django and the guy added the following line of code, however he didnt exactly explain what it does. return '%s - %s' django the full code line is: def __str__(self): return '%s - %s' % (self.post, self.author) and i do understand it, just not that return part. Anyone mind clearing it out for me. -
Django foreign key issue with django-import-export library (IntegrityError at /import/ FOREIGN KEY constraint failed)
I'm relatively new to Django and not an advanced programmer, so please pardon my ignorance. What is working: I have a Django application that uses one main model which connects to two secondary models with foreign keys. The application can correctly create companies from template and from admin, and can correctly display the "niche" drop-down field using a foreign key to the Category model and can correctly display the images using a foreign key from the CompanyImage model. What is not working: The django-import-export library can correctly import an XLS document from front end and from admin, but ONLY if I disable the Category and CompanyImage model that are relying on foreign keys. The library does import correctly with the default user=models.ForeignKey(User) in my main Company model, but the foreign keys that connect to the secondary models are causing a foreign key error: IntegrityError at /import/ FOREIGN KEY constraint failed. What I need The XLS sheet I am importing does not import the fields that use a foreign key, so I would like to disable those fields to avoid the foreign key error. It would be nice to import a niche/category field, but I can do without. What I've tried … -
Implementing 'saved books' cart in Django
I'd like to implement a cart page, where i can save all the books that i've saved before models.py class Book(models.Model): LANGUAGES = ( ('ukr', 'Ukrainian'), ('eng', 'English'), ('rus', 'Russian'), ) image = models.ImageField(upload_to='images/', default='4.jpg') title = models.CharField(max_length=128) description = models.CharField(max_length=512) language = models.CharField(choices=LANGUAGES, default='English', max_length=100) # many books has one genre, if genre is deleted then delete related books genre = models.ForeignKey('Genre', on_delete=CASCADE) price = models.DecimalField(validators=[isBiggerThanZero], max_digits=6, decimal_places=2) slug = AutoSlugField(populate_from='title', default='') def __str__(self): return self.title class Genre(models.Model): genre = models.CharField(max_length=32, default='') def __str__(self): return self.genre I think that i need to add a new model Cart with a field saved = models.ForeignKey(Book) But it should be a list of books and idk how to implement it :( P.S.1 You should be registered if you want to save a book, so users are authorized. Skip sessions :) P.S.2 If there is a way to do that without additional modules, i'll be very grateful to you :) -
Collapse Django NavBar: On Mouse Over Show and On Mouse Out Hide
I am in need to hide a django app Blockquote navbar on mouse out and show on mouse over just like in 1. The django app is using Bootstrap4. According to W3School BootStrap4 has .collapse class 2. From a BootStrap4 perspective, I am still figuring out I could use the collapse class with hover. On the other hand, by just using css, I went through the first attempt following something like in 3. HTML <div id="nav_general"> <nav id="navbar" class="navbar navbar-inverse navbar-fixed-top" role="navigation"> </nav> </div> CSS .home #navbar { display: flex; transform: translateY(-100%); } .home #nav_general:hover #navbar { transform: translateY(0); } Within the CSS configuration the navbar was hidden forever and it is not expanding on mouse over. Could anyone point me to the reason the navbar has been hidden forever and how I could make it expand on mouse over? How could I achieve the same goal by just using BootStrap4 class=collapse?