Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to extend templates from different app Django with Jinja?
I found that I have many Django projects and I want to extract all common features into an app. When working with extract the Django template I got this problem. Here is the app structure myproject/ app1/ jinja2/ app1/ app1.html app2/ jinja2/ app2/ app2.html From app2.html I want to extend app1.html What I try to do: {% extend app1/app1.html %} I get jinja2.exceptions.TemplateNotFound app1/app1.html Jinja2 setting in settings.py TEMPLATES = [ { 'BACKEND':'django.template.backends.jinja2.Jinja2', 'DIRS': [ PROJECT_DIR / 'jinjatemplates' ], 'APP_DIRS': True, }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I got similar question here then I just do extent app1.html from app2.html but it got TemplateNotFound error django include template from another app Got some error and want to find a way to fix -
How can I serve multiple Django applications with Nginx and Gunicorn using multiple domains
I'm trying to host an extra website on my digital ocean droplet. I'm using Ubuntu 20.04.6 LTS. The original website is working well. I'm following this tutorial on how to Serve multiple Django applications with Nginx and Gunicorn using multiple domains (https://www.youtube.com/watch?v=koo3bF2EPqk ). After setting up everything im getting the error " DisallowedHost at / Invalid HTTP_HOST header: 'www.example.co.ke. You may need to add 'www.example.co.ke' to ALLOWED_HOSTS" Below is my /etc/nginx/sites-available/example server { listen 80; server_name subdomain.example.co.ke www.subdomain.example.co.ke; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/xxx/pyapps/xxx; } location /media/ { root /home/xxx/pyapps/xxx; } location / { include proxy_params; proxy_pass http://unix:/run/xxx.sock; } } On Django app I have added both subdomain.example.co.ke www.subdomain.example.co.ke in allowed hosts. Please note the other working site is not using example.co.ke. Both domain names point to the same droplet IP. Thank you, any help will be appreciated. I tried restarting nginix and Gunicorn but im still getting the same bug. Also, tried adding the Ip address in allowed hosting but its not working too. -
Where to put multithread-Tasks code in Django
If I need to run multithread (or multiprocessing) tasks using threading (or multiprocessing) module, where should I put threading-related code? I will need a TaskManager of some sort (which will handle tasks creation and control), Task of some sort (which will not be persistent), initialization of them, and other things. Although I will need some thread-related functions, which are not OOP, but will be used in Thread class and so on. TaskManager is not exactly Model. It's Controller of some sort. This code is running in sub-thread, this is clearly not a View. Task is model, but web-unrelated and not database-saved. And it is although running in (another) subthread. Multithreading functions and so on - are not MVC or OOP at all. Initialization code of TaskManager - where this should be? -
Why Date is not displayed in Django Admin Panel
Model date =models.DateField(auto_now_add=True) in my django model.py file and everything is working fine but the problem is it won't show data/time in django admin panel. Here Date is created as an auto_now_add=True but it not showing in an Admin Panel -
where should i add the django rest framework token in http. header or body?
Im a new in django rest framework. im developing a user registration, login and logout page for first. in many of the tutorial i found that, they add the token in the body. but in the drf documentation , they it shoud be in the body. im so confuced. anyone help me with the logic i just created a login page. the view is testing the username and the password then return user information and the token. but how do i return the token. here is my login view. can u review my code: # user login class user_login(APIView): serializer_class = login_serializer def post(self, request, format = None): print(request.data) """ serialing the data and validating it, any exception found is_valied() the functionn automatically return respond with the error message as a dictionery """ # serializing data serializer = self.serializer_class(data=request.data) # validating the data serializer.is_valid(raise_exception=True) # authenticate the user email = serializer.validated_data['email'] password = serializer.validated_data['password'] user = authenticate(request, email = email, password = password) # if user is authenticated create tocken if user: token, created = Token.objects.get_or_create(user = user) print(request.user) print(request.auth) return Response({"status":200, "email": email, "token": token.key}, status=200) # else return 401 unautherized message else: return Response({"status":401,"message":"unauthorized"}, status=401) ``` -
How to update seaborn data when I use django?
I use django and create web page. Then I click button seaborn do not update data, only add data. Scatters are added to the plot as many times as I click the button. However I want reset existing data and show new plot by new data. Django code: def index(request): if request.method == "GET": form_index = ForecastField(request.GET) if form_index.is_valid(): adress_f = form_index.cleaned_data['flat_Ad'] newdf_pl = pd.read_csv(r'newdf.csv') newdf_pl = newdf_pl.loc[newdf_pl['Address_N'] == adress_f] sns.scatterplot(data=newdf_pl, x='Area', y='Price_G') fig = plt.gcf() buff = BytesIO() fig.savefig(buff, format='png') buff.seek(0) string = base64.b64encode(buff.read()) uri_F = urllib.parse.quote(string) context = {'Index_f': ForecastField(), 'pngg_F': uri_F} html_index = "MyHome/index.html" return render(request, html_index, context) HTML code: <div class='container'> <img src='data:image/png;base64,{{ pngg_F }}' alt="image"/> </div> -
I have problem with git and django migrate
I use git in django for my project and my database is postgres. When I make a change in the file and make migrations and then migrate, it is correct and the database is correct, but when I go back to the previous commit (git checkout command) and then migrate, a new migration is created, but when I run command python manage.py migrate, it says no changes were found. When I look at the database, I see that it has the same git checkout fields as before. I went through many ways, I deleted the migrations and created them again, but it didn't help, it still said that there is no change. Only when I delete the database and create it again, the migrate command works correctly. Deleting the database is dangerous. Can you suggest another way and guide me, thank you python manage.py makemigrations Migrations for 'main_app': main_app\migrations\0001_initial.py - Create model Project - Create model Resume - Create model Experience - Create model Comment python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, main_app, sessions, users Running migrations: No migrations to apply. -
How to aggregate over multiple fields in Django?
I have a Dango model Trade that store trades information for several markets. The objects are timestamped at every 5 minutes and I need to aggregate them by market and by datetime. What is the best solution to do that with performance in mind ? As you can see below, I could extract a list of the desired timestamps, iterate and aggregate data but I'm afraid it's not the most efficient solution. class Trade(TimestampedModel): market = models.ForeignKey(Market, on_delete=models.CASCADE, null=True) datetime = models.DateTimeField(null=True) amount = models.FloatField(null=True) price = models.FloatField(null=True) trades = models.FloatField(null=True) This is my code: from django.db.models import Sum, Avg # Time order object qs = Trade.objects.all().order_by("-datetime") # Extract unique timestamps dts = qs.values_list("datetime", flat=True).distinct() for dt in dts: cum_a = qs.filter(datetime=dt).aggregate(num_a=Sum('amount'))['num_a'] cum_t = qs.filter(datetime=dt).aggregate(num_t=Sum('trades'))['num_t'] avg_p = qs.filter(datetime=dt).aggregate(avg_p=Avg('price'))['avg_p'] .... # Store aggregated data -
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 …