Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can optimize query with large json data
class MyModel(models.Model): info = models.JosnField(default=dict()) # contain very large data .... .... .... .... queryset = MyModel.objects.all().order_by('id')[:200000] # it's very slow now i'm trying on compress json data -
Proper way to use bind-mount in Docker
I have a Django app. I need to dockerize it. The builtin database gets updated time to time. So I need to reflect the changes in host machine. My DockerFile is like this: FROM python:3.11-slim-buster ENV PYTHONUNBUFFERED=1 RUN pip install --upgrade pip WORKDIR /app COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt And the docker-compose file is: version: '3' services: better_half: container_name: better-half-django build: context: . command: bash -c "python manage.py runserver 0.0.0.0:8000" volumes: - .:/app env_file: - .env ports: - "8000:8000" I have used bind-mount to reflect the changes. The app runs perfectly in this configuration. But I am not sure is it the best practice or not. I want to know the best practice. Sould I use copy command in the DockerFile to copy all the project code to the app directory of the docker image? I am a newbie. Can anyone help me? Thanks in advanced. -
Django custom user model with different user models
I am creating a school management system and I want that when the admin creates users using the custom user model, the admin should create users and their profiles same time but profiles have different profile models I dont know what is it that I am doing wrong. I have a custom user model and also 3 different models for different users as below class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("email address"), unique=True) first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_student = models.BooleanField(default=False) is_parent = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = "email" REQUIRED_FIELDS = ['first_name', 'last_name'] objects = CustomUserManager() def __str__(self): return self.email The other model is class AdminHOD(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) title = models.CharField(_('Title'), max_length=4, default=MR, choices=TITLE, blank=False, null=True) bio = models.TextField() gender = models.CharField(_('Gender'), max_length=20, default=MALE, choices=GENDER, blank=False) tel = models.CharField(default='+273240000000', null = False, blank=False, max_length=15, help_text= 'Enter number with Country Code Eg. +273240000000') birthday = models.DateField(_('Birthday'), blank=False, null=False) avatar = models.ImageField(blank=True, null=True, upload_to="avatars/adminhod/") address_line_1 = models.CharField(_('Address Line 1'), max_length=125, null=True, blank=True) address_line_2 = models.CharField(_('Address Line 2'), max_length=125, null=True, blank=True) city = models.CharField(_('City'), max_length=125, null=True, blank=True) province = models.CharField(_('Province'), max_length=40, default=GAUTENG, choices=PROVINCES, blank=False, null=True) created … -
Can't connect to AWS postsql RDS
I'm trying to stand up a Dev database for a web app. I have setup the Dev database using a snapshot from the current prod server. I'm currently trying to restore the dev server's DB from a .dmp file I have via: psql --host=blahblahblahblah.us-east-1.rds.amazonaws.com --port=5432 --username=postgres --password --dbname <dbname> -f backup.sql Which gives me the error: psql: error: connection to server at "awseb-e-gjem7uperk-stack-awsebrdsdatabase-1hzzq9r4a74c.cg7ksxih0nnz.us-east-1.rds.amazonaws.com" (3.225.21.170), port 5432 failed: Operation timed out Is the server running on that host and accepting TCP/IP connections? I believe I have followed all the recommended steps to debug. Check that the host name used is the DB instance endpoint and that the port number used is correct - yes, they are correct. I copied directly from the RDS Connectivity & security page. Make sure that the DB instance's public accessibility is set to Yes: Make sure that the user connecting to the database has CONNECT access to it - (THIS ONE I'M NOT SURE ABOUT How can I do this if I can't connect?) Check that the security group assigned to the DB instance has rules to allow access - I have access to everybody. I know it's not best practice, but I'm trying to get … -
Token authentication in django . Credentials are correct whch are already saved in database but still token is not generating
Hi I'm stuck with a problem that the credentials are correct in database but still it is printing the the "else" condition that "Invalid email or password". help e out I'm stuck with this problem I've tried to setup AUTHENTICATION_BACKEND in "settings.py" file . but it is not the solution here. -
Why is the CSS not loading in the Django admin panel?
when i am on my local host the css is loading but when i am on server then it is not and i am not using any static files in my project and debug is also set to False I have tried setting debug = False and collect static files. -
django Error: webpush push failed, how to solve?
I have set everything but it seems not ok with this error when sending push. I don't have idea where it causes. ![81c764ff-4682-4fee-aa7b-a382f1e92be5]enter image description here This package is a pretty simple merge of django-pwa, and django-webpush. https://github.com/avryhof/django-pwa-webpush -
Should I Dockerize my Django app or just make a virtual env?
I developed an accounting software with django which will be only used on the local server of client's computer. My question is: How do I setup the dependencies on clients computer? Do I install all dependencies individually? Or put my project onto a virtual env and move the virtual env into the clients PC? Or should I dockerize the app? -
How do I properly setup Django translations?
When I try to py manage.py makemessages --all,I get this: File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File " \<frozen importlib.\_bootstrap\>", line 1178, in \_find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File " \<frozen importlib.\_bootstrap\>", line 690, in \_load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File \<frozen importlib.\_bootstrap\>", line 241, in _call_with_frames_removed File "C:\Users\rodne\AppData\Local\Programs\Python\Python311\Lib\site- packages\translations\apps.py", line 2, in <module> from django.utils.translation import ugettex`t_lazy as _ ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation' (C:\Users\rodne\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\translation_init_.py) Super long error message. I know Django recently changed the Translation so that you can no longer use ugettext into gettext as _ however that did nothing. -
I stucked while adding new permissions to customUsers
I'm trying to add several permissions Some of them are saving without any problem. Any errors aren't raising when I give permissions, but I'm not being able to add these perms only. Nothing else ( ('can_view_socialmedia', "Can view socialmedia"), ('can_add_socialmedia', 'Can add socialmedia'), ('can_change_socialmedia', 'Can change socialmedia'), ) to my adminstrator model but I stucked. After that I tried to add those conflict permissions by django signal. But nothing changed. I don't know why I can't add these permissions Note! I already did makemigrations and migrate commands Here you can see my code belong to giving permissions to users 👇👇👇 variables.py file employees_permissions = { 'boss': ( ('can_view_boss', 'Can view boss'), ('can_add_boss', 'Can add boss'), ('can_change_boss', 'Can change boss'), ('can_delete_boss', 'Can delete boss'), ('can_view_teacher', "Can view teacher"), ('can_add_teacher', 'Can add teacher'), ('can_change_teacher', 'Can change teacher'), # ('can_delete_teacher', 'Can delete teacher'), ('can_view_adminstrator', "Can view adminstrator"), ('can_add_adminstrator', 'Can add adminstrator'), ('can_change_adminstrator', 'Can change adminstrator'), ('can_delete_adminstrator', 'Can delete adminstrator'), ('can_view_accountant', "Can view accountant"), ('can_add_accountant', 'Can add accountant'), ('can_change_accountant', 'Can change accountant'), ('can_delete_accountant', 'Can delete accountant'), ('can_view_services', 'Can view services'), ('can_view_subjects', 'Can view subjects'), ('can_view_groups', 'Can view groups'), ), 'adminstrator': ( ('can_view_teacher', "Can view teacher"), ('can_add_teacher', 'Can add teacher'), ('can_change_teacher', 'Can change teacher'), ('can_view_student', … -
Why is one of the css styles not showing up?
I have Django-project, which include CSS and HTML files, but one of the CSS styles not showing up. I started my HTML with: {% load static %} and next: <link rel="stylesheet" href="{% static 'images/custom.css' %}"> Also in settings.py there is line: **STATIC_URL = "static/"**. HTML: <div class="container"> <div class="contact-container"> {% block content %}{% endblock %} </div> </div> CSS: .container { background : #0000; font-family : 'Istok Web', 'Nanum Myeongjo', 'Roboto', 'Roboto Mono', sans-serif; } .contact-container { background-image : url('images/aaa.jpg'); background-attachment : fixed; background-size : cover; } But it doesn't work. Style container is working correctly, but contact-container not showing up. -
(KeyError) I want to make an application using models and ModelForm structure in Django but I am getting keyerror error
I'm trying to make an electrical formula calculation app in Django. I want to enter the values in the variables in the calculation page and see them on the results page. In doing so, I want the modules to be interconnected because to reach the values. views.py class CalculationView(View): def get(self, request): transformers = Transformer.objects.all() form = CalculationForm() return render(request, 'calculation_form.html', {'form': form}) def post(self, request): form = CalculationForm(request.POST) if form.is_valid(): data = form.cleaned_data LowVoltageLineCurrent = data['Power'] / (data['HighVoltage'] * math.sqrt(3)) HighVoltageLineCurrent = data['Power'] / (data['LowVoltage'] * math.sqrt(3)) if data['LVconnection'].lower() == 'y': LowVoltagePhaseCurrent = LowVoltageLineCurrent elif data['LVconnection'].lower() == 'd': LowVoltagePhaseCurrent = LowVoltageLineCurrent / math.sqrt(3) else: LowVoltagePhaseCurrent = None if data['HVconnection'].lower() == 'y': HighVoltagePhaseCurrent = HighVoltageLineCurrent elif data['HVconnection'].lower() == 'd': HighVoltagePhaseCurrent = HighVoltageLineCurrent / math.sqrt(3) else: HighVoltagePhaseCurrent = None transformer = data['transformer'] result = Result.objects.create( Power=data['Power'], HighVoltage=data['HighVoltage'], LowVoltage=data['LowVoltage'], LowVoltageLineCurrent=LowVoltageLineCurrent, HighVoltageLineCurrent=HighVoltageLineCurrent, LVconnection=data['LVconnection'], HVconnection=data['HVconnection'], LowVoltagePhaseCurrent=LowVoltagePhaseCurrent, HighVoltagePhaseCurrent=HighVoltagePhaseCurrent, transformer=transformer, user=request.user ) return redirect('results', pk=result.pk) return render(request, 'calculation_form.html', {'form': form}) class ResultsView(View): def get(self, request, pk): result = Result.objects.get(pk=pk, user=request.user) return render(request, 'results.html', {'result': result}) models.py # models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Transformer(models.Model): LV_CHOICES = [('D', 'D'),('Y', 'Y'),] HV_CHOICES = [('D', 'D'),('Y', 'Y'),] user = models.ForeignKey(User, on_delete=models.PROTECT) … -
AttributeError: module 'quizbot.quiz.models' has no attribute '_meta'
Trying to figure out why I am getting this error and how to fix it. Trying to use django import-export library for importing files into the database. I have no idea what to try but have looked it up with nothing to give. I used the django-import -export documentation but did not help solve this issue. from django.db import models # from django.utils.translation import ugettext as _ # Create your models here. class Question(models.Model): # For Translation # title = models.CharField(_(""), max_length=255) # JUST PUT _ before any " " areas objects = None LEVEL = ( (0, ('Any')), (1, ('Beginner')), (2, ('Intermediate')), (3, ('Advanced')), (4, ('Expert')), ) # sets the amount of chars for the max length title = models.CharField(("title"), max_length=255) # This is used to make the points system points = models.SmallIntegerField("points") # This is used to make the difficulty settings difficulty = models.IntegerField(('Difficulty'), choices=LEVEL, default=0) # This question is shown be default is_active = models.BooleanField(("Is Active"), default=True) # When the question was created created_at = models.DateTimeField(("Created"), auto_now=False, auto_now_add=True) # When the question was last updated updated_at = models.DateTimeField(("Updated"), auto_now=True, auto_now_add=False) def __str__(self): return self.title class Answer(models.Model): # the first field in ForeignKey is identifying the table we … -
Upgrading Redis to 7.0.11 results in TypeError at /login/ __init__() got an unexpected keyword argument 'ssl_cert_reqs'
We use redis with django-rq to manage queues on our project. Heroku has recently forced upgrades to Redis 7.0.11 and that requires TLS. Per their docs we need to set 'ssl_cert_reqs'=None in order to make sure redis is using TLS but not looking for a cert. CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": os.environ.get('REDIS_URL'), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS": { "ssl_cert_reqs": None }, } } } Setting the above in my project's settings.py results in the following error: TypeError at /login/ __init__() got an unexpected keyword argument 'ssl_cert_reqs' Other settings like "max_connections": 5 don't cause an error. I've been searching and I haven't seen anyone else with this issue. Has anyone else run across this issue and hopefully a fix? We're using: Django==2.2.28 django-redis==5.2.0 django-rq==2.8.1 redis==4.5.5 rq==1.15.1 It also fails on another build we have: Django==3.0.14 django-redis==5.2.0 django-rq==2.8.1 redis==4.6.0 rq==1.15.1 We've tried configuring our project with multiple builds of Django, django-redis, django-rq, redis, and rq with no luck: -
How to find product name from category?
I have created three models Main Category , Category and Product Category model contains the Foreign Key of main category and product model contains the Foreign Key of main category and category model Product model contains the product details. models.py class BaseModel(models.Model): id = models.UUIDField(primary_key=True, unique=True, editable=False, default=uuid.uuid4) created_at = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class MainCategory(BaseModel): name = models.CharField(max_length=100) def __str__(self): return self.name class Category(BaseModel): main_category = models.ForeignKey( MainCategory, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100) def __str__(self): return self.main_category.name + "---" + self.name class Product(BaseModel): name = models.CharField(max_length=100) description = models.TextField() main_category = models.ForeignKey( MainCategory, on_delete=models.CASCADE, related_name='main_category') category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name='category', null=True, blank=True) slug = models.SlugField(unique=True, max_length=100, null=True, blank=True) def save(self, *args, **kwargs): self.slug = generate_slug(self.name) super(Product, self).save(*args, **kwargs) views.py def categories(request): main_categories = MainCategory.objects.all() context = { 'main_categories': main_categories } return render(request, 'allProducts.html', context) def showProductsMainCategoryWise(request): main_category = request.GET.get('main_category') if main_category == None: products = Product.objects.order_by('id') else: products = Product.objects.filter(main_category__name=main_category) main_categories = MainCategory.objects.all() context = { 'products': products, 'main_categories': main_categories } return render(request, 'allProducts.html', context) def showProductsCategoryWise(request): main_category = request.GET.get('main_category') category = request.GET.get('category') if main_category == None and category == None: products = Product.objects.order_by('id') else: products = Product.objects.all().filter( Q(main_category__name=main_category), Q(category__name=category)) main_categories = MainCategory.objects.all() categories = … -
Heroku deleted my google_application_credentials.json
I created google_application_credentials.json with heroku bash but the file was deleted, how best can I handle this ? -
Django: How to prevent a page from reloading when I click button with Ajax/Javascript? (not jQuery)
In the home.html page (index.html > login.html > home.html) i have a combobox (independent, not connected to the database but to a list), a textarea and a button. When I click the button, it prints some text in the textarea (using a condition found in views.py). Very simple. Problem: The problem is that when I click the button, the page reloads and then prints in the textarea. How can I prevent the page from loading when I click the button (without using jQuery)? Important: bearing in mind that I will have to add many comboboxes, so I would like to manage them as best as possible. Is it possible to manage the code as much as possible in the py files and not split it too much in the js file or js tag? P.S: I searched many questions on stackoverflow or various tutorials, but I couldn't solve. Apparently, even though these are similar questions, each solution is a different case with different problems and solutions. CODE home.html (index > login > home) index.html is 127.0.0.1:8000/. Home.html will only open after successful login. The address of when I view the forms is 127.0.0.1:8000/home and when I click Submit I still … -
Why am I getting "The model User is not registered" in Django
I'm following a tutorial on building a social network app with Django. I'm getting an error even though I'm following the tutorial. Error: django.contrib.admin.sites.NotRegistered: The model User is not registered admin.py from django.contrib import admin from django.contrib.auth.models import User from .models import Profile # Register your models here. class ProfileInline(admin.StackedInline): model = Profile class UserAdmin(admin.ModelAdmin): model = User fields = ["username"] inlines = [ProfileInline] #so we can edit users and profiles in one place since we're profile should be extending User. admin.site.unregister(User) admin.site.register(User, UserAdmin) The error is complaining about the line that says "admin.site.unregister(User)". models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follows = models.ManyToManyField("self", related_name="followers", symmetrical=False, blank=True) #symmetrical=False so that user can follow someone without them following back #blank=True means field can remain empty, user doesn't have to follow anyone. When I comment out the admin.site.unregister(User) line, I get the following error: django.contrib.admin.sites.AlreadyRegistered: The model User is already registered with 'auth.UserAdmin'. Which is weird to me because didn't it just say that the model User was not registered? -
Setting up Django application on Hetzner Managed Server
I have a managed server from Hetzner for my wordpress websites and now I want to deploy a django application on it without renting a cloud server from hetzner. The application runs on my computer with localhost on the browser, but on the server it only shows the index.html page with the right css styling. When I try to use e.g. buttons on the page it throws me "The requested URL was not found on this server." because the links are with "/reg/" and when the django isn't running right it can't access the other pages. I've set up a cronjob on the server "'/usr/bin/python3 /usr/home/username/public_html/testbox/manage.py'" and that seems to work fine according to the hetzner dashboard. In addition, Python and django are installed on the subdomain. Is there another thing e.g. docker or nginx that I am missing? Thanks in advance. -
How to run a telegram bot in django?
I want to run a telegram bot in django and have it run with the command "python manage.py runserver". I tried to do this with subprocess, but it gives an error and because of this there is a conflict with the launch of several bots. Is there an alternative solution? #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import subprocess import sys from subprocess import call def main(): """Run administrative tasks.""" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoProject7.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc subprocess.Popen(["python", "main.py"]) execute_from_command_line(sys.argv) if __name__ == "__main__": main() -
Stripe Portal url not secure Python
I'm working on a Django application integrated with Stripe, and I'm facing a security issue related to user subscription management through the Stripe portal. Currently, I provide a simple link for users with subscriptions to access the portal. However, I've noticed that if I copy the link from the browser tab that the view generate and paste it into a private tab in another browser, the portal loads up, allowing access to someone else's subscription details. an example of the url generated : https://billing.stripe.com/p/session/test_YWNjdF8xSGFuNG5KV3p0WnBRQUJ4LF9POHM5UWlrYlhtM0FadVZmV3NUU3hQFMrgrrgg0HK1DtM1hxe This presents a significant security concern since an unauthorized user who obtains the URL could potentially manipulate the billing information of a subscriber. so my view : def customer_portal(request): # Authenticate your user. customer_id = request.user.customer.id # Create a session. session = stripe.billing_portal.Session.create( customer=customer_id, return_url='http://127.0.0.1:8000/account/billing/', ) # Directly redirect the user to the portal. return redirect(session.url) the link : <h4><a href="{% url 'subscriptions:customerPortal' %}">Manage Billing</a></h4> the urls : path('billing/portal/', customer_portal, name='customerPortal'), I'm doing something wrong ? -
Dajngo: Pagination in search results with Class-based views
I want to paginate by keywords that I enter in the form. I use the following class def pageNotFound(request, exceprion): return HttpResponseNotFound("<h2>Page not found</h2>") def get_quotes(): top_tags = get_top_tags() context = { "top_tags": top_tags, "functional_menu": functional_menu, } return context class Main(ListView): model = Quote paginate_by = 10 template_name = "quotes/index.html" context_object_name = "quotes" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update(get_quotes()) return context class SearchedResults(ListView): model = Quote paginate_by = 10 template_name = "quotes/index.html" context_object_name = "quotes" def get_queryset(self): query = self.request.GET.get("search_query") if query: queryset = Quote.objects.filter( Q(quote__icontains=query) | Q(tags__name__icontains=query) | Q(author__fullname__icontains=query) ).distinct() else: queryset = super().get_queryset() return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context The problem is that when you go to the next page, the form field is cleared and the query takes the value None query=None. The entire pagination becomes undefined. How to save queryset when crossing pages in pagination? -
Django returns TemplateDoesNotExist for namespaced app templates which are rendered by class views but works for plain function views
I'm new to Django and have a project myproject and inside is an app, users. I can't figure out why name spacing the my templates in a subdirectory inside of a folder called templates within the users apps (so the path is myproject/users/templates/users/) does not work for class based views but it works fine for regular function views. When using a class based view I get error message Templateloader postmortem saying: django.template.loaders.app_directories.Loader: /home/me/projectmainfolder/myproject/users/templates/signup_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/me/projectmainfolder/penv/lib/python3.10/site-packages/django/contrib/admin/templates/signup_form.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/me/projectmainfolder/penv/lib/python3.10/site-packages/django/contrib/auth/templates/signup_form.html (Source does not exist) When I move the template out of the name spaced sub-directory and into templates it works fine. users/urls.py is: from django.urls import path, include from . import views app_name = "users" urlpatterns = [ path("accounts/", include("django.contrib.auth.urls")), # works fine path("accounts/test", views.testdef, name="test"), #doesn't work path("accounts/signup/user", views.UserSignupView.as_view(), name="signup_form"), ] The regular function testdef is : def testdef(request): return render(request, "users/test.html") The class view UserSignupView is: class UserSignupView(CreateView): model = CustomUser form_class =UserProfileSignupForm template_name = 'signup_form.html' def somefunction(self, **kwargs): ... Any idea how to resolve this is very appreciated. I would like to keep things name spaced according to Django's docs. I tried moving the files around and found success that way but … -
Django ORM: have model field always return a constant
I am extending Django model into a few child classes: Model –> SampleModel –> SampleModelA –> SampleModelB –> SampleModelC –> SampleModelD All child models (A,B,C,D) have field SampleType as Integer. Models A and B may have different SampleTypes (1–5), whereas for models C and D, SampleType is always the same: 1 and 2, respectively. I must preserve SampleType field in all child models for polymorphism purposes, but need models C and D always return 1 and 2, respectively for that field in any record, no matter what query. What is the simplest way to do that? (preferably without taking up disk space for the field) -
How to know if a user is previously loged in in django but with firebase database
how do we know this in HTML and python both? When we open the django website it should show different things for logged user. please give some examples with a code with comments but dont use django authtentcation system ..