Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can I do django custom authorization? I need admin auth by username and password and users by only phone number
How can I realize this code? admin use only admin panel for authorization users doesn't use admin panel therefore they use only app for authorization with OTP phonenumber. from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import gettext as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifier for authentication instead of usernames. """ # oddiy userlar yaratish uchun def create_user(self, email, password, **extra_fields): if not email: raise ValueError(_('Users must have an email address')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user # supper user yaratish uchun def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) I have manager class and I looked similar code. from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model class EmailBackend(ModelBackend): def authenticate(self, request, email=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=email) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user def get_user(self, user_id): UserModel = get_user_model() try: return UserModel.objects.get(pk=user_id) except UserModel.DoesNotExist: return None I looked some video in youtube I didn't find. -
Django: collectstatic is not collecting static files
I found a github proyect. Copied it locally, but running collecstatic does not copy files to staticfiles folder. Why? If I do the full path search: python manage.py findstatic D:\web_proyects\imprenta_gallito\static\css\home.css I get error: django.core.exceptions.SuspiciousFileOperation: The joined path (D:\web_proyects\imprenta_gallito\static\css\home.css) is located outside of the base path component (D:\virtual_envs\imprenta_gallito\Lib\site-packages\django\contrib\admin\static) settings.py: import os import os import secrets from pathlib import Path import dj_database_url from decouple import config # SITE_ROOT = root() # 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/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get( "SECRET_KEY", default=secrets.token_urlsafe(nbytes=64), ) #DEBUG = config('DEBUG', default=False, cast=bool) # The `DYNO` env var is set on Heroku CI, but it's not a real Heroku app, so we have to # also explicitly exclude CI: # https://devcenter.heroku.com/articles/heroku-ci#immutable-environment-variables IS_HEROKU_APP = "DYNO" in os.environ and not "CI" in os.environ # SECURITY WARNING: don't run with debug turned on in production! if not IS_HEROKU_APP: DEBUG = True # On Heroku, it's safe to use a wildcard for `ALLOWED_HOSTS``, since the Heroku router performs # validation of the Host header in the incoming HTTP request. On other platforms … -
How to fix Django regualr expression Problem
Django Rest Framework after User registration sends out an Email for the new User to verify the EMail adress. The link attached is like https://my_domain.com/api/verify_email/?token=ddfddjrf....fddkfjdjh my api.urls.py file looks like: api.urls.py from django.urls import re_path from . import views urlpatterns = [ re_path(r'^verify_email/(?P<token>[\w.-]+)/',views.verify_email, name="verify_email"), [ and in project urls.py ... path('api/', include("api.urls")), ... When I try to run that link I get: Page not found (404) The current path api/verify_email/, didn't match any of these. I can see a URL pattern from the URL.conf: Django tried these URL patterns,in this order. ... api/ ^verify_email/(?P[\w.-]+)/ [name='verify_email'] ... I hope somebody can help because I can't find a solution somewhere .... And I tried several things to fix it. But without any success. Thank's a lot. Greetings RR -
Django filter in other model without foreign key
I have two different models: class AggUii(Model): year = models.IntegerField(blank=True, null=True) month = models.CharField(max_length=2, blank=True, null=True) country = models.CharField(max_length=7, blank=True, null=True) service = models.CharField(max_length=16, blank=True, null=True) doc_id = models.CharField(max_length=100, blank=True, null=True) counts = models.IntegerField(blank=True, null=True) data_type = models.CharField(max_length=200, blank=True, null=True) section_type = models.CharField(max_length=200, blank=True, null=True) yop = models.CharField(db_column='YOP', max_length=4, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'agg_uii' class HierarchieIndexDocid(Model): ancestor = models.CharField(max_length=255) descendant_docid = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'hierarchie_index_docid' As you can see, these tables aren't connected by a Foreign Key. Is there any way, I can rebuild this MySQL statement in Django ORM? The meta_id is passed as a parameter. SELECT agg_uii.year, SUM(agg_uii.counts) FROM agg_uii,hierarchie_index_doc_id WHERE (agg_uii.doc_id=hierarchie_index_doc_id.descendant_docid and hierarchie_index_docid.ancestor="meta_id") GROUP BY agg_uii.year; Thank you! -
Getting errors in installing redux-devtools-extension in react project
I am getting errors while installing redux-devtools-extension uisng npm command in react-redux-django project. -
Prefetch related n+1 problem with django. How can i solve it?
I have three Models named 'Route', 'Place', 'PlaceImage'. class Route(models.Model): place = models.ForeignKey(Place, on_delete=models.CASCADE, null=False, blank=False) day = models.IntegerField(null=False, blank=False) order = models.IntegerField(null=False, blank=False) class Place(models.Model): name = models.CharField(null=False, blank=False) class PlaceImage(models.Model): place = models.ForeignKey(Place, on_delete=models.CASCADE, null=False, blank=False) image = models.ImageField(null=False, blank=False) I want to display routes and place image based on Route Model. Original code was... # views.py response_obj = (Route.objects.filter(day=day).prefetch_related("place__image").order_by('order')) serializer = RouteSerializer(response_obj, many=True, context={'request': request}) # Part of RouteSerializer in serializers.py placeImage = serializers.SerializerMethodField("get_placeImage_prefetch_related") def get_placeImage_prefetch_related(self, group): request = self.context.get('request') image = group.place.image return request.build_absolute_uri(image.first().image.url) And I have N+1 Query at getting place image like this (0.000) SELECT "PLACE_IMAGE"."id", "PLACE_IMAGE"."place_id", "PLACE_IMAGE"."image", "PLACE_IMAGE"."created_at" FROM "PLACE_IMAGE" WHERE "PLACE_IMAGE"."place_id" = 80 ORDER BY "PLACE_IMAGE"."id" ASC LIMIT 1; args=(80,); alias=default (0.000) SELECT "PLACE_IMAGE"."id", "PLACE_IMAGE"."place_id", "PLACE_IMAGE"."image", "PLACE_IMAGE"."created_at" FROM "PLACE_IMAGE" WHERE "PLACE_IMAGE"."place_id" = 79 ORDER BY "PLACE_IMAGE"."id" ASC LIMIT 1; args=(79,); alias=default (0.000) SELECT "PLACE_IMAGE"."id", "PLACE_IMAGE"."place_id", "PLACE_IMAGE"."image", "PLACE_IMAGE"."created_at" FROM "PLACE_IMAGE" WHERE "PLACE_IMAGE"."place_id" = 78 ORDER BY "PLACE_IMAGE"."id" ASC LIMIT 1; args=(78,); alias=default How can I solve this n+1 problem? In views.py, I tried prefetch_related(Prefetch('place__image', queryset=PlaceImage.objects.all().only('image'))) but error occurred. AttributeError: 'PlaceImage' object has no attribute '_add_hints' -
data transfer into sql
from django.shortcuts import render import json from .models import MyModel import os def display(request): json_file_path = os.path.join(os.path.dirname(__file__), '..', '..', './jsondata.json') try: with open(json_file_path, 'r') as f: data = json.load(f) for item in data: my_model_instance = MyModel(end_year=item['end_year'], intensity=item['intensity'], sector=item['sector'], topic=item['topic'], insight=item['insight'], url=item['url'], region=item['region'], start_year=item['start_year'], impact=item['impact'], added=item['added'], published=item['published'], country=item['country'], relevance=item['relevance'], pestle=item['pestle'], source=item['source'], title=item['title'], likelihood=item['likelihood']) my_model_instance.save() except FileNotFoundError: data = [] template_name = 'display' return render(request, template_name, {'data': data}) i am trying to transfer the data from json into sql using django -
Django join on a field that isn't the ForeignKey
I'm new to Django but I'm making a game where one of the elements is that players vote for each other. Here are the models I've set up (relevant fields only) #models.py class Game(models.Model): gamecode = ShortUUIDField(length=4, max_length=4, unique=True) phasenumber = models.IntegerField(default=1) isActive = models.BooleanField(default=True) class Player(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) isPlaying = models.BooleanField(default=True) class PlayerVote(models.Model): byplayer = models.ForeignKey(Player, on_delete=models.CASCADE) forplayer = models.ForeignKey(Player, on_delete=models.CASCADE, related_name="voteforplayer") gamephasenumber = models.IntegerField() timestamp = models.DateTimeField(auto_now_add=True) When a user joins a game, they get an entry in the "Player" model and when they cast a vote for another player, an entry is added to the "PlayerVote" model showing which player voted (byplayer) and who they voted for (forplayer). What I'd like to do is create a QuerySet which contains each player and how many votes they got. I have tried using annotate which seems to be able to give me a count of the number of votes, but it defaults to joining on the byplayer field, so I end up with the number of votes each player cast, rather than the number of votes each player received. In SQL I would just do a join on Player.pk = PlayerVote.forplayer.pk, is it … -
integrate google oauth for gmail login/ signup system
I am designing an application to be accessible on both app and web. I want my customers to login/ signup via gmail as well. for this I need to integrate google auth system for social logins. My end goal is to establish a connection with google and extract user data such as name, profile_pic, dob, sub from that. I followed the below approach for my app and it worked. from google.oauth2 import id_token from google.auth.transport import requests id_info = id_token.verify_oauth2_token(token, requests.Request(), google_client_id) print(id_info['sub'], id_info['email']) this works fine for app and gives me all user data. Now, when i try to do this for web, from all the ways i could find, I tried with google API calls as below in web, we get code in callback API request from google as a request param. We have to fetch an auth token from google in exchange of this code and then use that token to fetch user data. (That's how it works, as per my understanding) data = { 'code': code, 'client_id': my_client_id, 'client_secret': my_client_secret_key, 'redirect_uri': redirect_uri, 'grant_type': 'authorization_code' } response = requests.post('https://oauth2.googleapis.com/token', data=data) if not response.ok: logger.info('Could not get access token from Google.') return access_token = response.json()['access_token'] response2 = requests.get( … -
Django Taggable tags not working, empty page
I apologize in advance if I write something unclear, I am new to both django and stackoverflow. I'm trying to implement a blog site, with posts and all that. An important part of the site is tag search, which I'm trying to implement via Taggit. However, when I click on the tag url link, I always get a blank page. I also have a pagination system that divides the blog into different pages. urlpatterns = [ path('', views.PostList.as_view(), name="home"), path(r'^$', views.post_list, name='post_list'), path(r'^tag/(?P<tag_slug>[-\w]+)/$', views.post_list, name='post_list_by_tag'), ] class Post(models.Model): title = models.CharField(max_length = 250, unique = True) slug = models.CharField(max_length = 200, unique = True) type = models.CharField(max_length=100, choices=Type_CHOICES) section = models.CharField(max_length=100, choices=Section_CHOICES) tags = TaggableManager() from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from .models import Post from django.views import generic from taggit.models import Tag from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def post_list(request, tag_slug=None): object_list = Post.objects.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) paginator = Paginator(object_list, 3) # 3 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out … -
Serving a Dash dashboard from Django hosted app to an external webpage
I am currently hosting my dashboard on a url like the following: https://xxx.herokuapp.com/dashboard/ExternalDashboard using Django and serving an HTML page with the following contents: <!DOCTYPE html> <html> <head> <title>External Dashboard</title> <style> body, html { height: 100%; margin: 0; padding: 0; } #plotly-app-container { height: 100%; } </style> </head> <body> <div id="plotly-app-container"> {% load plotly_dash %} {% plotly_app name="ExternalDashboard" ratio=1 %} </div> </body> </html> This works very well and my dash dashboard is interactable and everything is good. Now I want to serve this Dashboard on another website say https://YYY.herokuapp.com/FetchDashBoard, here I also want to send back some information such as an authentication token which i will use on my dashboard to check which plots to display. From the official dash documentation (https://dash.plotly.com/integrating-dash) on integrating dash I gather zero useful information. Im not a frontend developer and simply creating an html page on https://YYY.herokuapp.com/FetchDashBoard with the following contents just yields a blank page: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Display Dashboard</title> </head> <body> <div id="dash-app"></div> <script> var setter = window.dash_embedded_component.renderDash( { url_base_pathname: "https://xxx.herokuapp.com/dashboard/ExternalDashboard"}, 'dash-app', sharedData ); </script> </body> </html> Bear in mind that im not sending any data to begin with, I just want to see … -
how to create user profile and save user data from data base?
I want to create a user profile, I will add that user to my own template, when a user registers, it will be registered. His profile name, username, email address will be added. As soon as he adds the post, all the posts will be added to his profile history. How to make this thing in django? I want to create a user profile, I will add that user to my own template, when a user registers, it will be registered. His profile name, username, email address will be added. As soon as he adds the post, all the posts will be added to his profile history. How to make this thing with django? -
How to allow null value on serializer when the field in the model is required?
Given the following payload, models.py, and serializers.py in Django (DRF): payload { "created_by": 6, "brand": 1, "foo_details": [ { "quantity": 123, "price_estimation": 456 }, { "quantity": 789, "price_estimation": 1011 } ] } models.py class Foo(models.Model): created_by = models.ForeignKey(CustomUser, on_delete=models.PROTECT) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True) # OTHER FIELDS HERE class FooChild(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name="foo_details") quantity = models.PositiveIntegerField(default=0) price_estimation = models.PositiveIntegerField(default=0) # OTHER FIELDS HERE serializers.py class FooChildSerializer(serializers.ModelSerializer): # foo = serializers.PrimaryKeyRelatedField(read_only=True, required=False) -> LINE 2 class Meta: model = FooChild fields = ["id", "foo", "quantity", "price_estimation", ...] class FooSerializer(serializers.ModelSerializer): # foo_details = FooChildSerializer(many=True) -> LINE 9 # foo_details = serializers.DictField(child=serializers.CharField(), many=True) -> LINE 10 class Meta: model = Foo fields = ["id", "created_by", "brand", "foo_details", ...] def create(self, validated_data): # I want to save the payload to `Foo` and `FooChild` inside this function at the same time, below is my unsuccessful attempt # print(validated_data) # validated_data.pop("foo_details") # foo = Foo.objects.create(**validated_data) -> LINE 21 # foo_child = FooChild.objects.create(foo=foo) # return foo The problem I'm having right now is, when I tried to POST the payload, DRF complained that foo field in FooChild is required, which is understandable, the problem is, the id of the Foo exists only after I created … -
what is the different between migrate and makemigrations?
What is the difference between the migrate and makemigrations ? I want to know different between both and why we have to both in django. after changing model.py file and that affect database then we have to run this two command py manage.py makemigrations user py manage.py migrate -
How to combine queries in django that span foreign key relationships?
Suppose I have two models: class Team(models.Model): name = models.CharField() class Player(models.Model): name = models.CharField() team = models.ForeignKey(Team) Now, I want to filter Player objects through their name as well as the name of their team. So for example if user input is aa, I want all Players who have aa in their name OR in their team's name. So far I have tried to use two queries like this: players = Player.objects.filter( name__icontains=request.GET.get("q", ""), # ...other filters ) more = Player.objects.filter( team__name__icontains=request.GET.get("q", ""), # ...other filters ) players = players.union(more) This gives the results, but it has its own problems: i) It gives duplicate results in cases where the search query matches both, the player name and the team name (.union method does not support .distinct) ii) It searches the database twice which can be an expensive operation. So I would like it to run in just one query. iii) It is not DRY. You have to repeat the other filters twice. So is there a way to get the results accurately? -
Django multi tenant help required
I am currently building saas app using django_multitenant package and i read and followed all the detail given in the docs and while using Django admin panel everything is fine. If we create any object from panel the object automatically get tenant assigned to it but while using an API and It kept asking the tenant id how to solve it. # setting MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "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", "apps.api_auth.middlewares.MultitenantMiddleware", # 'django_multitenant.middlewares.MultitenantMiddleware', ] # custom middleware class MultitenantMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): jwt_auth = JWTAuthentication() # Authenticate the user auth_result = jwt_auth.authenticate(request) if auth_result is not None: user, _ = auth_result if user and not user.is_anonymous: tenant = Institute.objects.filter(user=user).first() set_current_tenant(tenant) response = self.get_response(request) unset_current_tenant() return response # models class Institute(TenantModel): name = models.CharField(max_length=100) class TenantMeta: tenant_field_name = "id" class CustomUserManager(TenantManagerMixin, UserManager): pass class User(TenantModel, AbstractUser): institute = TenantForeignKey( "tenant.institute", on_delete=models.CASCADE, blank=True, null=True ) objects = CustomUserManager() class TenantMeta: tenant_field_name = "institute_id" class SessionYear(TenantModel): start_year = models.DateField() end_year = models.DateField() is_deleted = models.BooleanField(default=False) is_active = models.BooleanField(default=False) institute = TenantForeignKey("tenant.institute", on_delete=models.CASCADE) class TenantMeta: tenant_field_name = "institute_id" # API view from django_multitenant import views from rest_framework import viewsets, permissions from apps.tenant import tenant_func … -
nginx + uwsgi upstream prematurely closed connection while reading response header from upstream
I'm using uwsgi and nginx to deploy a Django project which using VUE3 and Django. And nginx is in a docker container.I have tried several conf combinations, only the follow one works. location /cseq/ { root /usr/share/nginx/html; #try_files $uri $uri/ /cseq/index.html; index index.html index.htm; } location /cseq/api/ { proxy_pass http://xxx:8001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; uwsgi_buffer_size 16k; uwsgi_busy_buffers_size 24k; } [uwsgi] http=:8001 chdir=/root/project/cseq/cseq-backend module=cseq.wsgi:application master=true vacuum=true max-requests=5000 workers= 4 threads = 2 buffer-size = 65536 daemonize=/root/project/cseq/cseq-backend/uwsgi.log My question is: in uwsgi conf, using http works, but change http to socket, nginx has a error:upstream prematurely closed connection while reading response header from upstream. when I change both conf to the follow location /cseq/ { root /usr/share/nginx/html; #try_files $uri $uri/ /cseq/index.html; index index.html index.htm; } location /cseq/api/ { include uwsgi_params; uwsgi_pass 127.0.0.1:8001; } [uwsgi] socket=:8001 chdir=/root/project/cseq/cseq-backend module=cseq.wsgi:application master=true vacuum=true max-requests=5000 workers= 4 threads = 2 buffer-size = 65536 daemonize=/root/project/cseq/cseq-backend/uwsgi.log the error becomes failed (111: Connection refused) while connecting to upstream, in both errors, uwsgi didn't has any connection. Any ideas or solutions? I want to use nginx and uwsgi to deploy a Django project -
Case insensative search/filter in django
at my Search class of django project I try to get products query from db but it case sensative not matter what i tried, i still can not enhance my search query maybe not that way to solution, i will find a possible way to get it right but one and biggest broblet that i use Sqlite3 wher is method (name__icontains=search_query) not valid, i mean valid but does not work part of Search class: def get_queryset(self): search_query = self.request.GET.get('q') print(f"start q {search_query}") print(Product.objects.filter(name__icontains=search_query)) print(repr(search_query),"----------") if search_query: # Filter products where label contains the search query (case-insensitive) return Product.objects.filter(name__icontains=search_query) else: return Product.objects.none() -
Why is Django prefetch_related resulting in 100s of extra SQL queries?
My relationships are as follows: A Portfolio has a many 2 many relationship to LoanTape through PortfolioLoanTapes A Quote has many LoanTapes A Quote has many Documents I am trying to query a Portfolio and all its related starred documents in a GET portfolio API call in DRF ModelViewSet. models.py class Portfolio(models.Model): loan_tapes = models.ManyToManyField("LoanTape", through="PortfolioLoanTapes") class PortfolioLoanTapes(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete=models.PROTECT) loan_tape = models.ForeignKey(LoanTape, on_delete=models.PROTECT) class LoanTape(models.Model): portfolios = models.ManyToManyField("Portfolio", through="PortfolioLoanTapes") quote = models.ForeignKey("Quote", on_delete=models.PROTECT, blank=False, null=False, related_name="loan_tapes") class Quote(models.Model): ... class Document(models.Model): quote = models.ForeignKey(Quote, on_delete=models.PROTECT, related_name="documents") is_starred = models.BooleanField(default=False) view.py def get_queryset(self): starred_documents_qs = Document.objects.filter(is_starred=True) quotes_prefetch = Prefetch('quote__documents', queryset=starred_documents_qs, to_attr='starred_documents') loan_tapes_prefetch = Prefetch('portfolioloantapes_set__loan_tape', queryset=LoanTape.objects.prefetch_related(quotes_prefetch)) qs = Portfolio.objects.prefetch_related(loan_tapes_prefetch).filter(deleted__isnull=True) return qs serializer.py class PortfolioDetailSerializer(serializers.ModelSerializer): loan_tapes = PortfolioLoanTapeSerializer(many=True, read_only=True, source="portfolioloantapes_set") class PortfolioLoanTapeSerializer(serializers.ModelSerializer): def to_representation(self, instance): ret = super().to_representation(instance) ret.update(LoanTapeSerializer(instance.loan_tape).data) return ret class LoanTapeSerializer(serializers.ModelSerializer): image_url = serializers.SerializerMethodField() def get_image_url(self, instance): if starred_docs := getattr(instance.quote, 'starred_documents', []): return starred_docs[0].url test.py (missing some setup objects) def test_retrieve_query_count(self): with self.assertNumQueries(4): response = self.client.get(f"/api/v1/portfolios/{portfolio.id}/", **self.headers) self.assertEqual(response.status_code, 200) When asserting the number of queries in the test above, Django is making 224 DB calls!! Are my prefetch objects not setup correctly? Is there a more efficient path in the prefetch? I'm quite lost and can't seem … -
Django crispy form how to format while typing
super_amount = models.DecimalField( max_digits=20, decimal_places=2, default=Decimal(0), ) {{ form.super_amount|as_crispy_field }} I have this field in my form but I want this field to be formatted with commas while typing in browser. So if I write 123456789, it will be shown like this everytime I write a number: 1 -> 12 -> 123 -> 1,234 -> 12,345 -> ... -> 123,456,789 https://stackoverflow.com/a/39279790/14253522 I tried to use this but after 6 digit, field clears itself. I tried to work around this problem but wasn't able to solve it. -
NGINX and Django not in debug serving some static files and some no
I am experiencing some weird behaviour after switching off DEBUG on Django, behind NGINX reverse proxy. I am testing it on a Armbian Linux with Python 3.7.3. Django project has the manage.py inside the folder folder configuration is - /var/webserver/backend - manage.py - backend - settings.py - static - img (contains collected plus my logo and favicon) - admin (the collected admin files) The NGINX configuration is as following (the static part, the rest is a reverse proxy with a self signed certificate): location /static { autoindex on; autoindex_exact_size off; alias /var/webserver/backend/static; } The settings.py static part is as following, staticfiles app is in the APPS: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' I run the manage.py command while in the /var/webserver/backend directory, nginx is ran as service. I think I have tried all combinations of "slashes" both inside the NGINX configuration and settings.py (before, after, both, none) This configuration is the nearest to work, the situation is the following: The logo.png and favicon.ico inside the static/img folder are displayed correctly all the css, js or others are not loaded (page is completely without style) There are no 404 in the logs (either Django or NGINX access.log shows 200). … -
Django apps have circular dependency, causes foreign key models not to migrate
I have two django apps that have foreign keys to each other An api app and another app called blog Here is my models.py for the blog app class Post(models.Model): uuid = models.UUIDField(default=uuid.uuid4, primary_key=False, unique=True) title = models.CharField(max_length=600) authors = models.ManyToManyField('Author', related_name='authors') tags = models.ManyToManyField('Tag', related_name='tags') date_published = models.DateField(auto_now_add=True) # store table of contents as JSON table_of_contents = models.TextField(default=dict) # s3 link to thumbnail thumbnail = models.URLField(max_length=300) # each post belongs to a blog blog = models.ForeignKey('api.Blog', on_delete=models.CASCADE, default=0) slug = models.SlugField(max_length=100, default='') # store markdown as text content = models.TextField(default='') # link to post url = models.URLField(default='') # for json serialization def as_dict(self): return { "title": self.title, "slug": self.slug, "authors": [ author.as_dict() for author in self.authors.all() ], "tags": [ tag.as_dict() for tag in self.tags.all() ], "date_published": "01/01/2001", "table_of_contents": self.table_of_contents, "thumbnail": self.thumbnail, "id": str(self.uuid), } def __str___(self): return self.title class Author(models.Model): name = models.CharField(max_length=100) blog = models.ForeignKey('api.Blog', on_delete=models.CASCADE, default=0) def as_dict(self): return { "name": self.name, "profile": self.name } def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=50) blog = models.ForeignKey('api.Blog', on_delete=models.CASCADE, default=0) def as_dict(self): return { "name": self.name } def __str__(self): return self.name And my models.py for my "api" app class Blog(models.Model): # Foreign key to the associated tenant in … -
Django objects.get not working when using the request data
I couldn't understand why this code isn't working: I'm currently using Django as cms, and nextjs as fronted: while I was testing the get request i had a lot of trouble to make the Member.objects.get(firstname='Alessia') working and also filter doesn't work at all. from django.http import HttpResponse from django.http import JsonResponse from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.decorators import api_view from simulazione.models import * from simulazione.api.serializers import * @api_view(['GET']) def get_data(request): nome = request.GET.get('name', None) try: dear = Member.objects.get(firstname=nome) serializer = MemberSerializer(dear) data = {'hello': 'hello2'} return JsonResponse(serializer.data) except: print("Server error") Everytime I run this, i get this error: AssertionError at /simulazione/api/get_data/ Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> -
Django view caching: how to set expire at time?
I would like to cache some view until end of month. e.g. @cache_page_expire_at_end_of_month def some_view(request): ... I found this old question Django per-view caching: set expiry time rather than cache timeout? But I can't get it to work. -
Difficulty Establishing Secure Connection Between Web Server and MQTT Server
I'm currently working on a project for monitoring robots, and I've developed a web platform using Django and Vue for data acquisition and visualization. At present, I'm utilizing an MQTT server to transmit all my data. However, I've encountered an issue while trying to configure communication between my web page, which has an SSL certificate generated by Certbot, and the MQTT server implemented on a Raspberry Pi 4. I've attempted to generate an SSL certificate for MQTT using OpenSSL, but I've been unsuccessful in establishing a connection between the web server and the MQTT server. It seems that the web page doesn't allow unencrypted connections with the MQTT server. I'm employing the WebSocket protocol for this connection. Additionally, I'm unable to use Certbot to generate an SSL certificate for the Raspberry Pi, as I don't have my own domain for the Raspberry Pi's IP address. Does anyone have any ideas about what might be happening or any alternative methods for securely establishing this connection? Thanks in advance for your assistance. When attempting to establish the connection between my web server and the MQTT server, I used an SSL certificate generated by Certbot on the web server and tried to generate …