Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Using a for loop to view all images from my db - using img src
I am currently learning Django and making my first steps. I try to build a webgallery to learn all the basic stuff. I successfully displayed some images using static files. So I tried saving Images through ImageFields and "upload_to" in my DB, saving it to my static directory. I tried to display everyone of them with a for loop in an tag. My img displays properly with using a {% static %} tag but when I try to insert a {{ }} Tag it isn't working, although it's the same url it doesn't work. I tried changing my STATIC FILE in settings.py I tried various other forms of nesting my {{}} in there Reading the docs to staticfile https://docs.djangoproject.com/en/2.2/howto/static-files/ This thread Display an image located in the database in Django This thread https://docs.djangoproject.com/en/2.2/topics/files/#using-files-in-models My Code: <p>Overview</p> {% block content %} <div> {% for image in images %} {{ image.img_photo }} <!-- webgalleries/test.jpg --> {% load static %} <img src="{% static 'webgalleries/test.jpg' %}" alt="{{ image }}"> <!-- working --> <img src="{% static '{{ image.img_photo }}' %}" alt="{{ image }}"> <!-- not working --> {% empty %} <p>No content</p> {% endfor %} </div> {% endblock content %} I expect the output to … -
In Django does .get() have better performance than .first()?
The Django implementation of .first() seems to get all items into a list and then return the first one. Is .get() more performant ? Surely the database can just return one item, the implementation of .first() seems suboptimal, -
How to pass two arguments between two views in Django?
I am converting a Flask project into Django one. I have a view1 function that takes user input and passes it to a function1 that returns two variables. Variable x is used in query string and passed to view2. However, I also need to pass variable y to view2 for further operations. I Flask application I used expression 'global y' but this does not work in Django. Any ideas, def function1(input): #does something return x,y def view1(request): form = SomeForm() context={'form': form} if request.method == "POST": form = SomeForm(request.POST) if form.is_valid(): input = form.cleaned_data['data_from_user'] # global y --> works only in Flask x,y = function1(input) return redirect("view2", x) # goes to path('<str:x>/', views.my_app, name='view2') return render(request, "my_app/view1.html", context) def view2(request, x): record = SomeTable.objects.filter(y=y).first() context = {'record': record} return render(request, "my_app/view2.html", context) -
Error connecting Google AppEngine Django with SQL 2nd generation instance?
I want migrating my site from First to Second Generation SQL instance, this is the old config: DATABASES['unidades'] = { 'ENGINE': 'google.appengine.ext.django.backends.rdbms', 'INSTANCE': 'tcontur2:posiciones', 'NAME': 'unidades', 'USER': MY_USER, 'PASSWORD': 'MY_PASSWORD', } This works fine, now I trying with this code: DATABASES['unidades'] = { # 2da gen no funciono error COUNT_ROWS 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/tcontur2:us-central1:second-gen-1572540648416', 'NAME': 'unidades', 'USER': MY_USER, 'PASSWORD': MY_PASSWORD } And this code DATABASES['unidades'] = { # 2da gen no funciono error COUNT_ROWS 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/tcontur2:us-central1:second-gen-1572540648416', 'NAME': 'unidades', 'USER': MY_USER, 'PASSWORD': MY_PASSWORD } And this is the error: AttributeError at / 'module' object has no attribute 'FOUND_ROWS' ... /base/alloc/tmpfs/dynamic_runtimes/python27g/79cfdbb680326abd/python27/python27_lib/versions/third_party/django-1.5/django/db/models/query.py in _result_iter self._fill_cache() ... ▶ Local vars /base/alloc/tmpfs/dynamic_runtimes/python27g/79cfdbb680326abd/python27/python27_lib/versions/third_party/django-1.5/django/db/models/query.py in _fill_cache self._result_cache.append(next(self._iter)) ... ▶ Local vars /base/alloc/tmpfs/dynamic_runtimes/python27g/79cfdbb680326abd/python27/python27_lib/versions/third_party/django-1.5/django/db/models/query.py in iterator for row in compiler.results_iter(): ... ▶ Local vars /base/alloc/tmpfs/dynamic_runtimes/python27g/79cfdbb680326abd/python27/python27_lib/versions/third_party/django-1.5/django/db/models/sql/compiler.py in results_iter for rows in self.execute_sql(MULTI): ... ▶ Local vars /base/alloc/tmpfs/dynamic_runtimes/python27g/79cfdbb680326abd/python27/python27_lib/versions/third_party/django-1.5/django/db/models/sql/compiler.py in execute_sql cursor = self.connection.cursor() ... ▼ Local vars Variable Value self <django.db.backends.mysql.compiler.SQLCompiler object at 0x3e7ec68e0890> params (1,) result_type 'multi' sql u'SELECT `posicion_unidades`.`id`, `posicion_unidades`.`empresa`, `posicion_unidades`.`ruta`, `posicion_unidades`.`lado`, `posicion_unidades`.`padron`, `posicion_unidades`.`placa`, `posicion_unidades`.`longitud`, `posicion_unidades`.`latitud`, `posicion_unidades`.`hora`, `posicion_unidades`.`velocidad`, `posicion_unidades`.`direccion`, `posicion_unidades`.`metros`, `posicion_unidades`.`color`, `posicion_unidades`.`frecuencia`, `posicion_unidades`.`estado`, `posicion_unidades`.`ultima`, `posicion_unidades`.`actual`, `posicion_unidades`.`sin_boletaje`, `posicion_unidades`.`con_boletaje`, `posicion_unidades`.`record`, `posicion_unidades`.`volada`, `posicion_unidades`.`control`, `posicion_unidades`.`datero`, `posicion_unidades`.`log`, `posicion_unidades`.`odometro`, `posicion_unidades`.`datero_atras`, `posicion_unidades`.`llamada`, `posicion_unidades`.`emergencia`, `posicion_unidades`.`salio`, `posicion_unidades`.`conectado`, `posicion_unidades`.`fuera`, `posicion_unidades`.`correteo`, `posicion_unidades`.`antena`, `posicion_unidades`.`exceso_velocidad`, `posicion_unidades`.`limite`, `posicion_unidades`.`activo`, `posicion_unidades`.`chofer`, `posicion_unidades`.`ticket` FROM … -
How can I fix a Django ForeignKey error: (adming E202)?
I am creating a project. In models.py I have: from django.db import models from children.models import Child from django.contrib.auth.models import User class OrderLineItem(models.Model): child = models.ForeignKey(Child, null=False, on_delete=models.CASCADE, related_name="child") donation = models.IntegerField(blank=False) def __str__(self): return "{0}-{1}".format(self.donation, self.child.name) class Order(models.Model): full_name = models.ForeignKey(User, blank=False, on_delete=models.CASCADE) phone_number = models.CharField(max_length=20, blank=False) country = models.CharField(max_length=40, blank=False) postcode = models.CharField(max_length=20, blank=True) town_or_city = models.CharField(max_length=40, blank=False) street_address1 = models.CharField(max_length=40, blank=False) street_address2 = models.CharField(max_length=40, blank=True) date = models.DateField() orderlineitem = models.ForeignKey(OrderLineItem, on_delete=models.CASCADE) def __str__(self): return "{0}-{1}-{2}".format(self.id, self.date, self.full_name) However, in the console I get: ERRORS: class 'checkout.admin.OrderLineAdminInline': (admin.E202) 'checkout.OrderLineItem' has no ForeignKey to 'checkout.Order'. How can I fix this? -
Django REST Framework Authentication keyword
I'm trying to rename the Rest_framework TokenAuthentication keyword from "Token" to "Bearer" as suggested in the Documentation I have subclassed the TokenAuthentication class like this: in module: user/authentication.py from rest_framework import authentication class TokenAuthentication(authentication.TokenAuthentication): """ Simple token based authentication. Clients should authenticate by passing the token key in the "Authorization" HTTP header, prepended with the string "Token ". For example: Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a """ keyword = 'Bearer' in module app/settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'user.authentication.TokenAuthentication', ), } It is still sending me a 401 Unauthorized when im using 'Authorization: Bearer ...token...' but not with 'Authorization: Token ...token...' What am I doing wrong ? -
How to properly execute this ajax request with Django?
I made a page with form that has a few fields from a model called EmployeeWorkAreaLog, the first field being where a person enters their Employee #, which is tied to a separate model called Salesman that has all the main data for verification. I made this function get_employee_name(), which returns the name based on the Employee # from the other model, but I'm not sure how to display it in the page, right on the top, without refreshing after the person tabs/clicks out into the next field in the form? I'm not too familiar with html, but I was reading an ajax request would do the trick, but I'm not sure how to approach this. Below you can see what I attempted, but I'm not sure how to handle the success or how to properly insert it into the html. This is basically so the person knows that the Employee # they entered matches their name before proceeding to fill the rest out. views.py class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['adp_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in self.request.POST: form.save() return HttpResponseRedirect(self.request.path_info) elif 'leave_area' in self.request.POST: form.save() … -
django two m2m models
I am quite new to databases as such, and I am trying to figure out how to set up an M2M model with 2 models. So, I have gone through the official docs for m2m and it is pretty clear for the example with Publications and Article`. I completely get it. However, in my use case, I unfortunately have a three way relationship between 3 models like so: Teacher has many students students can have many teachers students can attend many schools Teacher can teach in many schools Where Teachers, Students and Schools are three different models. How does one set up such a model using m2m in django? -
How can to start tasks with celery-beat?
Why i can't run a periodic tasks? proj/settings.py REDIS_HOST = 'localhost' REDIS_PORT = '6379' CELERY_BROKER_URL = 'redis://localhost:6379' BROKER_URL = 'redis://' + REDIS_HOST + ':' + REDIS_PORT CELERY_BEAT_SCHEDULE = { 'task-first': { 'task': 'app.tasks.one', 'schedule': timedelta(seconds=1) }, 'task-second': { 'task': 'app.tasks.two', 'schedule': crontab(minute=0, hour='*/3,10-19') } } proj/celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) proj/__init.py__ from .celery import app as celery_app __all__ = ['celery_app'] celery -A proj worker -l info [2019-10-31 16:57:57,906: INFO/MainProcess] Connected to redis://localhost:6379// [2019-10-31 16:57:57,912: INFO/MainProcess] mingle: searching for neighbors [2019-10-31 16:57:58,927: INFO/MainProcess] mingle: all alone [2019-10-31 16:57:58,951: INFO/MainProcess] celery@lexvel-MS-7A72 ready. Tasks are found celery -A oddsportal beat -l info Configuration -> . broker -> redis://localhost:6379// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%INFO . maxinterval -> 5.00 minutes (300s) [2019-10-31 16:58:02,851: INFO/MainProcess] beat: Starting... The celerybeat.pid and celerybeat-shedule files are created. But besides these lines nothing more is displayed. -
Slow in-memory-backend for email in my Django 2.2 tests
I am using an in-memory-backend for email in my Django 2.2 tests. The documentation mentions: The outbox attribute is created when the first message is sent. It’s a list with an EmailMessage instance for each message that would be sent. This works fine and dandy, but it takes five seconds to initialize this outbox attribute. This basically increases my total test time of the test suite from 1 second to 6 seconds. When sending a second email in another test case in the same run, this occurs instantly, so it must be related to the setting up, but I don't know how to speed this up. Any thoughts? -
In django model what are the pros and cons of setting null=True or blank=True?
In a django model, I usually take the lazy/easy way our to set all my CharFields to both null=True and blank=True. I am going to remove one, but which one is more preferable to keep? I am using MySQL by the way. -
How to use model methods in django templates with class based view
I've defined methods in my model, and I'm trying to use it in django template, which is rendered using ListView My model looks like this: class Book(models.Model): name = models.CharField(max_length=32) price = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) def get_total_sum(self): return super().objects.all().filter(user=self.user).aggregate(models.Sum('price')) My view: from django.views.generic.list import ListView from book.models import Book class BookView(ListView): template_name = 'book.html' # I'm using this to order book by created date def get_queryset(self): return Book.objects.filter(user=self.request.user).order_by('-created_at') And my template: Total books: {{ object_list|length }} Total price of all books: # I've no idea how to display them here, when using class based view -
How to check the diff in two models in django
Suppose I program a "Job" to process the input and give an output. It produces many different objects and be stored in different database tables (12~20 models) I need to diff two jobs output, users may have some modified in the input and leads to the output change. I need to find out which instances are changed in the models. I tried to add the compare() method to each model and use the name to index the instance in two Jobs. (Found=>Compare) class ModelA(models.Model): job_id = models.IntegerField() name = models.CharField(max_length=31) content1 = models.CharField(max_length=128) content2 = models.CharField(max_length=128) content2 = models.CharField(max_length=128) def compare(self, comp) excluded = "id", "job_id" d1, d2 = self.__dict__, comp.__dict__ for k, v in d1.items(): if k in excluded: continue if v != d2[k]: return False return True Most of the models which have a mutual name index may work, I can use the name to find the mutual instance in two jobs and then call the compare() to test the difference. However, in some models, the name is not a very proper way to index two instances since the name is more like an order. So the instance name may shift if new instances are added in the … -
Django: Heroku Failing to launch, at=error code=H10 desc=“App crashed”
Trying to launch my web app for the past 3 days and I keep getting this error. before the app is working perfectly without any error. I view my logs but cannot seem to decipher where the error is coming from or how to begin to debug. I don't even know what to do now because I am really tired. If anyone can help that would be amazing! Thank you! 2019-10-31T15:19:04.996635+00:00 app[web.1]: [2019-10-31 15:19:04 +0000] [11] [INFO] Worker exiting (pid: 11) 2019-10-31T15:19:04.998991+00:00 app[web.1]: [2019-10-31 15:19:04 +0000] [4] [INFO] Handling signal: term 2019-10-31T15:19:05.203657+00:00 app[web.1]: [2019-10-31 15:19:05 +0000] [4] [INFO] Shutting down: Master 2019-10-31T15:19:11.689709+00:00 heroku[web.1]: State changed from starting to up 2019-10-31T15:19:11.608486+00:00 app[web.1]: [2019-10-31 15:19:11 +0000] [4] [INFO] Starting gunicorn 19.9.0 2019-10-31T15:19:11.609129+00:00 app[web.1]: [2019-10-31 15:19:11 +0000] [4] [INFO] Listening at: http://0.0.0.0:49822 ( 4) 2019-10-31T15:19:11.60926+00:00 app[web.1]: [2019-10-31 15:19:11 +0000] [4] [INFO] Using worker: sync 2019-10-31T15:19:11.61345+00:00 app[web.1]: [2019-10-31 15:19:11 +0000] [10] [INFO] Booting worker with pid: 10 2019-10-31T15:19:11.652534+00:00 app[web.1]: [2019-10-31 15:19:11 +0000] [11] [INFO] Booting worker with pid: 11 2019-10-31T15:19:32.839267+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=selmee.he rokuapp.com request_id=c3a5ba3c-b692-4541-a43b-8fdead5e5adc fwd="197.210.84.35" dyno= connect= service= status=503 bytes = protocol=https 2019-10-31T15:29:47+00:00 app[api]: Build started by user musty474izala@gmail.com 2019-10-31T15:30:14.108522+00:00 heroku[web.1]: State changed from up to down 2019-10-31T15:30:12.243748+00:00 … -
Data from django to JS
I have some data on my django views, and I will pass it to my django templates with some variable. Let's supose that I'm giving to my views a list called 'listone', and on the view I created a list on JS, now I want to pass the listone data to the js list, Is this even possible or there are other way to do it? -
Do i need models.py even for ready made mysql databases?
I spin up a django project. Afterwards, i didn't write models.py but instead I created a database from MySQL command line(independent from django) and created three tables with required columns. Finally i connected my django app with that database successfully. I applied migrations. But now i am confused do i need to write models.py with every field name as in column? I remember implementing a basic project in which i did write models.py and created database using "python manage.py shell" and then put values using "from polls.models import Choice, Question"? How do i put data now initially and then using python on some action from UI? -
Ajax Triggered request doesn't update Django View
I tried to break this problem down into the simplest example. When the request is ajax, rendering the page with an updated context doesn't produce the expected result. index.html: <html> <body> {% if templateVariable %} <h1>{{ templateVariable }}</h1> {% endif %} <button id="testBtn">TEST</button> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $(function() { $('#testBtn').click(function(event) { $.ajax({ type: "POST", url: "./", data: { 'x' : 'x', 'csrfmiddlewaretoken' : '{{ csrf_token }}' } }); }); }); }); </script> </body> </html> views.py def index(request): context = {} if 'x' in request.POST: context['templateVariable'] = 'I was updated via ajax' print('ajax ran') return render(request, 'index.html', context) context['templateVariable'] = 'I was not updated via ajax' print('ajax was not run') return render(request, 'index.html', context) When I first load the page, 'ajax was not run' is printed, templateVariable is 'I was not updated via ajax', and the page renders with that in the h1 tag as expected. When I click the testBtn, I expect the ajax request to trigger the if statement, update the context, and render the page with 'I was updated by ajax' in the h1 tag. Instead, 'ajax ran' is printed but templateVariable remains 'I was not updated by ajax' when the page … -
supervisorctl - projworker: ERROR (no such file)
Path to root of project: /home/user/projects/proj /etc/supervisor/conf.d/celery_proj_worker.conf [program:projworker] command=/home/user/.virtualenvs/proj/bin/celery -A proj worker -l info directory=/home/user/projects/proj user=user numprocs=1 autostart=true autorestart=true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=998 -
Is there a way to add models to postgres without deleting all the tables in postgres?
Django I am trying to add a new table/model from Django models to my existing postgres database with tables already but the only solution is to start from scratch again Solution: Delete migrations, delete all the tables in the postgres database. python manage.py makemigrations, python manage.py migrate Error: The table does not exist when browsing the drf api or the postgres database after trying to makemigrations and migrate with the new models. -
Django prefetch_related on ManyToMany(through)
I am attempting to minimize my number of queries on a ManyToMany(through=), but I seem to be causing an n+1 simply by prefetching. Models: class Member(ImmutableModel): organizations = models.ManyToManyField('Organizations', through='MemberOrg', related_name='members') class MemberOrg(ImmutableModel): member = models.ForeignKey('Member', related_name='member_orgs') org = models.ForeignKey('Organization', related_name='member_orgs') class Organization(ImmutableModel): From a clean database, if I setup these models: member = Member.objects.create() org = Organization.objects.create() MemberOrg.objects.create(member=member, org=org) MemberOrg.objects.create(member=member, org=org) Then fetch: Member.objects.all().prefetch_related('member_orgs') I get the following queries: (0.009) SELECT "main_member"."id", (...) FROM "main_member"; args=() (0.010) SELECT "main_memberorg"."id", (...) FROM "main_memberorg" WHERE "main_memberorg"."member_id" IN (1); args=(1,) (0.005) SELECT "main_member"."id", (...) FROM "main_member" WHERE "main_member"."id" = 1; args=(1,) (0.003) SELECT "main_member"."id", (...) FROM "main_member" WHERE "main_member"."id" = 1; args=(1,) I am trying to figure out why I am getting one query of the Member model per MemberOrg. This behavior continues as I add MemberOrg-s. I can't find any mention of this in the docs, and these questions suggest this is how they solved the problem, but it doesn't seem to be working as intended for me. (Note: This is just an example schema - my requirements are more complex and I am tied to this model setup.) Django: 1.9.1 postgres: 9.6 -
In django, how do you create many to many relationshipd between models
Say i have 3 models (Actor, Movie and Series) defined like this: class Actor(models.Model): name = charField... date_of_birth = ... filmography = (list of Series and Movie objects) class Movie(models.Model): name = ... genre = ... cast = (list of Actor objects) class Series(models.Model): name = ... no_of_eps = ... cast = (list of Actor objects) How do i make a many to many relationship between 'actor and movie' and 'actor and series' where actor can store a number of movies and tv shows in its filmography field and movie and series can store a number of actors in there respective cast fields. (Ignore lack of inheritance for movie and series unless it's the only solution) -
ModelForm not creating a new entry in Database
I am trying to get my form to save the responses to the database however a new entry isn't being created in the database when I try to check via the admin section. When I hit the next button the page reloads like it's supposed to and no errors pop up. I deleted the db.sqlite3 file and re-ran the migrations but it still didn't seem to work. The other forms are saving the data to the database. The issue is only with this form. Can you tell me what changes I should make? Thanks in advance views.py def qone(request): if request.method == "GET": global starttime starttime = my_timer() form.save() elif request.method == "POST": form = Question1Form(request.POST) if form.is_valid(): global endtime endtime = my_timer() global timespent1 timespent1 = "{0} seconds".format(endtime - starttime) form.save(commit=True) else: form = Question1Form() form = Question1Form() return render(request,'question1.html',{'form':form}) models.py class Responses(models.Model): question1 = models.TextField() question2 = models.TextField() question3 = models.TextField() timespent1 = models.TimeField(null=False) forms.py class Question1Form(forms.ModelForm): question1 = forms.CharField() timespent1 = forms.TimeField(widget=forms.HiddenInput()) class Meta: model = Responses fields = ('question1','timespent1') html {% extends 'base.html' %} {% block content %} {% load staticfiles %} <div class="container"> <form method="POST"> {% csrf_token %} {{form.as_p}} <input type="Submit" name="" value="Next"> </form> </div> … -
The current path, FOUR/index/{ % url 'four:test' 1 %}, didn't match any of these
My template does not pass parameters and will not report an error, but the parameters will be reported incorrectly, please help me. my urls.py is: from django.urls import re_path from FOUR import views app_name = "four" urlpatterns = [ re_path(r'mmmm', views.mmmm, name='mmmm'), re_path(r'gettime/(?P<year>\d+)/(?P<month>\d+)/(?P<day>\d+)/$', views.gettime, name='gettime'), ] my views.py is : def mmmm(request): return render(request, 'test3.html') def gettime(request, year, day, month): return HttpResponse("time is %s-%s-%s" % (year, month, day)) my html is: <a href="{ % url 'aaa:mmmm' % }">mmmmm</a><br> <a href="{ % url 'gettime' year=2019 month=12 day=18 %}">cmdb/userinfo/tom/tomnickname/10</a><br> mmmmm is OK,cmdb/userinfo/tom/tomnickname/10 The following error will occur enter image description here -
How to fix a lot of duplicates of sql queries in Django admin?
I have a custom user who has only one field added. I installed the django debugger and saw that when creating a user and most likely when changing, a lot of identical requests are created. How to fix it? models.py class CustomUserManager(UserManager): pass class TestUser(AbstractUser): phone = PhoneNumberField(null=False, blank=False, unique=True) email = CharField(unique=True, max_length=35, null=False, blank=False) class Meta: db_table = '"fyzzys"."users"' permissions = [ ("can_see_payments", "payments"), ("can_see_analytics", "analytics"), ("can_see_documents", "documents"), ("can_see_sverka", "sverka"), ("can_see_ways", "ways") ] objects = CustomUserManager() def __str__(self): return self.username admin.py admin.site.register(Permission) class MyUserAdmin(UserAdmin): model = TestUser form = CustomUserChangeForm add_form = CustomUserCreationForm list_display = ('username', 'first_name', 'email', 'phone', 'is_active',) list_filter = (['is_active']) search_fields = () filter_horizontal = (['groups', 'user_permissions']) fieldsets = ( ('Personal info', {'fields': ('first_name', 'email', 'phone', 'password')}), ('permissions', {'fields': ('is_active', 'is_staff', 'user_permissions')}) ) add_fieldsets = UserAdmin.add_fieldsets + ( ('Personal info', {'fields': ('first_name', 'email', 'phone')}), ('permissions', {'fields': ('is_active', 'is_staff', 'user_permissions')}), ) admin.site.register(TestUser, MyUserAdmin) -
Every time that I try to use connection.cursor I get an error
I'm trying to add an script to my project to check the connection to the DB, but every time that I try to use 'connection.cursor()' or 'connection.ensure_connection()' gives me an error. Any idea what could it be. from django.db import connection def snapshot(): try: connection.ensure_connection() except: print('not connected') else: print('connected') snapshot() Traceback (most recent call last): File "Fufillment_Portal/savedb.py", line 82, in <module> snapshot() File "Fufillment_Portal/savedb.py", line 31, in snapshot cursor = connection.cursor() File "/usr/local/lib/python3.7/site-packages/django/db/__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 198, in __getitem__ self.ensure_defaults(alias) File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 166, in ensure_defaults conn = self.databases[alias] File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 147, in databases self._databases = settings.DATABASES File "/usr/local/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/usr/local/lib/python3.7/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.7/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in …