Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'remove' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['remove\\/\\(\\?P(?P<pk>[^/]+)\\\\d\\+\\)\\/\\$$']
I want the remove obj function to be triggered when the user click on it but its throwing error I have tried searching but cannot find solution I want to display a list ob objects and as soon as a user clicks on the object it gets deleted patients.html <body> {% include 'pages/nav.html' %} <div class="container"> <p>patients <a class="btn btn-primary btn-lg" role ="button" href="/patientadd">Add Patients</a> </p> <div class="list-group"> <br> <br> {% for i in names %} <a href="{% url 'remove' pk=i.pk %}" class="list-group-item">{{i}}</a> {% endfor %} </div> </div> </body> views.py not the whole view def removeObj(request, pk): object = get_object_or_404(request,pk) object.delete() model.py from django.db import models from django.contrib.auth.models import User class Patient(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) age = models.IntegerField() numvisit = models.IntegerField() detail = models.TextField(max_length=300) # url pattern urlpatterns = [ path('admin/', admin.site.urls), path('register/',register,name="register"), path('patients/',patients,name="patients"), path('patientadd/',patientAdd,name="patientadd"), path('login/',login,name="login"), path(r"remove/(?P<pk>\d+)/$",removeObj,name="remove"), path('register/logout/',logout,name="logout"), path('',home), ] -
Python anywhere deploying static django files wont work followed tutorial 100 %
I am trying to deploy my static files from my django app using python everywhere. I have followed 3 different tutorials now and none of them have worked. my STATIC_URL is set to /static/ and my STATIC_ROOT is '/home/coursePlanner/CoursePlanner/static' I collected all static files to the static root folder ('/home/coursePlanner/CoursePlanner/static) and If I use the python anywhere file broswer they are certainly all there. in my python anywhere WSGI file, path is set to '/home/coursePlanner/CoursePlanner' and os.environ['DJANGO_SETTINGS_MODULE'] is set to 'CoursePlanner.settings'. Finally, in the static files section of the webapp settings, URL = '/staitc/' and directory=/home/coursePlanner/CoursePlanner/static. When I open my webpage none of my static files load. Furthermore If I go to http://courseplanner.pythonanywhere.com/static/css/styles.css I get the following page: Page not found (404) Request Method: GET Request URL: http://courseplanner.pythonanywhere.com/static/css/styles.css Using the URLconf defined in CoursePlanner.urls, Django tried these URL patterns, in this order: admin/ [name='courseplanner-planner'] validate/ getRec/ search/ reqBarHandler/ getUnits/ The current path, static/css/styles.css, didn't match any of these. but if i go to the request URL in the python anywhere file manager, the file is present literally at that exact URL. What is going on? Any help would be greatly apperciated as Ive literally spent almost two full days trying … -
update field of queryset before passing to formset in django
i have a queryset that contains age of traveller. qset = Travellers.objects.filter(traveller_type='1') print(qset) print(qset[0].traveller_age) travellers_formset = TravellersFormset(queryset = qset) this gives give: <QuerySet [<Travellers: Travellers object (16887)>]> 33 i intend have a flag (is_renewal), which if true, should update the age of traveller by a year before passing to queryset to formset. so i'm doing something like this if travel_quote.is_renewal: print('starting renewal section') for each in qset.iterator(): print(each) print(each.traveller_age) each.traveller_age = each.traveller_age + 1 print(each.traveller_age) print('renewal section completed, checking for updated age') print(qset[0].get_fields()) this gives starting renewal section <QuerySet [<Travellers: Travellers object (16887)>]> 33 34 renewal section completed, checking for updated age 33 <<<<< i want this to be 34 instead of 33 after the loop -
how could I see in django the code of import lib utilizing shortcut keys in windows?
how to see in django the code of import lib utilizing shortcut keys in windows? Ad example the code behind djmoney etc. ? I remember that it is necessary to place the mouse on the library and press shortcut keys (ctrl+...) but I don't remember what. Thanks you and good evening from Italy -
django: python manage.py runserver issue
I am using Windows 10 and installed django via Anaconda conda install -c anaconda django after that I created a new project django-admin startproject website When I navigte into the folder where the manage.py file is an run python manage.py runserver I get the following output and nothing happens. Any ideas? -
Django : OneToOneField - RelatedObjectDoesNotExist
I have this two following classes in my model: class Answer(models.Model): answer = models.CharField(max_length=300) question = models.ForeignKey('Question', on_delete=models.CASCADE) def __str__(self): return "{0}, view: {1}".format(self.answer, self.answer_number) class Vote(models.Model): answer = models.OneToOneField(Answer, related_name="votes", on_delete=models.CASCADE) users = models.ManyToManyField(User) def __str__(self): return str(self.answer.answer)[:30] In the shell I take the first Answer: >>> Answer.objects.all()[0] <Answer: choix 1 , view: 0> I want to get the Vote object: >>> Answer.objects.all()[0].votes Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Hippolyte\AppData\Roaming\Python\Python38\site-packages\django\db\models\fields\related_descriptors.py", line 420, in __get__ raise self.RelatedObjectDoesNotExist( questions.models.Answer.votes.RelatedObjectDoesNotExist: Answer has no votes. But an error occured. I don't understand why the related_name is not recognized. Could you help me ? -
Custom vs Generic Views in Django
The question is about generic views, and their use in practice. They are presented as a better, cleaner, alternative for writing custom views, however they didn't seem to simply the view code much, and seemed very case specific. So in practice, are these generic views used extensively, with custom ones written only for very specific cases? Or is it the opposite, and generic views only exist for minimalists/case specific needs? -
Avoid race condition during creating object with incremented field
I'm trying to create MyModel object but I want to set bar field to already existed largest bar value in db for specified foo. The problem here are race conditions. I wanted to perform all logic on db side in one step without sucess. I have found solution but it's not the most elegant way. Infinite loops are always bad idea. from django.db import models, IntegrityError from django.db.models import Max class MyModel(models.Model): foo = models.UUIDField(primary_key=True, default=uuid4) bar = models.PositiveIntegerField() class Meta: constraints = [ models.UniqueConstraint( fields=['id', 'other_id'], name='unique_id_other_id' ) ] @classmethod def create_my_model(cls, data): while True: bar = (cls.objects.filter(foo=data['foo']).aggregate(Max('bar')).get('bar_max') or 0) + 1 try: cls.objects.create(bar=bar, **data) except IntegrityError: continue I will be glad if anyone can point me any direction how to handle this. BR -
Djongo not connecting to mlab server
I am using djongo with django2 to connect to mlab mongodb instance. settings.py 'default': { 'ENGINE': 'djongo', 'NAME': 'neon', 'HOST': 'mongodb://username:password@ds249605.mlab.com:49605/mlab1', } } although I am using this settings, the PyMongo connects to the local instance of mongodb. log Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/core/management/base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/backends/base/introspection.py", line 48, in table_names return get_names(cursor) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/django/db/backends/base/introspection.py", line 43, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/djongo/introspection.py", line 47, in get_table_list for c in cursor.db_conn.list_collection_names() File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/pymongo/database.py", line 856, in list_collection_names for result in self.list_collections(session=session, **kwargs)] File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/pymongo/database.py", line 819, in list_collections _cmd, read_pref, session) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/pymongo/mongo_client.py", line 1454, in _retryable_read read_pref, session, address=address) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/pymongo/mongo_client.py", line 1253, in _select_server server = topology.select_server(server_selector) File "/home/rahul/projects/django/neon/lib/python3.7/site-packages/pymongo/topology.py", line 235, in select_server … -
I need help to integrate duo_python 2FA into Django-mama-cas
I've setup django-mama-cas as a primary central authentication server for serveral department websites. The websites reside in a drupal/php web framework and use phpCAS for the CAS client. I need to integrate duo_python somehow to the django-mama-cas server. I am not sure where to start and any advice on what files or classes to edit is what I am looking for. From what I imagine those [files, classes, etc] to be, are below: settings.py import os import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType, PosixGroupType # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! with open('/n/fs/stage/signon/cas_container/casServer/secret_key.txt') as f: SECRET_KEY = f.read().strip() # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['signon.example.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mama_cas', ] 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', ] ROOT_URLCONF = 'casServer.urls' # Django Templates Settings: https://docs.djangoproject.com/en/2.2/topics/templates/ 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', ], }, }, ] # WSGI Settings: https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ WSGI_APPLICATION = 'casServer.wsgi.application' # Database Settings: https://docs.djangoproject.com/en/2.2/ref/databases/ DATABASES = … -
login_required decorator on a class based view in django
I have a working class based view. But when adding @login_required I get the error: AttributeError: 'function' object has no attribute 'as_view' Something is happening to the ResultListView here: from django.urls import path from .views import ResultListView urlpatterns = [ path('meetings/', ResultListView.as_view(), name='meetings'), ] My views.py: @login_required class ResultListView(ListView): template_name = ... def get_queryset(self): return Result.objects.filter(rider__user=self.request.user) Which is all working fine until I put the decorator in. Very confused now, I don't see why ResultListView should loose its attributes when sending it through the decorator. -
Get the last and unique element of the list based on date
Here is my data and code: [ (datetime.date(2020, 3, 25), 'Raport'), (datetime.date(2020, 3, 24), 'Raport'), (datetime.date(2020, 3, 23), 'Raport'), (datetime.date(2020, 3, 25), 'Document'), (datetime.date(2020, 3, 24), 'Document'), (datetime.date(2020, 3, 23), 'Document'), (datetime.date(2020, 3, 25), 'Analize'), (datetime.date(2020, 3, 24), 'Analize'), (datetime.date(2020, 3, 23), 'Analize'), ] Here is django (2.2) code: sorted(DataSet.objects.values_list('doc_type', flat=True).distinct(), reverse=True) I need to get the last and unique element of each document doc_type together with the date. At the moment I have the same list of documents: ['Raport', 'Document', 'Analize'] but I need: [(datetime.date(2020, 3, 25), 'Raport'), (datetime.date(2020, 3, 25), 'Document'), (datetime.date(2020, 3, 25), 'Analize')] Can someone provide me some hint? Thanks. -
Django View: ConnectionError: HTTPSConnectionPool
I have a django view in a production project: @csrf_exempt def test_view(request): ... Clients who intended to use this endpoint for a redirect says that its not working. I try to test it locally. If I access the url using the browser it works fine but every time I try to access this endpoint in a script locally. I get this error: import requests r = requests.get('http://mywebsite.com/test/?test_run=me') print(r.text, r.status_code) error: File "venv\lib\site-packages\requests\adapters.py", line 516, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPSConnectionPool(host='mywebsite.com', port=443): Max retries exceeded with url: /test/?test_run=me(Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x0000011424D0ABE0>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond',)) Process finished with exit code 1 Any idea of resolving ? -
Linking a model in Django
I have two models LeaveType and MyUser class LeaveType(models.Model): type_ = models.CharField(max_length=50, null=False, blank=False) total_leave_per_year = models.IntegerField(null=False, blank=False, default = 0) def __str__(self): return self.type_ Say, Leave types are: 1. Annual Leave of 20 days per year 2. Sick Leave of 5 days per year class MyUser(models.Model): dob = models.DateField(auto_now_add=True) leave = models.ForeignKey(LeaveType, on_delete=models.CASCADE, related_name="lms_leave_type") Now, When a user apply for an annual for 2 days then his/her remaining leave will be 18 days per year. Now how can I manage this? I have tried to use Inline ways but it does not work for me. Another method I tried is building another model containing user object, leave type object and his/her remaining leaves. Is this a better way or we have another better than this? Thank You. :) -
Order a Django queryset by another dict
So, right now I have this model and a calculated dictionary class User(models.Model): user_id = models.AutoField(primary_key=True) #scores dict {user_id: score} scores = {1: 9, 2: 2, 3: 1, 4: 5} I need to order the queryset based on each user score in the scores dict. Something like this Views.py queryset.annotate(score=scores['user_id']).order_by('score') -
get django rest api Image field url as data to generate QRcode
Im absolute beginner and currently trying to generate qr code so ,how would i get or retrive the url of image field in views.py so that i can add data to make qr code basically the original image is first posted in aws with django rest framework models.py from django.db import models class Picture(models.Model): Original_Image = models.ImageField(upload_to="media/images") QR_Embedded_Image = models.ImageField('QR_Embedded_Image') created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True) urls.py from django.urls import path, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register('App', views.PictureView) urlpatterns = [ path('', include(router.urls)), path('upload-image/', views.UploadImage.as_view(), name="UploadImage"), ] views.py class PicturesView(viewsets.ModelViewSet): queryset = Pictures.objects.all()[:2] serializer_class = PicturesSerializer def create(self, request): image_url = upload_files_to_s3("image.jpeg") qr_code = qrcode.QRCode(box_size=2) qr_code.add_data('image url ') qr_code.make() qr_code_img = qr_code.make_image(fill_color= "#000000" , back_color= "white") qr_code_img.save(' ') -
How to get key-value of context in Django?
I try to query to get all of Topic of Post. Each Post belong multiple Topic. I got this but i don't know how to pass to Template. This is my code. In template i got posts but i can't access topics of single posts. Thank for help. models.py class Post(models.Model): title = models.CharField(unique=True, max_length=121) content = models.TextField() published = models.DateField(default=timezone.now) def __str__(self): return self.title class Topic(models.Model): topic_name = models.CharField(primary_key=True,unique=True, max_length=60) posts = models.ManyToManyField(Post) def __str__(self): return self.topic_name views.py def codinglife(request): posts = Post.objects.filter(topic__topic_name__contains='codinglife') #Get posts belong topic 'codinglife' context = { 'posts': Post.objects.filter(topic__topic_name__contains='codinglife') } # for each post get topic this post belong many topic for post in posts: context[post.id] = Topic.objects.filter(posts=post) return render(request, 'site/topiclistview.html', context) Template {% extends "site/base.html" %} {% block content %} {% for post in posts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <small class="text-muted">{{ post.published }}</small> {% comment 'need to show topic her' %} {% endcomment %} </div> <h2><a class="article-title" href="#">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% endblock content %} -
Django Quiz make it repeatable
I found this via google: https://github.com/sibtc/django-multiple-user-types-example I would like to change this quiz so that a checkbox asks if the quiz may be repeated when creating it. I have added the repeat in the models. class Quiz(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='quizzes') name = models.CharField(max_length=255) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='quizzes') repeat = models.BooleanField(default=False) and also ind the craete and updateview class QuizCreateView(CreateView): model = Quiz fields = ('name', 'subject', 'repeat', ) Now of course I would like the quiz to be repeated. For this purpose I have in the appropriate view: @method_decorator([login_required, student_required], name='dispatch') class QuizListView(ListView): model = Quiz ordering = ('name', ) context_object_name = 'quizzes' template_name = 'classroom/students/quiz_list.html' def get_queryset(self): student = self.request.user.student student_interests = student.interests.values_list('pk', flat=True) taken_quizzes = student.quizzes.values_list('pk', flat=True) queryset = Quiz.objects.filter(subject__in=student_interests) \ #.exclude(pk__in=taken_quizzes) \ .annotate(questions_count=Count('questions')) \ .filter(questions_count__gt=0) return queryset Here I have temporarily removed the corresponding exclude. Then I see the quiz in the list, but unfortunately I cannot call it up again. Now I get the template error: Exception Type: TemplateDoesNotExist Exception Value: students/taken_quiz.html How can I have the quiz repeated now? -
django-pytest error creating test database containing many to many field
I have a model having many to many field like the following. I am using pytest to write unit test cases for it. models.py class CustomerMaster(models.Model): customer_key = models.IntegerField(db_column='CUSTOMER_KEY', primary_key=True) # Field name made lowercase. first_name = models.TextField(db_column='FIRST_NAME', blank=True, null=True) # Field name made lowercase. last_name = models.TextField(db_column='LAST_NAME', blank=True, null=True) # Field name made lowercase. email = models.CharField(db_column='EMAIL', max_length=255, blank=True, null=True) # Field name made lowercase. gender = models.TextField(db_column='GENDER', blank=True, null=True) # Field name made lowercase. dob = models.DateField(db_column='DOB', blank=True, null=True) # Field name made lowercase. phone = models.CharField(db_column='PHONE', max_length=255, blank=True, null=True) # Field name made lowercase. address = models.TextField(db_column='ADDRESS', blank=True, null=True) # Field name made lowercase. ... class Meta: managed = False db_table = 'customer_master' def __str__(self): return self.first_name + self.last_name class Segment(models.Model): name = models.CharField(max_length=100) folder = models.CharField(max_length=100) selection = JSONField() createdAt = models.DateTimeField(null=True) updatedAt = models.DateTimeField(null=True) createdBy = models.ForeignKey(User, on_delete=models.CASCADE, null=True) contact = models.ManyToManyField(CustomerMaster) def __str__(self): return self.name I need to check if only the logged in user is able to acces the view. For that, I am using the @login_required decorator provided by the django itself. For creating a dummy user I am using the following fixture: conftest.py import uuid import pytest @pytest.fixture def test_password(): return … -
Django: Filter object and create for million of records
get_or_create() is just a convenience function, but if i need to have (Filter+create) million of record in a single go?. bulk_create only create objects but not filtering. Can i do it using with transition or rawquery is the only solution? result = Model.objects.filter(field__lookup=value)[0] if not result: result = Model.objects.create(...) return result -
Web Application preferably in Django or Laravel with fingerprint detection
i got a project for school that asked me this stuff: It is a simple web application for fingerprinting users or visitors. Something similar as this one, except that we don't need to check if fingerprint is unique. https://amiunique.org/fp So the app should be modern and should respond to the visitor details of his device (OS, browser, IP address, country, city - this can be done via API /maxmind/... and some other information from device) Here you can use any framework as you want bootstrap or anything else... Design should be simple - in front page should have one button in the middle which says: Scan me or whatever, after clicking all results should appear on the page in organized way. Here is one example of front page: https://fingerprintjs.com/open-source/ The purpose of app is to detect if OS is outdated or browser is not latest version to inform user in some sort of windows. But that we can discuses later. Can you provide me some sources on how can i start this fingerprint thing, i have good knowledge of web developing html css js back-end and front-end, but implementing fingerprint is first time in my life. THANKS!!!! -
Django Model details displayed in the Bootstrap modal
Not sure if this question was asked before, but even that it is, it's out-dated, so pardon my repetition. I'll jump straight to it - I have a datable which is rendered from a complicated cross tabbed query, and it returns like 10 000+ rows, and in the very table I have a "detail" button which triggers a bootstrap modal, and when it opens it just shows some more unique details about the current object, or row. Now, the problem is, when the page where the table is, gets called, it takes so much time to load, it has 20 megabytes, which is a lot, and it takes like 5 seconds depending on the processor because every object gets loaded with his own modal (its happening inside the for loop). My question is, what is the best approach to load the details(bootstrap modal) only when the "details" button gets pressed. I tried something with Ajax, which was confused for me, so I would appreciate every suggestion. Thank you! This is the html of a table : % block content_row %} {% include 'partials/_alerts.html' %} <div class="card-body container-fluid"> {% include 'opportunity/opp_breadcrumb.html' %} <h2 class="-heading" style="margin-left: 50%">OPTIKA</h2> <table class="table table-bordered table table-hover … -
ModuleNotFoundError: No module named 'apidjangowithjwt.emailservice'
Folder Structure of my project where apidjangowithjwt is the project name & emailservice and user are the apps. views.py in user app where I am importing emailservice app which is giving the error Detailed error: File "F:\DjangoDemo\JWTAuthentication\apidjangowithjwt\user\views.py", line 17, in from apidjangowithjwt.emailservice.views import send_email ModuleNotFoundError: No module named 'apidjangowithjwt.emailservice' from apidjangowithjwt.emailservice.views import send_email **#giving error** views.py in emailservice app where I defined a function send_mail. from django.core import mail def send_email(**kwargs): with mail.get_connection() as connection: email=mail.EmailMessage(kwargs['subject'],kwargs['body'],kwargs['from_email'],kwargs['to_email'],kwargs['bcc'], connection,kwargs['attachments'],kwargs['header'],kwargs['bcc'],kwargs['reply_to']) email.send() I have also registerd my both apps in settings.py as: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'user', 'rest_framework', 'emailservice' ] -
FDB connection on Python closes itself
I am using FireBird connector for Python in my django app. I have a single connection per session, in order to minimize the loading times and increase the efficiency, but whenever the connection is being alive for more than 10 minutes, the connection "closes" itself. It's quoted because it doesn't really close itself, the object connection is still alive and the attribute closed of the class is set to False. In this state, whenever you try to execute a query, and fdb.fbcore.DatabaseError is thrown. This is my connector class I use to create a connection: class DBConnector(object): def __init__(self): print("Init Connector") self.host = 'the_host' self.database = 'the_database' self.user = 'the_user' self.password = 'the_super_secret_and_secure_key' self.charset = 'the_most_common_charset' self.dbconn = None def create_connection(self): print("Creating Connection") connection = fdb.connect( host=self.host, database=self.database, user=self.user, password=self.password, charset=self.charset, ) return connection def __enter__(self): self.dbconn = self.create_connection() return self.dbconn def __exit__(self, exc_type, exc_val, exc_tb): self.dbconn.close() When I do con = DBConnector() cursor = con.cursor() cursor.execute(MY_SELECT) It works perfect. Now if i let the connection alive for more than 10 minutes and try again to execute a query: cursor.execute(ANOTHER_SELECT) It throws fdb.fbcore.DatabaseError: Error while preparing SQL statement:\n- SQLCODE: -902\n- Unable to complete network request to host .\n- Error writing … -
DJANGO project admin page not opening
I was making a to do website using Django. And i encountered a weird error. As soon i start my server and type /admin to the url my server gets close. Not able to access the admin page. Any fixes? thanks. PS: my url file doesn't have any error. Image of the terminal : terminal screnshot