Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve ProgrammingError "relation "django_session" does not exist" when using Django with Heroku
I have looked at different threads on here and can't seem to find the solution. It's presenting itself like its an error in the heroku code (I know its not, I've done something wrong), regardless I am very stuck. I have deployed the django project with sqlite3, no issues and am currently trying to convert it postgreSQL. My Settings File: from pathlib import Path import os import django_heroku import dj_database_url from decouple import config import dj_database_url import dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # .env configuration: dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! #SECRET_KEY = 'django-insecure-#r@o%yo-#92(0*j%9vn*9l7itkd50l7wadkc=55p$wd46ljl5-' with open('secret_key.txt', 'r') as f: SECRET_KEY = f.readline().strip() # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts.apps.AccountsConfig', 'core.apps.CoreConfig', 'files.apps.FilesConfig', 'django_unused_media', ] AUTH_USER_MODEL = 'accounts.User' LOGIN_REDIRECT_URL = "/" LOGOUT_REDIRECT_URL = "/" MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = … -
How to modify this django Model to create single table in database?
backend.py from storages.backends.s3boto3 import S3Boto3Storage class PublicStorage(S3Boto3Storage): location = getattr(settings,'PUBLIC_FILES_LOCATION','PUBLIC_URL') default_acl = 'public-read' file_overwrite = False custom_domain = False class PrivateStorage(S3Boto3Storage): location = getattr(settings,'PUBLIC_FILES_LOCATION','PRIVATE_URL') default_acl = 'public-read' file_overwrite = False custom_domain = False Model.py from django.db import models from django.conf import settings from accounts_engine.models import CustomUser from Main.aws.backend import * class Template_Core(models.Model): user = models.ForeignKey(CustomUser,on_delete=models.CASCADE) original_filename = models.CharField(max_length = 500) TEMPLATE_TYPE_LIST = [ ('0','Private'), ('1','Public'), ('2','Shared'), ] template_type = models.CharField(max_length=15,choices=TEMPLATE_TYPE_LIST,default='Public') VIEW_TYPE_LIST = [ ('0','Edit'), ('1','Import'), ] view_type = models.CharField(max_length=10,choices=VIEW_TYPE_LIST,default='Import') template_name = models.CharField(max_length=255,default='mytemplate',null=False) template_description = models.CharField(max_length=500) creation_date = models.DateTimeField(auto_now_add=True) class Meta: abstract = True #class created for path to store path in db and also call public and private storage class based on requirement. class Template_Public(Template_Core): path = models.FileField(storage = PublicStorage()) class Template_Private(Template_Core): path = models.FileField(storage = PrivateStorage()) I don't want seperate class (Template_public,Template_private) because it's creating seperate table in db. How to modify this model.py file so that only one table can be created and path constructer can also be called for public and private storage. -
Django Fobi - runserver URL (http://127.0.0.1:8000/) Page Not Found
In order to be able to quickly evaluate the django-fobi, a demo app (with a quick installer) has been created (works on Ubuntu/Debian, may work on other Linux systems as well, although not guaranteed). Follow the instructions below for having the demo running within a minute. Grab the latest django_fobi_example_app_installer.sh: wget https://raw.github.com/barseghyanartur/django-fobi/stable/examples/django_fobi_example_app_installer.sh Assign execute rights to the installer and run the django_fobi_example_app_installer.sh: chmod +x django_fobi_example_app_installer.sh ./django_fobi_example_app_installer.sh Open your browser and test the app. Dashboard: URL: http://127.0.0.1:8001/fobi/ Admin username: test_admin Admin password: test Django admin interface: URL: http://127.0.0.1:8001/admin/ Admin username: test_admin Admin password: test After running all these command and also pip install django-fobi, the result of the runserver website url was 'Page Not Found'. But there are no pending migrations, and everything working normally. Also the urls.py seems to be okay. Can anyone solve this? thx -
Automatically fill in the user field in Models Django
After creating the user field in models.py, how can you make it fill itself by detecting the user by itself? -
Django Websocket getting slow as the connected users increases
I am using Django Channels to send messages to the frontend. and the frequency of the messages is one message per second, everything works fine when I am working on local but on production where I used Nginx, Gunicorn and Daphne to host the server, the connection to the websocket happened after 2-3 attempts, and after the webscokets get connected the messages started coming really slow. Is this issue is related to the server or with the code. Thank you !!! -
How can I redirect this to a slug url in django?
So I have one detail view and one function in my views.py. So i have included the form in detail view template list_detail.html. and upon posting the form successfully. It redirects to all page(homepage basically). Now I want it to redirect to detailview page which is like this. and for that I need to pass the slug value of that List models specific object. But can build the logic here. I am new to django. path('list/<slug:slug>/', TheirDetailView.as_view(),name='list_detail'), path('all',views.all, name='all'), path('create_comment',views.create_comment, name='create_comment'), class TheirDetailView(DetailView): model = List def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) modell = Review.objects.all() context["modam"] = modell context["form"] = ReviewForm() return context def create_comment(request): context = {} form = ReviewForm(request.POST or None) if form.is_valid(): form.save() return redirect('app:all') else: context['form'] = form return render(request, "app/create_comment.html", context) -
Create a Telegram bot inside my website in Django
I will be deploying a website in a few days and I would like to know if it is possible to run a Telegram bot together with my website. Because? This way, I would take better advantage of Django's ORM and would not need to create separate queries to the Database, since my Bot will provide information according to the client's wishes. Is there a library for this or could you create a separate code and run with Celery? -
Hi My Django Forms.cleaned_data is not giving me any output. Can someone help me?
I am trying to create a page to generate passwords and the user will select either level 0 or level 1 for varying strengths of the password. And I am not able to get the users selection of level 0 or level 1 using the radio button. My views.py from django.shortcuts import render import random import string from types import NoneType from random_word import RandomWords from .forms import CHOICES def password(request): passw = passGenAdvanced() form = CHOICES(request.POST) if form.is_valid(): selected = form.cleaned_data.get("password") print(selected) return render(request, 'generator/password.html', {"password":passw}) My forms.py from django import forms password = [('0','Level 0'), ('1', 'Level 1')] class CHOICES(forms.Form): password = forms.ChoiceField(choices=password, widget=forms.RadioSelect) My html file {% extends 'generator/base.html'%} {% block content %} <style> .button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } </style> <form method = "POST"> {% csrf_token %} <div class="form-check"> <input class="form-check-input" type="radio" name="password" id="Level0"> <label class="form-check-label" for="password">Level 0</label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="password" id="Level1"> <label class="form-check-label" for="password">Level 1</label> </div> <button type="submit" class="button">Submit</button> </form> <h5 class="alert alert-success">Your Generated Password: <strong>{{password}}</strong></h5> {% endblock %} Sorry if the problem may seem obvious, I am new to django. -
Djano error :TypeError: Object of type CharField is not JSON serializable.Thanks in Advance
**models.py** from django.db import models class Identity(models.Model): first_name=models.CharField(max_length=40,null=True,blank=False), last_name=models.CharField(max_length=40,null=True,blank=False), def __str__ (self): return self.first_name **serializers.py** from rest_framework import serializers from .models import Identity class IdentitySerializer(serializers.ModelSerializer): class Meta: model = Identity fields=('first_name','last_name',) **views.py** from rest_framework import generics from .models import Identity from .serializers import IdentitySerializer class IdentityList(generics.ListCreateAPIView): queryset=Identity.objects.all() serializer_class=IdentitySerializer class Identity(generics.RetrieveUpdateDestroyAPIView): queryset=Identity.objects.all() serializer_class=IdentitySerializer **Application** **urls.py** from django.urls import path,include; from App import views urlpatterns = [ path('identity', views.IdentityList.as_view()), path('<int:ik>/', views.Identity.as_view()), ] **Project** **urls.py** from django.contrib import admin from django.urls import path, include from rest_framework.schemas import get_schema_view from django.views.generic import TemplateView urlpatterns = [ path('', include('App.urls')), #path('', admin.site.urls), path('openapi', get_schema_view( title="Service", description="API development" ), name='openapi-schema'), path('docs/', TemplateView.as_view( template_name='documentation.html', extra_context={'schema_url':'openapi-schema'} ), name='swagger-ui'), ] **setting.py** """ Django settings for solutionOne project. Generated by 'django-admin startproject' using Django 4.0.4. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path # 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/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-72^br23d)5w=bk6q_7s)88u)ld!9yrpwzyv*vsn5qmpbts(_m-' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = … -
Filtering the last Query Created and Iterating through manytomany relationship in a Django Project
I have the following model: class Log(models.Model): log_order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) class ActiveSession(models.Model): log = models.ManyToManyField(Log, related_name='savedlogs') In my view I am trying to get the very last create ActiveSession which has a many to many relationship with Log model to iterate between them. This is how I created the views: def get_context_data(self, **kwargs): active_session =ActiveSession.objects.get(id=ActiveSession.objects.last().id) context = super().get_context_data(**kwargs) return context I think my problem is with the get i tried using filter(id=id).latest but it did not work. here is the template: {% for x in active_session %} {{ x.log_order }} {% endfor %} I am currently getting TypeError: 'ActiveSession' object is not iterable my question: How to fix this error and how can I use the for loop in the template to display the details of each Log which is inside each ActiveSession. In this example there are 3 Logs inside the Active session and I want to show the log_order of each -
jQuery onclick event doens't work on the first click
So my problem is that I created a jQuery function to open menu on button click. Menu code is located on another html template of my Django project, and what happens is that the menu doesn't open at the first click, but works after second. I also included part that changes the span element of the button which works from the first click. Here is my snippet for the jQuery: <script> $(document).ready(() => { $('#btn').on('click', function () { var thisElement = $(this); var buttonSpan = thisElement.find('span'); var menu = $("#menu"); if(buttonSpan.text() === "Close"){ buttonSpan.text('Open'); menu.css('width', '0'); } else { if(buttonSpan.text() === "Open"){ buttonSpan.text('Close'); menu.css('width', '20%'); } } }) }) </script> There is no any scripts on my html where the menu is located, it is just basic div with id 'menu'. But like I said, it should work as it opens at the second click. I think this is something to do with eventlistener as I read something about it, but I couldn't make a sense of it in a perspective of my problme. Also tried to change (document).ready(() => { to (document).ready(function() {, but it didn't do the trick. Is there somethign clear that I am missing? -
GridLayout not not containing generated cards in for loop
I want to make a gridlayout of cards in html that stores a bunch of cards generated using information I pull from a database. project_photo is an array of image file paths that are referred to generate the cards within the for loop. However, when I run it the gridlayout (named card-grid) only contains the first card that is generated from the for loop. Is there any way to make it so that it contains all the cards generated from the for loop? <div class="card-grid"> {% for project in context %} {% with 'jweb/images/'|add:project.image as project_photo %} <div class="card"> <h2 class="card-header" style="text-align:center">{{project.title}} <div class="card-image"> <img src="{% static project_photo %}" style="float:left"> </div> </h2> </div> </div> </div> -
nginx is giving 502 Bad Gateway, with user www-data and works when user is root
trying to debug this for the last two days, but I could not figure out what's wrong these are my permissions for the socket file srw-rw-rw- 1 www-data www-data 0 Oct 10 02:48 cafe.sock and my nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; with this conf I am getting this error "502 bad gateway" cafe.sock failed (13: Permission denied) while connecting to the upstream, client: 106.217.200.51, server: 65. 2.186.229, request: "GET /favicon.ico HTTP/1.1", upstream: "uwsgi://unix:/home/ubuntu/lakegarden/cafe.sock:", host: "65.2.186.229", referrer: "http://65.2.186.229/admin/" after changing user root; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; it is working fine, I can see the admin panel, but read it in SO that we should not have root as a user for security reasons. is there something that i am missing. thank you -
'AppSettings' object has no attribute 'STORE_TOKENS'
I have Object: AppSettings in app_settings.py class AppSettings(object): def init(self, prefix): self.prefix = prefix def _setting(self, name, dflt): from django.conf import settings getter = getattr( settings, "ALLAUTH_SETTING_GETTER", lambda name, dflt: getattr(settings, name, dflt), ) return getter(self.prefix + name, dflt) @property def STORE_TOKENS(self): return self._setting("STORE_TOKENS", False)` And when it get requested in my models.py by: if app_settings.STORE_TOKENS and self.token and self.token.app.pk: getting attribute error saying! 'AppSettings' object has no attribute 'STORE_TOKENS' Any input will be highly appreciated! -
Django Models create product bundle
I have a products model class Product(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=8, decimal_places=2) weight= models.PositiveIntegerField(default=454) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name="product_brand", blank=True, default=1) flavour = models.CharField(max_length=200, blank=True) discription = models.TextField(default='') image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url Now I want to be able to create a bundle of let's say, buy 5 items for £ 10. In the shopping cart, it will be added as a 5 X Multibuy. So I have another model called Multibuy class Multibuy(models.Model): name = models.CharField(max_length=200, default='Multibuy') brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name="multibuy_brand", blank=True, default=1) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) max_items = models.IntegerField(default=8, null=True, blank=True) price = models.DecimalField(max_digits=8, decimal_places=2) I am curious to know if there is a better way to do this. For example, write a decorator in the products model, and do away with the Multibuy model. Bearing in mind that the price and the quantity of the bundles for different products will be different and the admin needs to add that and may want to alter it later. -
Problem with pushing code to heroku through git. Using gitpod
Feel like this is probably the easiest thing in the world to you guys but i cant uploade my django blog to heroku, iv tried everything i can think of, runtime.txt file with different python versions, tried doing it through heroku instead of through git but that doesnt work. Im at a loss and i could really use some help. thanks in advance! ill paste in the error message down below gitpod /workspace/Django-Blog/Blog (master) $ git push heroku master Enumerating objects: 82, done. Counting objects: 100% (82/82), done. Delta compression using up to 16 threads Compressing objects: 100% (77/77), done. Writing objects: 100% (82/82), 26.92 KiB | 3.85 MiB/s, done. Total 82 (delta 18), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-22 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: -----> Installing python-3.10.7 remote: -----> Installing pip 22.2.2, setuptools 63.4.3 and wheel 0.37.1 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting asgiref==3.5.2 remote: Downloading asgiref-3.5.2-py3-none-any.whl (22 kB) remote: Collecting backports.zoneinfo==0.2.1 remote: Downloading backports.zoneinfo-0.2.1.tar.gz (74 kB) remote: … -
In model create days for every year created
Am new to Django (and Python) and have a problem initializing my model. For every school year created in the database, I want the corresponding days (not exactly 365/366, but > 300) to be created with a default value of 0 (a one-to-many relationship). I learned that I should not try to do this in a constructor, but after the constructor has run (and the object and its attributes have become accessible). So is this a case for using signals or should I override pre- or post-save(). And why? Or is there a third option which I have missed so far? from django.db import models import pandas as pd class BaseModel(models.Model): objects = models.Manager() class Meta: abstract = True class SchoolYear(BaseModel): start = models.DateField() end = models.DateField() def init_days(self): current_date = self.start delta = timedelta(days=1) while current_date <= self.end: self.days.add(schoolyear=self, date=current_date, value=0) current_date += delta class Day(BaseModel): schoolyear = models.ForeignKey(SchoolYear, on_delete=models.CASCADE) date = models.DateField() value = models.IntegerField() -
How to make django faster when there are large datasets?
I am making e-commerce website using django restframework. However, I realize that number of reviews are going to be larger as time goes.. (reviews have bunch of images and texts) let say 1000 reviews per items, It will make whole website slow when I go on to the product detail page or product list page.. how to prevent django getting slower when related datasets are bigger and bigger? -
Database not working running tests in Django with PostgreSQL in docker compose
I hope you are doing well! I am having a problem. I am trying to run my Django tests inside of my container with docker compose with the command line sudo docker compose run --rm app sh -c 'python3 manage.py test', but I am receiving these logs I am not pretty sure what is happening here. I am not noticing something weird in my docker-compose file either. I have tried cleaning the volumes, deleting all the images, and building again just in case I made something wrong through the process but it didn't fix my problem. I will let you know the file just in case. version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=dev - DB_USER=devuser - DB_PASS=changeme container_name: django_container depends_on: - db db: image: postgres container_name: postgresql_db restart: always volumes: - dev-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=dev - POSTGRES_USER=devuser - POSTGRES_PASSWORD=changeme volumes: dev-db-data: -
Getting the value of a foreign key of a foreign key in Django
I have three models as follows: class ServiceCategory(models.Model): name = models.CharField(max_length=50) def natural_key(self): return self.name class Service(models.Model): service_category = models.ForeignKey(ServiceCategory, on_delete=models.CASCADE) name = models.CharField(max_length=50) def natural_key(self): return self.name class Request(models.Model): name = models.CharField(max_length=50) services = models.ManyToManyField(Service) def natural_key(self): return self.name I want to query with the default Django in a way that I can get the names of the Service Category since I will be filtering on it. Currently I have the following: data = (Request.objects.filter( services__service_category__name=service ).distinct() ) data = serialize("json", data, use_natural_foreign_keys=True) So far I only get back the names of the services, but not the service categories. I have tried values but it throws an error when I serialize. I tried to add the fields argument in serialize with services__service_category__name and it did not work as well. Can anyone help with this please ? -
Reload Variable Data from DB without restarting Django
I have a function in my Django Views.py and I use the data in another function but if a user changes True to False then I want to update it without having to restart Django. def update_list(): global processess processess = botactive.objects.filter(active=True).values_list('user') update_list() I use processess which fetches users who have a model field set to True but if they set it to False I want to not include them if there is a new request. listi = [row[0] for row in processess] def wallet_verify(listi): # print(listi) database = Bybitapidatas.objects.filter(user = listi) ... This is the request I make and want it to use fresh data without restarting Django and also in python and not using html. def verifyt(request): with ProcessPoolExecutor(max_workers=4, initializer=django.setup) as executor: results = executor.map(wallet_verify, listi) return HttpResponse("done") -
How to generate many wallet addresses from a parent address using pycoin
I'm new to pycoin which is a python library for bitcoin and other alt-coins and couldn't get my head around it well yet. I'm working on a project requiring a parent wallet address with many child wallet addresses that could be used to receive coins via django. For example, Wallet A would be able to create child 1, child 2 and child 3 ..... and those children could be used to receive coins that will go straight to the parent's Wallet A Thanks a lot in advance -
How can I do to load the static folder from a CSS file?
How can I do to load the static folder from a CSS file? I tried to import using url() but it doesn't work. I want to use the static path to give a background to an element. background: url"{% static 'assets/img/check.png' %}", #458fff; } ``` -
Django complexity of one-to-one field reverse lookup
Reverse lookup takes log(n) time as stated in this question. complexity of a reverse django foreign key lookup What is the complexity of reverse lookup of one-to-one field? -
PyDictionary import issue
I am having issues on Mac OS installing PyDictionary into a Django project. When I pip3 install PyDictionary it says Requirement already satisfied: when I enter the command pip3 freeze it shows me PyDictionary==2.0.1 is already installed. But it can't find the module for some reason: from django.shortcuts import render from PyDictionary import PyDictionary # Create your views here. def index(request): return render(request, 'index.html') def word(request): search = request.GET.get('search') dictionary = PyDictionary() meaning = dictionary.meaning(search) synonyms = dictionary.synonym(search) antonyms = dictionary.antonym(search) context = { 'meaning': meaning, 'synonyms': synonyms, 'antonyms': antonyms } return render(request, 'word.html') I get the error: File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/Users/natelampros/PycharmProjects/english_dictionary/englishdictionary/dictionary/urls.py", line 2, in <module> from . import views File "/Users/natelampros/PycharmProjects/english_dictionary/englishdictionary/dictionary/views.py", line 2, in <module> from PyDictionary import PyDictionary ModuleNotFoundError: No module named 'PyDictionary' I've looked and can not find out why it can't find the module. I've tried installing PyDictionary on vs code and in terminal and it …