Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: cannot import name 'reflections' from 'chatbot'
It doesn't work even I've imported from chatbot import Chat, reflections, multiFunctionCall.Let show me the way if you can deal with a issue It doesn't work even I've imported from chatbot import Chat, reflections, multiFunctionCall.I expect the way How to solve this problem -
"file wasn't available on site" error while it does exist, Django
I am programming a web that gets a .csv or .xlsx dataset, processes it, and returns it to the user using Django. I should say it is working OK on localhost. but not in a real server. views.py for creating a project and receiving the file: from django.core.files.storage import FileSystemStorage def create_prject(request): if request.method == 'POST': user = request.user name = request.POST.get('pname') data = request.FILES['data'] frequency = request.POST.get('frequency') unit = request.POST.get('unit') fs = FileSystemStorage(location=f'Media/Projects/{user}') filename = fs.save(data.name, data) dataurl = f'/Media/Projects/{user}/{filename}' header = request.POST.get('header') if header is not None: Project.objects.create(ProUser=user, Name=name, Data=filename, DataURL=dataurl, Header=True, Frequency=str(frequency), Unit=unit) else: Project.objects.create(ProUser=user, Name=name, Data=filename, DataURL=dataurl, Header=False, Frequency=str(frequency), Unit=unit) return redirect('dashboard') and after processing I want to return to user the files (the raw file and processed file must be downloadable). views.py after processing: def process(request): user = request.user if not user.is_authenticated: return redirect('login') else: if request.method == 'POST': # Some Processing Functions and creating the pandas.DataFrame excel_file = f'Despiked - {project.Name}.xlsx' dff.to_excel(excel_file, index=False) fs = FileSystemStorage(location=f'Media/Projects/Despiked/{user}') filename = fs.save(excel_file, open(excel_file, 'rb')) os.remove(excel_file) project.Processed_Data = filename project.Processed_DataURL = f'/Media/Projects/Despiked/{user}/{filename}' project.save() return redirect('dashboard') the download button will be shown in the template. but when I click on each file (raw or processed) I get the "File … -
Django django.db.backends.postgresql no available database error
I have this error and I don't have a typo django.core.exceptions.ImproperlyConfigured: '"django.db.backends.postgresql"' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' I've also tried with posgresql_psycopg2 since my django version is Django==2.2.28 I'm having this issue while I'm trying to run tests with tox. It works with django.db.backends.sqlite3but I want to run tests on postgres These are my deps from logs + docker compose -f docker-compose-test.yml exec -i -t test bash -c 'tox -e full_test ; chown 1563162805:1138207179 -R .' full_test installed: amqp==2.6.1,appdirs==1.4.4,asn1crypto==0.22.0,astroid==2.3.3,attrs==22.2.0,Authlib==1.2.1,backcall==0.2.0,beautifulsoup4==4.7.1,bento3 @ file:///bento3/.tox/.tmp/package/16/bento3-3.109.0.zip,billiard==3.6.4.0,boto3==1.14.23,botocore==1.17.63,bump2version==1.0.1,celery==4.4.7,certifi==2022.9.24,cffi==1.15.1,chardet==3.0.4,charset-normalizer==2.0.12,contextlib2==0.5.4,coreapi==2.3.3,coreschema==0.0.4,coverage==6.2,cryptography==3.4.7,cssselect==1.0.3,dateutils==0.6.8,decorator==5.1.1,defusedxml==0.7.1,distlib==0.3.7,Django==2.2.28,django-appconf==1.0.2,django-celery-results==2.2.0,django-classy-tags==2.0.0,django-debug-toolbar==3.1.1,django-elasticache==1.0.3,django-extensions==3.1.3,django-filer==0.9.115,django-filer-rest==1.4.6,django-filter==2.4.0,django-heartbeat==2.0.3,django-http-auth==2.0.0,django-identity-consumer==1.0.9,django-js-asset==2.0.0,django-mptt==0.11.1,django-polymorphic==2.1.2,django-rest-swagger==2.0.4,django-sekizai==2.0.0,django-simple-history==3.0.0,django-storages==1.9.1,django-tagging==0.5.0,django-tastypie==0.12.2,django-waffle==0.12.0,django-webpack-loader==0.7.0,djangorestframework==3.13.1,djangorestframework-jsonapi==3.1.0,docutils==0.15.2,easy-thumbnails==2.7,enum34==1.1.6,execnet==1.9.0,factory-boy==2.12.0,Faker==5.0.0,feedparser==6.0.8,filelock==3.4.1,google-api-python-client==1.3.1,httplib2==0.22.0,idna==3.4,importlib-metadata==1.7.0,importlib-resources==3.2.1,inflection==0.3.1,iniconfig==1.1.1,ipaddress==1.0.18,ipdb==0.13.9,ipython==7.16.1,ipython-genutils==0.2.0,isort==4.3.21,itypes==1.1.0,jedi==0.19.0,Jinja2==3.0.3,jmespath==0.10.0,json-schema-validator==2.4.1,kombu==4.6.11,lazy-object-proxy==1.4.4,lxml==4.7.1,MarkupSafe==2.0.1,mccabe==0.6.1,newrelic==7.16.0.178,oauth2client==1.5.2,objectpath==0.6.1,openapi-codec==1.0.0,packaging==21.3,parso==0.8.3,pbs-account-consumer==1.7.2,pbs-api-adapters==0.3.15,pexpect==4.8.0,pickleshare==0.7.5,Pillow==8.4.0,pluggy==0.13.1,prompt-toolkit==3.0.36,psutil==5.7.0,psycopg2==2.7.3.2,ptyprocess==0.7.0,py==1.11.0,pyasn1==0.1.9,pyasn1-modules==0.0.8,pycparser==2.18,pycurl==7.43.0.6,Pygments==2.14.0,pylibmc==1.5.2,pylint==2.4.2,pylint-celery==0.3,pylint-django==2.0.11,pylint-plugin-utils==0.7,pyOpenSSL==21.0.0,pyparsing==3.1.1,pytest==6.1.2,pytest-cov==2.8.1,pytest-django==4.4.0,pytest-factoryboy==2.0.3,pytest-forked==1.4.0,pytest-xdist==1.34.0,python-dateutil==2.5.3,python-googleanalytics==1.0.2,python-memcached==1.53,python-mimeparse==1.5.2,python3-openid==3.1.0,pytz==2023.3,redis==3.5.3,requests==2.26.0,rfc3987==1.3.7,rfeed==1.1.1,rsa==4.9,s3transfer==0.3.7,sentry-sdk==1.9.10,sgmllib3k==1.0.0,simplejson==3.8.2,six==1.10.0,soupsieve==1.9.5,sqlparse==0.4.4,text-unidecode==1.3,toml==0.10.2,tox==3.24.4,traitlets==4.3.3,typed-ast==1.4.3,typing-extensions==4.1.1,Unidecode==1.1.2,uritemplate==0.6,urllib3==1.26.7,vine==1.3.0,virtualenv==20.0.23,wcwidth==0.2.6,wrapt==1.11.2,zipp==1.2.0 full_test run-test-pre: PYTHONHASHSEED='2000759817' My python version is 3.6 -
How to use ModelChoiceField and ModelMultipleChoiceField without duplication in the database
I have a (main) Model that has multiple fk's class ParkingSpace(models.Model): name = models.CharField(max_length=50, blank=False) description = models.TextField(blank=False) image = models.ImageField(null=True, upload_to="images/parking_spaces") price = models.ForeignKey('Price', on_delete=models.CASCADE, null=True, blank=False) opening_hours = models.ForeignKey('OpeningHours', on_delete=models.CASCADE, null=True, blank=False) location = models.OneToOneField('Location', on_delete=models.CASCADE, null=True, blank=False) size = models.ForeignKey('Size', on_delete=models.CASCADE, null=True, blank=False) type = models.ForeignKey('Type', on_delete=models.CASCADE, null=True, blank=False) features = models.ManyToManyField('Features', blank=False, db_table='ParkingSpaceFeatures') reviews = models.ManyToManyField('Review', blank=False, db_table='ParkingSpaceReviews') contact_information = models.ForeignKey('ContactInformation', on_delete=models.CASCADE, null=True, blank=False) seller_account = models.ForeignKey('Account', on_delete=models.CASCADE, null=True, blank=False) Let me use size in this example: class Type(models.Model): STREET = "ST" # Parking space that is on the street PARKINGKLOT = "PL" # Parking space that is a parking lot (car park) PRIVATE = "PV" # Parking space that is being rented out by an individual TYPE_CATEGORY_CHOICES = [ (STREET,"Street Parking"), (PARKINGKLOT, "Car Park"), #used Car Park as user-friendly text as more commonly used (PRIVATE, "Private Parking") ] type_category = models.CharField(max_length=2,choices=TYPE_CATEGORY_CHOICES,blank =False,null=True) Now I want to create a form where the user will be able to enter the information to create a parking space. For fields such as size,type and features the form ModelChoiceField or ModelMultipleChoiceField will be used. The problem is when I use this and save it to the database there is dupliaction? … -
save user to db,if I have two customusers.How do i save them and generate JWT using SimpleJWT in DRF
I Have two Customusers in my project, The main Customuser: lass CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', 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) class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True,null=False) profile_picture = models.ImageField(upload_to='profile_pics/', null=True, blank=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) date_of_birth = models.DateField(null=True, blank=True, default=None) phone_number = models.CharField(max_length=20, blank=True,null=True) address = models.TextField(blank=True) total_tickets_sold = models.PositiveIntegerField(default=0) total_tickets_bought = models.PositiveIntegerField(default=0) is_verified = models.BooleanField(default=False) kyc_verified = models.BooleanField(default=False) social_media_account = models.CharField(max_length=100, blank=True) bank_account_name = models.CharField(max_length=100, blank=True) bank_account_iban = models.CharField(max_length=100, blank=True) bank_account_name_on_card = models.CharField(max_length=100, blank=True) user_rating = models.IntegerField(default=0) last_login = models.DateTimeField(null=True, blank=True) delete_account_request = models.BooleanField(default=False) user_tags = models.CharField(max_length=100, blank=True) account_creation_date = models.DateTimeField(auto_now_add=True) USER_TYPE_CHOICES = ( ('buyer', 'Buyer'), ('seller', 'Seller'), ) user_type = models.CharField(max_length=10, choices=USER_TYPE_CHOICES, default='buyer') ACCOUNT_STATUS_CHOICES = ( ('active', 'Active'), ('suspended', 'Suspended'), ('banned', 'Banned'), ) account_status = models.CharField(max_length=10, choices=ACCOUNT_STATUS_CHOICES, default='active') is_staff = models.BooleanField(default=False) # groups = models.ManyToManyField(Group, blank=True, related_name='customuser_set') # user_permissions = models.ManyToManyField(Permission, blank=True, related_name='customuser_set') objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] And also … -
Occasionally slow Redis requests from Django
On a Django application we are using Redis as caching backend using the django-redis package. While this works generally well there are occasionally Redis requests which are quite slow, ranging from a hundreds of milliseconds up to 4-5 seconds (!). The affected slow requests are simple GET and SET requests on various keys. A few of the keys have a little larger values like up to 180 KB but it happens also on keys with smaller values. We use Sentry's performance data feature to identify the slow requests. Those slow requests happen only one or two times a day, we didn't found a particular pattern or a way to reproduce it. Redis' slowlog does not show any of those slow requests, the slowest query listed is about 200ms and is not related to the slow queries we see in Sentry. The whole setup is hosted in the OpenTelekomCloud, which is some sort of an OpenStack instance. The Django application is running on multiple PODs in a Kubernetes cluster and the Redis server is a managed instance of the hosting provider (Kubernetes and Redis server are in the same VPC and same subnet). The Redis server is used almost exclusively as … -
django messages TemplateSyntaxError
I've been trying to use messages in django. I checked everything but keep getting this error below. TemplateSyntaxError at /home/ 'messages' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz I made sure all the settings are properly configured in settings.py INSTALLED_APPS = [ 'schedule_app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ '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', ] TEMPLATES = [ { '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', ], }, }, ] <h2> {% if messages %} {% for message in messages %} {% message %} {% endfor %} {% endif %} </h2> I also tried {% load messages %} on top of the template but still not working.. -
How to disable the back browser button after a user logs into a profile
I am trying to make a user not be able to go back to the login page from a profile page after logging in I have tried using @never_cache but it still seems to be saving the session and I can go back with the browser back button without logging out. I have then implemented the@cache_control(max_age=0, no_cache=True, no_store=True, must_revalidate=True) and its did not work. I then tried adding a random_string and timestamp after the login url but this made the profile page unreachable Here is my current user_login view: @cache_control(max_age=0, no_cache=True, no_store=True, must_revalidate=True) #Ensure you cant go back to login with the browser back button def user_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: messages.success(request, 'Logged in successfully') # Display success message login(request, user) timestamp_query_param = int(timezone.now().timestamp()) return redirect(f'profile/?t={timestamp_query_param}') # Handling authentication failure else: messages.error(request, 'Account does not exist or password is wrong') # Display error message and redirect the same page return render(request, 'login.html', {'error_message': 'Invalid credentials'}) return render(request, 'login.html') -
Advice for converting a web application (Django REST backend, React frontend) into a desktop application
I've been working on a web application which has pivoted, and now I'd like to convert it into a deployable desktop application. The frontend is made with React, and the backend is made using Django REST, along side some necessary services such as Celery, RabbitMQ, and Reddis. What would be the best practice here? Ideally I'd love to have everything shippable as a singular installation package, but I'm not sure that's feasible without scrapping the frontend and just making the whole app in Django. Any advice would be appreciated! -
Migrate the Databse from Sqlite3 to PostgreSQL
I want to change the databse of my django application from default(sqlit3) to PostgreSQL for better productivity I have Mayan EDMS App which is designed in Django and used SQLite3 as the database in the back-ends and i want to change the database of my Django app from SQLite3 to PostgreSQL Please help to to acheive this functionality i have tried by changing the databse details and i expect to achevie that functionality -
Django formset get all parameter value issue
I have a listview that show data in table, I have create a form that filter the data and show in table (working), but I want to make a formset, add filter condition and get all values without any success. views.py class CmsView(ListView): queryset = Cmsexport.objects.all().values() model = Cmsexport form_class = CmsFilterForm template_name = 'table.html' context_object_name = 'table' paginate_by = 10 def get_queryset(self): queryset = super(CmsView, self).get_queryset() field = self.request.GET.get('field') lookup = self.request.GET.get('lookup') value = self.request.GET.get('value') reset = self.request.GET.get('btn-reset') if (field and lookup and value) is not None: query = field.lower().replace(" ", "_") + '__' + lookup queryset = Cmsexport.objects.filter(**{ query: value }).values() if reset: queryset = Cmsexport.objects.filter().values() return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = CmsFilterForm() context['formset'] = CmsFormSet(queryset=Cmsexport.objects.none()) return context forms.py class CmsFilterForm(ModelForm): class Meta: model = Cmsexport #fields = ['name', 'state_text'] fields = '__all__' CmsFormSet = modelformset_factory( Cmsexport, fields = '__all__', extra=1 ) Any idea? -
Django:UNIQUE constraint failed: users_profile.user_id
I am using a Form to create a registration feature for my website. However, when I try to register, I encounter the following issue. Strangely, in the admin database, a user and profile have been successfully created. Can anyone please help me identify what might be causing this problem django.db.utils.IntegrityError: UNIQUE constraint failed: users_profile.user_id model from django.db import models from django.contrib.auth.models import User import uuid # Create your models here. from django.db.models.signals import post_save, post_delete from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True , blank=True) name = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=500, blank=True, null=True) username = models.CharField(max_length=200, blank=True, null=True) location = models.CharField(max_length=200, blank=True, null=True) short_intro = models.CharField(max_length=200, blank=True , null=True) bio = models.TextField(blank=True, null=True) profile_image = models.ImageField( null=True, blank=True, upload_to='profiles/', default='profiles/user-default.png') social_github = models.CharField(max_length=200, blank=True, null=True) social_twitter = models.CharField(max_length=200, blank=True, null=True) social_linkedin = models.CharField(max_length=200, blank=True, null=True) social_youtube = models.CharField(max_length=200, blank=True, null=True) social_website = models.CharField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.username) class Meta: ordering = ['created'] class Skill(models.Model): owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank=True, null=True) description = models.TextField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__ (self): return str(self.name) #@receiver(post_save, … -
TypeError: data.map is not a function in react and django
I'm using Axios to retrieve data from the backend. When I log the data to the console, it appears as an object. However, I need the data to be in an array format. When I try to use the map function on the data, it gives me an error stating that data.map is not a function. I am using django in backend function Search() { const [data,setData] = useState([]) // setting data as array i had also used null here useEffect(()=>{ axios.get("http://127.0.0.1:8000/api/listing") //using axios api .then(response =>{ setData(response.data) console.log(response.data) //data is appears as object when do console.log }) .catch(error =>{ console.log("Error fetching data:",error) }); },[]); return ( <div> <h1>Fetched Data</h1> {/* <ul> //data.map is not a function {data.map(item =>( <li key={item.id}>{item.title}</li> ))} </ul> */} </div> ) } export default Search I have checked wheather data from backend is in form of array or object and i got that the data is not in form of array if (Array.isArray(response.data)) { setData(response.data); } else { console.error('Data is not an array:', response.data); } after that i tried to convert data to array in two ways .then((response) => { //if data is not in array convert it into array const dataArray = Array.isArray(response.data) ? … -
why is django import export not working for me
I have the following model for a website category class Category(models.Model): name = models.CharField(max_length=50) description = models.TextField(max_length=500, blank=True, null=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True ,related_name='sub_categories') created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "category" verbose_name_plural = "categories" db_table = "website_categories" unique_together = ('name', 'parent',) def __str__(self): return self.name I have installed django-import-export model and have the following set up for the admin from .models import * from import_export import resources from import_export.admin import ImportExportModelAdmin from django.contrib.auth import get_user_model User = get_user_model() class WebsiteAdmin(admin.ModelAdmin): list_display = ("url", "category", "user") search_fields = ["url", "category", "user"] class ServiceCategoryAdmin(admin.ModelAdmin): list_display = ("name",) search_fields = ["name"] class ProductCategoryAdmin(admin.ModelAdmin): list_display = ("name",) search_fields = ["name"] class CategoryResource(resources.ModelResource): class Meta: model = Category fields = ('id', 'name', 'description',) class CategoryAdmin(ImportExportModelAdmin): list_display = ("name",) search_fields = ["name"] resource_classes = [CategoryResource] admin.site.register(Website, WebsiteAdmin) admin.site.register(ServiceCategory, ServiceCategoryAdmin) admin.site.register(ProductCategory, ProductCategoryAdmin) admin.site.register(Category, CategoryAdmin) On the admin side I see the import and export buttons and I am able to import a file but the data is not getting correctly imported and the only thing getting generated is the id. So for every line in the csv doc the id is generated bu not the name nor … -
Atomic Transactions not working in Django
I have a Django function which does a very basic create/update operation and I was trying to implement atomic block for transactions but it doesn't seem to work. The implementation is very straight forward but I am still unable to do the rollback so I am wondering if I am doing something wrong or missed some config. with transaction.atomic(): try: auth_user_data['email'] = email auth_user_data['first_name'] = first_name auth_user_data['last_name'] = last_name user = User.objects.using('xyz').create(**auth_user_data) auth_user_data['id'] = user.id user_securities_data['zipcode'] = address_info['zipcode'] user_securities_data['address'] = address_info['address'] user_securities_data['country'] = address_info['country'] user_securities_data['user_id'] = user.id user_securities_data['abc'] = user.id user = Profile.objects.using('xyz').create(**user_securities_data) except Exception as e: print("ERROR___________", e) What I am trying to achieve here is the first create to the DB should be success and the second create DB should be a failure and that would revert both the operations. -
Django pytest in docker-compose django.db.utils.OperationalError
I've docker-compose configuration for django and postgres, it works fine. However, when I'm trying to run pytest inside a django container it fails with an error: pytest apps/service/tests/test_api.py::TestCreate::test_new ====================================================================== test session starts ======================================================================= platform linux -- Python 3.8.18, pytest-7.4.1, pluggy-1.3.0 django: settings: project.settings.local (from env) rootdir: /app/code configfile: pytest.ini plugins: mock-3.11.1, django-4.5.2, Faker-19.6.1, celery-4.4.2 collected 1 item apps/service/tests/test_api.py E [100%] ============================================================================= ERRORS ============================================================================= __________________________________________________ ERROR at setup of TestCreate.test_new __________________________________________________ self = <django.db.backends.postgresql.base.DatabaseWrapper object at 0xffff71cedf70> @async_unsafe def ensure_connection(self): """Guarantee that a connection to the database is established.""" if self.connection is None: with self.wrap_database_errors: > self.connect() /usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py:219: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/local/lib/python3.8/site-packages/django/utils/asyncio.py:33: in inner return func(*args, **kwargs) /usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py:200: in connect self.connection = self.get_new_connection(conn_params) /usr/local/lib/python3.8/site-packages/django/utils/asyncio.py:33: in inner return func(*args, **kwargs) /usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py:187: in get_new_connection connection … -
Poll Django DB regularly from within app - permissions error
I would like to keep record of some "check-in" events in my Django app database. If a client/user hasn't posted a check-in (done via HTTP request to my app) for over X minutes, then I would like to emit a socketIO message to the client. The client can post a check-in as frequently as they like. I am running this app from a Kubernetes pod, with database username and password being exported as environment variables on pod deployment. My solution is to kick off a thread at app startup, and have this thread poll the Django database every 10 minutes. If a check-in record is not found in the database in the last 10 minutes, then call my socket emission function. Otherwise, go back to sleep for 10 minutes. Unfortunately, when I try to poll the database from within my thread, I'm met with: django.db.utils.ProgrammingError: permission denied for table check_in_table Some simplified code snippets: # WatchCheckIn().start() is called from my apps.py file within my `AppConfig`'s `ready()` class WatchCheckIn(threading.Thread): def run(self) -> None: logging.info('Querying database for check-ins.') try: latest_record = models.CheckIn.objects.last() check_in_period = datetime.datetime.now( tz=datetime.timezone.utc) - datetime.timedelta(minutes=10) if latest_record.check_in_time < check_in_period: socket_views.notify_need_check_in() except IndexError: logging.warning('No previous check-ins found.') finally: time.sleep(600) In … -
Uncaught TypeError: Cannot read properties of undefined (reading 'connect'). Twilio SDK Javascript with Django
Im developing a Dialer web app with Django and to make calls trought the browser im user Twilio SDK and Im reciving this error Complete error: ContentDispatcherService: no listeners for an event TAB_STATE__GET_NAVIGATION_METHOD caller:1 Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist. caller.js:20 Requesting Access Token... caller.js:87 Uncaught TypeError: Cannot read properties of undefined (reading 'connect') at start_device (caller.js:87:12) at HTMLButtonElement.onclick (caller:75:86) caller.js:52 Device registered So im trying to make a call trhoug connect(); method but it doesnt stablish the conection, the device is register and idk what means on it. script / async function start_device() { console.log("Requesting Access Token..."); /*Document ready*/ $.get('token', { forPage: window.location.pathname }) .then(function (data) { device = new Twilio.Device(data.token, { codecPreferences: ["opus", "pcmu"], fakeLocalDTMF: true, enableRingingState: true }); device.on("ready", function (device) { console.log("Twilio.Ready"); updateCallStatus("Ready"); }); device.on('registered',function(reg){ console.log('Device registered'); updateCallStatus('Registered'); }); device.on("error", function (error) { console.log("Twilio.Device Error: " + error.message); updateCallStatus("ERROR: " + error.message); }); device.on("connect", function (conn) { // Enable the hang up button and disable the call buttons hangUpButton.prop("disabled", false); updateCallStatus("Calling"); }); device.on("disconnect", function (conn) { // Disable the hangup button and enable the call buttons hangUpButton.prop("disabled", true); updateCallStatus("Ready"); }); device.register(); startDevice.prop('disabled', true) }) .catch(function (err) { console.log(err); console.log("Could … -
je rencontre un probleme d'importation de mon fichier json dans la base de donnee postgresql [closed]
je n'arrive pas a importer mes donnee du json pour postgresql django svp aidez moi a resoudre ce problemme cela fait une semaine que je n'y arrive pas. voici l'erreur que cela genere l'orsque jexecute ma commande python manage.py loadata fixtures/file_backup.json django.core.serializers.base.DeserializationError: Problem installing fixture 'G:\Opera + 1.9 tmp\fixtures\file_backup.json': -
Is there an elegant way to send repeating data in RESTful requests [closed]
The frontend of an app I'm building makes various api calls to the backend which follows restful principles. There is some data the user inputs when they first visit the website that gets sent to the backend in every ensuing backend request. At the moment, I am just throwing that data along with other relevant data in the JSON payload every time. For some reason I'm convinced there has to be a more elegant way to package data that gets sent in every single GET request. -
Master template for airium
I am using airium as a replacement for the default Django templates system. In the default Django system the concept of master template is used to give a common frame and look to all the pages of a site. I believe the same notion of a "master html" providing a frame is also worth when using Airium, no? Is there a way to use such a "master html" with Airium? Is it a concept existing within Airium? How could this possibly work? -
cannot import available functions in views or models in django
i started a simple django app called 'some_app' and added some code to the models.py and views.py. now i made a new file in the same directory called 'tmp_01.py' and wanted to import the functions and classes i wrote in views.py and models.py respectively. i'am facing a "moduleNotFoundError". models.py contains: from django.db import models class C1(models.Model): title=models.CharField(max_length=250,default='full of empty') and views.py : from django.shortcuts import render from django.db import transaction from .models import C1 john='doe' def finished(): print('DONE') def create_obj(): with transaction.atomic(): transaction.on_commit(finished) votes = C1.objects.create(title=john) votes.save() and finally tmp_01.py: from some_app.views import create_obj() from some_app.models import C1 create_obj() so when i run tmp_01.py i face ModuleNotFoundError: no module named "some_app" -
How to create a Djano ModelForm and a view that handles a Foreign key relationship
I have a model which consists of fk's to other models. class ParkingSpace(models.Model): name = models.CharField(max_length=50, blank=False) description = models.TextField(blank=False) image = models.ImageField(null=True, upload_to="images/parking_spaces") price = models.ForeignKey('Price', on_delete=models.CASCADE, null=True, blank=False) opening_hours = models.ForeignKey('OpeningHours', on_delete=models.CASCADE, null=True, blank=False) location = models.OneToOneField('Location', on_delete=models.CASCADE, null=True, blank=False) size = models.ForeignKey('Size', on_delete=models.CASCADE, null=True, blank=False) type = models.ForeignKey('Type', on_delete=models.CASCADE, null=True, blank=False) features = models.ManyToManyField('Features', blank=False, db_table='ParkingSpaceFeatures') reviews = models.ManyToManyField('Review', blank=False, db_table='ParkingSpaceReviews') contact_information = models.ForeignKey('ContactInformation', on_delete=models.CASCADE, null=True, blank=False) seller_account = models.ForeignKey('Account', on_delete=models.CASCADE, null=True, blank=False) Let me use the opening hours as an example: class OpeningHours(models.Model): # Opening and closing times of every day in the week monday_open = models.TimeField(null=True,blank=False) monday_close = models.TimeField(null=True,blank=False) tuesday_open = models.TimeField(null=True,blank=False) tuesday_close = models.TimeField(null=True,blank=False) wednesday_open = models.TimeField(null=True,blank=False) wednesday_close = models.TimeField(null=True,blank=False) thursday_open = models.TimeField(null=True,blank=False) thursday_close = models.TimeField(null=True,blank=False) friday_open = models.TimeField(null=True,blank=False) friday_close = models.TimeField(null=True,blank=False) saturday_open = models.TimeField(null=True,blank=False) saturday_close = models.TimeField(null=True,blank=False) sunday_open = models.TimeField(null=True,blank=False) sunday_close = models.TimeField(null=True,blank=False) Now I want to create a form where the user will be able to enter the information to create a parking space. For fields in parking space like price,opening_hours, location and contact_information these models have multiple fields that data needs to be inputted in a form. Is there a way that Django has that can handle all the database saving … -
ModuleNotFoundError: No module named 'pandas' in Django
I've followed the cookiecutter instructions to create a django project using Docker. I'm trying to use pandas inside my project but whatever I do, I get: (yt_venv) jan@Jans-MacBook-Pro summarizing % docker compose -f local.yml up [+] Running 3/0 ⠿ Container summarizing_local_postgres Running 0.0s ⠿ Container summarizing_local_docs Running 0.0s ⠿ Container summarizing_local_django Created 0.0s Attaching to summarizing_local_django, summarizing_local_docs, summarizing_local_postgres summarizing_local_django | PostgreSQL is available summarizing_local_django | Traceback (most recent call last): summarizing_local_django | File "/app/manage.py", line 31, in <module> summarizing_local_django | execute_from_command_line(sys.argv) summarizing_local_django | File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line summarizing_local_django | utility.execute() summarizing_local_django | File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 416, in execute summarizing_local_django | django.setup() summarizing_local_django | File "/usr/local/lib/python3.11/site-packages/django/__init__.py", line 24, in setup summarizing_local_django | apps.populate(settings.INSTALLED_APPS) summarizing_local_django | File "/usr/local/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate summarizing_local_django | app_config = AppConfig.create(entry) summarizing_local_django | ^^^^^^^^^^^^^^^^^^^^^^^ summarizing_local_django | File "/usr/local/lib/python3.11/site-packages/django/apps/config.py", line 193, in create summarizing_local_django | import_module(entry) summarizing_local_django | File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module summarizing_local_django | return _bootstrap._gcd_import(name[level:], package, level) summarizing_local_django | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ summarizing_local_django | File "<frozen importlib._bootstrap>", line 1204, in _gcd_import summarizing_local_django | File "<frozen importlib._bootstrap>", line 1176, in _find_and_load summarizing_local_django | File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked summarizing_local_django | ModuleNotFoundError: No module named 'pandas' summarizing_local_django exited with code 1 In the same … -
Add Class To All Fields Django Forms
How do you add a class to all fields at one time using Django Forms? I know you can define it per field using field = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control-sm'})) But thats a lot of boiler plate to add to every field on a model form. And theres even by looping through the fields in the constructor, but that seems more of a hack than would be neccessarry. Is there a more generic/ built-in way of doing this?