Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use AdminEmailHandler class to send mails to admins with celery task in django?
I'm trying to send a mails to admins with celery by overriding the current AdminEmailHandler class of django from django.utils.log import AdminEmailHandler from celery import shared_task class CeleryAdminEmailHanadler(AdminEmailHandler): @shared_task(bind=True) def celery_send(self,subject, message, *args, **kwargs): super().send_mail(subject, message, *args, **kwargs) def send_mail(self, subject, message, *args, **kwargs): self.celery_send.delay(subject, message, *args, **kwargs) whenever celery_send function run the super().send_mail function getting this error Error('super(type, obj): obj must be an instance or subtype of type') Traceback (most recent call last): File "D:\cmms\env\lib\site-packages\celery\app\trace.py", line 451, in trace_task R = retval = fun(*args, **kwargs) File "D:\cmms\env\lib\site-packages\celery\app\trace.py", line 734, in __protected_call__ return self.run(*args, **kwargs) File "D:\cmms\core\utils\log.py", line 7, in celery_send super().send_mail(subject, message, *args, **kwargs) TypeError: super(type, obj): obj must be an instance or subtype of type I'm using this for logging purposes to send mail to admins on critical errors in the website with celery. -
How to get value by index in jinja2 list?
I am using plotly to make multiple graphs and django framework to present the graph to user. I am storing all the graphs in list, example: all_graphs=[graph1, graph2] I need to show only one graph at a time according to value selected in dropdown in HTML. I am using javascript and jinja2 element for the same. Below is my javascript code: ` function graphshow(s){ var id=Number(s[s.selectedIndex].id); var graph1 = {{ all_graphs.0 | safe}}; Plotly.plot('id_of_div_to_show_graph', graph1, {}); } ` The above code works perfectly but when i replace 0 in line 2 with 'id' which is the index value of graph to be shown the code doesn't work. The value stored in 'id' is correct i've already checked. -
Django using URL parameters in template
I need to redirect to another page with same url parameters so I don't understand how to use url parameters in current template to redirect. dborg.html: {% extends './frame.html' %} {% block content %} <a href="{% url 'create_user' {{orgtype}} {{deg}} %}">Создать нового пользователя</a> {% csrf_token %} {{form}} {% for i in o %} <p><a href='{% url "view_user" i.id %}'>{{i.fld}}</a></p> {% endfor %} {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path('', views.main, name='main'), path('view_org/<str:orgtype>/<str:deg>', views.view_org_db, name='view_org'), path('token/<str:orgtype>/<str:deg>', views.get_token, name='token'), path('token/<str:orgtype>', views.get_token, name='token'), path('create/<str:orgtype>/<str:deg>', views.create_user, name='create_user'), path('search/', views.search_user, name='search_user'), path('report/', views.view_report, name='view_report'), path('view/<int:id>', views.view_user, name='view_user') ] -
How do I get a cloned Django project running?
When I do 'pip install -r requirements.txt', I get this message: python setup.py egg_info did not run successfully I tried python 'python3 -m pip install -U setuptools' but that didn't work. -
Django issue saving data to database
username is saving but information such as first_name, email and etc are not. `from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password from rest_framework import serializers class RegisterSerializer(serializers.ModelSerializer): email = serializers.CharField(required=True) first_name = serializers.CharField(max_length=50, required=True) last_name = serializers.CharField(max_length=50, required=True) password = serializers.CharField( write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) is_admin = serializers.BooleanField(default=False) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password', 'password2', 'is_admin') def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError( {"password": "Password fields didn't match."}) return attrs def create(self, validated_data): user = User.objects.create( username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user` i have searched online for hours, but have not managed to make much progress. if someone could elaborate on my issue and explain what I have done wrong that would be greatly appreciated -
Django - write Python code in an elegant way
I have a situation as shown below: in models.py: class singer(models.Model): name = models.CharField() nickName = models.CharField() numSongs= models.IntegerField() class writer(models.Model): name = models.CharField() numBooks = models.IntegerField() class weeklyTimeSinger(models.Model): singerID = models.ForeignKey(singer, on_delete = models.CASCADE, related_name = 'hook1') dayWeek = models.IntegerField() startHour = models.TimeField() stopHour = models.TimeField() class weeklyTimeWriter(models.Model): writerID = models.ForeignKey(writer, on_delete = models.CASCADE, related_name = 'hook2') dayWeek = models.IntegerField() startHour = models.TimeField() stopHour = models.TimeField() in view.py: class Filters(APIView): def queryFilter(self, querySet, request, singerOtWriter): param1 = int(request.GET.get('param1', 0)) param2 = int(request.GET.get('param2', 0)) if singerOtWriter == "singer": querySet = querySet.filter(weeklyTimeSinger_dayWeek=param1) querySet = querySet.filter(weeklyTimeSinger_startHour__lt=param2) querySet = querySet.update(..... ....a lot of operation on querySet else if singerOtWriter == "writer": querySet = querySet.filter(weeklyTimeWriter_dayWeek=param1) querySet = querySet.filter(weeklyTimeWriter_startHour__lt=param2) querySet = querySet.update(..... ....a lot of operation on querySet, the same of the case singer return querySet class Artist(Filters): def get(self, request): querySetSinger = singer.objects.all().annotate(numWorks= F('numSongs')) querySetSinger = self.queryFilter(querySetSinger , request, "singer") querySetSinger = querySetSinger.values('name', 'numWorks') querySetWriter = writer.objects.all().annotate(numWorks= F('numBooks')) querySetWriter = self.queryFilter(querySetWriter , request, "writer") querySetWriter = querySetWriter.values('name', 'numWorks') values = querySetSinger.union(querySetWriter) serialized = ArtistSerializers(values, many = True) return Response(serialized.data) In queryFilter function I have 2 different flows depending on singerOtWriter parameter. The 2 flows are long and identical execpt for "weeklyTimeWriter" or "weeklyTimeSinger" tables … -
Django complexity of one-to-one field reverse lookup
Reverse lookup of foreign key fields takes log(n) time as stated in this question. complexity of a reverse django foreign key lookup What is the complexity of reverse lookup of one-to-one field? -
Duplicate object with django-hitcount
I want to duplicate my current object with its values. So, I need to copy all of its old values to the new object. Duplication of all old values I implemented well, but I can't make hits (views) that are created with django-hitcount. I tried to do different options, but it doesn't work. Could you please give me advice on how to build it? models.py class Blog(models.Model, HitCountMixin): slug = models.SlugField() name = models.CharField() author = models.ForeignKey( "users.CustomUser", on_delete=models.SET_NULL, null=True, blank=True, ) content = models.TextField(blank=True, null=True) bookmarkscount = models.IntegerField(null=True, blank=True, default=0) downloadscount = models.IntegerField(null=True, blank=True, default=0) hit_count_generic = GenericRelation( HitCount, object_id_field="object_pk", related_query_name="hit_count_generic_relation", ) hitcount.models.py from datetime import timedelta from django.db import models from django.conf import settings from django.db.models import F from django.utils import timezone from django.dispatch import receiver from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.utils.translation import gettext_lazy as _ from etc.toolbox import get_model_class_from_string AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') from .managers import HitCountManager, HitManager from .settings import MODEL_HITCOUNT from .signals import delete_hit_count @receiver(delete_hit_count) def delete_hit_count_handler(sender, instance, save_hitcount=False, **kwargs): """ Custom callback for the Hit.delete() method. Hit.delete(): removes the hit from the associated HitCount object. Hit.delete(save_hitcount=True): preserves the hit for the associated HitCount object. """ if not save_hitcount: instance.hitcount.decrease() … -
Missing 'path' argument in get() call
I am trying to test my views in Django, and when I run this i get the error from django.test import TestCase, Client from django.urls import reverse from foodsystem_app.models import discount,menu import json class TestViews(TestCase): def test_login_GET(self): client = Client response = client.get(reverse('login')) self.assertEquals(response.status_code,200) self.assertTemplateUsed(response,'foodsystem/login.html') response = client.get(reverse('login')) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: Client.get() missing 1 required positional argument: 'path' ---------------------------------------------------------------------- Ran 4 tests in 0.005s FAILED (errors=1) I'm not sure what I am supposed to pass as the path name. This is the code for what I am testing def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}.") return redirect("main:homepage") else: messages.error(request,"Invalid username or password.") else: messages.error(request,"Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="login.html", context={"login_form":form}) -
Getting (2006, 'MySQL server has gone away error) in kafka consumer in my django application
I recently written a kafka consumer in my django project which is running in the background and there's a mysql query which reads inside the consumer and the process is very light as I don't have that much of data. But I'm getting (2006, 'MySQL server has gone away) and I'm not getting why exactly it's happening and what's the solution for this? Any leads or solution for this would be highly appreciated. The below is my code:- `def job_listener(): listener = KafkaConsumer(topic, group_id=group_id, bootstrap_servers=settings.KAFKA_BOOTSTRAP_SERVERS, auto_offset_reset=settings.KAFKA_AUTO_OFFSET_RESET, enable_auto_commit=settings.KAFKA_ENABLE_AUTO_COMMIT) for message in listener: try: data = json.loads(message.value) logger.info("Data Received {}".format(data)) except Exception as e: data = None logger.error("Failed to parse the message with exception {}".format(e)) if data is not None: try: Job.objects.get(pk=data['id'] except ObjectDoesNotExist: logger.error("Keyword doesn't exist with data {}".format(data)) listener.commit({TopicPartition(topic, message.partition): OffsetAndMetadata(message.offset+1, '')}) except Exception as e: logger.error( "Failed to read data {} with exception {}".format(data, e)) listener.seek(TopicPartition(topic, message.partition), message.offset)` -
how to pass a context variable from a variable inside of an if statement?
Inside of an if statement I've check_order that I need to have as a context variable for my template, I'm getting this traceback: local variable 'check_order' referenced before assignment. How do I have it as a context variable without having to repeat the code to have it outside of the if statement? View if request.method == "POST": if request.user.is_authenticated: customer = request.user.customer check_order = OrderItem.objects.filter(order__customer=customer) if check_order: if form.is_valid(): #does logic else: messages.error(request, f"Failed") else: return redirect() context = {"check_order": check_order} -
Specific User permissions in Django
I need to make only TL and HR approve permissions for leave. how to achieve it in Django Rest framework? since am a newbie i find this scenario challenging. Help me out Techies This is my User model class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=150, unique=True) name = models.CharField(max_length=150, blank=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_HR = models.BooleanField(default=False) is_TL = models.BooleanField(default=False) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) This is my leave request model. class Leave(models.Model): leave_type = models.CharField(max_length=50) employee = models.ForeignKey(UserDetails, on_delete=models.CASCADE) manager = models.CharField(max_length=50) applied_on = DateTimeField(auto_now_add=True) from_date = DateField() to_date = DateField() number_of_days = IntegerField() purpose = models.CharField(max_length=100) status = models.CharField(max_length=50, choices=( ('Pending', 'Pending'), ('Approved', 'Approved'), ('Rejected', 'Rejected') ),default='Pending') waiting_approval = models.BooleanField(default=True) TL_approved = models.BooleanField(default=False) TL_rejected = models.BooleanField(default=False) def approve(self): self.manager_approved = not self.manager_approved self.manager_rejected = not self.manager_rejected This is my views class LeaveManagerApproveView(APIView): def post(self, request): leave_id = request.data.get('leave_id') leave = Leave.objects.get(id=leave_id) leave.waiting_approval = False leave.manager_approved = True leave.status = 'Approved' leave.save() return Response({'successMessage': 'Leave Approved Successfully'}) In my views, i need only Hr or TL should approve or reject it? How to rock it? -
Django - Plesk - Centos7 - Apache
I have a rest-django project. The project uses plesk panel, centos 7 and apache. When I run my project, I get a python error. my site api.iyziwell.com print: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'iyziwell.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if name == 'main': main() Please help me. -
Unable to load the custom template tags in django
templatetags : myapp_extras.py from django import template register = template.Library() @register.simple_tag def my_url(value,field_name,urlencode=None): url = '?{}={}'.format(field_name,value) if urlencode: querystring = urlencode.split('&') filtered_querystring = filter(lambda p:p.split('=')[0]!=field_name,querystring) encoded_querystring = '&'.join(filtered_querystring) url = '{}&{}'.format(url,encoded_querystring) return url home.html {% load myapp_extras %} . . . <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a href="{% my_url 1 'page' request.GET.urlencode%}">&laquo; first</a> <a href="{% my_url page_obj.previous_page_number 'page' request.GET.urlencode%}">previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="{% my_url page_obj.next_page_number 'page' request.GET.urlencode%}">next</a> <a href="{% my_url page_obj.paginator.num_pages 'page' request.GET.urlencode%}">last &raquo;</a> {% endif %} </span> </div> settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'facligoapp' ] views.py def do_paginator(get_records_by_date,request): paginator = Paginator(get_records_by_date,10) page_number = request.GET.get('page', 1) try: page_obj = paginator.get_page(page_number) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) return page_obj : : if new_records_check_box_status is None and error_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)) get_records_by_date = check_drop_down_status(get_records_by_date,drop_down_status) get_records_by_date = do_paginator(get_records_by_date,request) Based on the my templates tags when I filter the datas the url should change. But the url is not changing and template tags is not working. I had created the init.py in template tags also. Is there any solution to change the structure … -
Djagno User token is not passed in HTTP request header:-
I have created a login api using token based authentication in django rest framework.....API works fine in local setup.....But after committing the code on live server. Login done successfully but after passing that login token in headers. user is not permissible to open the next page. Here is my code:- 1) Login function @api_view(["POST"]) @permission_classes((AllowAny,)) def login(request): account = request.data.get("account") username = request.data.get("username") password = request.data.get("password") all_subs = [] for i in Subscriber.objects.all(): all_subs.append(i.username) if account in all_subs: connect_to_db(database=account) set_db_connection(account) try: if '@' in username: user = User.objects.using(account).get(email=username) else: user = User.objects.using(account).get(username=username) except: return Response({'error':'Invalid Credential'}, status=HTTP_400_BAD_REQUEST) if user.check_password(password): token, _ = Token.objects.using(account).get_or_create(user=user) user_data = User.objects.using(account).get(id=token.user_id) serializer = UserSerializer(user_data) return Response({'data': serializer.data,'token': token.key}, status=HTTP_200_OK) else: return Response({'error':'Invalid Credential'}, status=HTTP_400_BAD_REQUEST) elif account == "enggforms": try: if '@' in username: user = User.objects.get(email=username) else: user = User.objects.get(username=username) except: return Response({'error':'Invalid Credential'}, status=HTTP_400_BAD_REQUEST) if user.check_password(password): token, _ = Token.objects.get_or_create(user=user) user_data = User.objects.get(id=token.user_id) serializer = UserSerializer(user_data) return Response({'data': serializer.data,'token': token.key}, status=HTTP_200_OK) else: return Response({'error':'Invalid Credential'}, status=HTTP_400_BAD_REQUEST) else: return Response({'error':'Invalid Credential'}, status=HTTP_400_BAD_REQUEST) if username is None : return Response({'error': 'Please provide username'}, status=HTTP_400_BAD_REQUEST) elif password is None: return Response({'error': 'Please provide password'}, status=HTTP_400_BAD_REQUEST) elif account is None: return Response({'error': 'Please provide account name'}, status=HTTP_400_BAD_REQUEST) if … -
Django - AppRegistryNotReady("Models aren't loaded yet.") using cities_light library
I have installed the cities_light library in Django and populated the db with the cities as instructed in the docs. I added the app in INSTALLED_APPS and I have been able to pull the data in this simple view. All cities load as expected: def index(request): cities = City.objects.all() context = { 'cities': cities } return render(request,'templates/index.html',context) However, I am trying to create a model which has City as a foreign key, but when I run the app or try to make the migrations I get 'django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.'. from cities_light.admin import City from django.db import models class Home(models.Model): location = models.ForeignKey(City, on_delete=models.CASCADE) I suspect I might need to override the model. Would that be the case? -
How to Display the data on webpage with a search option (search by valid resource number) and use below API details for data fetching
API Details: API Reference:* https://stat.ripe.net/docs/02.data-api/announced-prefixes.html* Method: GET Origin Url: https://stat.ripe.net/data/announced-prefixes/data.json?resource= Example URL: https://stat.ripe.net/data/announced- prefixes/data.json?resource=4007 Note: The bold value will be the user’s input from the search field. Data Output format in webpage: (https://i.stack.imgur.com/x7Qsk.png) Some valid resources number (ASN) are as below. 4007 17501 9238 141177 23752 By using python/django framework please help me. I have no knowledge about how to fetch data using API. -
Django session variable change in UI everytime when new request_id is created
I want to request id differ in every page data, same as request id is in available in approve_url . index function send session variable approve_url in test function. Here is index function global j, k, approve_url @api_view(['POST', 'GET']) def index(request): # j = '' # approve_url = '' if request.method == "POST": form = InputForm(request.POST) if form.is_valid(): form.save() try: ids = form.cleaned_data['git_Id'] print(ids) obj = sql() query = f""" SELECT request_id FROM request_form_db.request_form_mymodel where git_Id= '{ids}' ; """ print(query) p = obj.fetch_query(query) print("Query Result", p) for i in p: print("Result[0] : ", i[0]) print("Result : ", p) i = i[0] j = i approve_url = f"http://127.0.0.1:8000/form/test?request_id={i}" print("Url : ", approve_url) try: send_mail( 'KSA Test Activation', approve_url, 'Noreplygcontrol@airlinq.com', ['sorav.parmar@airlinq.com'], fail_silently=False, ) except Exception as e: print("Error : ", e) except Exception as e: print("Error : ", e) request.session['ids'] = ids request.session['approve_url'] = approve_url print('Request ID Sent : ', ids) print('Approve Url Sent : ', approve_url) form = InputForm() else: form = InputForm() return render(request, 'home.html', {'form': form}) Here is test function where approve_url getting from session variable and put into UI, but res value change in previous data as well.Its not same as request_id in approve_url. the latest request id … -
Django makemigrations in production?
I'm new to Django but one concern I'm running into is whether running makemigrations as part of the production deployment process is safe/deterministic? The main reason is some 3rd party apps will create new migrations beyond the pre-defined ones, i.e. hordak for example, when a new currency is added via CURRENCIES in settings.py. Since a currency can be added anytime later and these are part of an 3rd party app the migrations are not checked in to the repo. This requires makemigrations to be run on deploy? This seems dangerous since there will be untraceable changes to the DB? Is a way to explicitly check-in to the repo 3rd party migrations? -
Css static in html use django, css no show out
main.html add {% load static %} at top and {% static 'css/main.css' %} in link css href {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CM1</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <link rel="stylesheet" type="test/css" href="{% static 'css/main.css' %}"> </head> <body> {% include "accounts/navbar.html" %} {% block content %} {% endblock content %} <hr> <h5>Our footer</h5> </body> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> </html> **setting.py code so longer, i just skip to important things, the STATICFILES_DIRS bracket is () or [] ** import os INSTALLED_APPS = [ ... 'django.contrib.staticfiles', #<-- already have ... ] STATIC_URL = 'static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static/"), ) -
Django/Python - AssertionError: Class ThreadSerializer missing "Meta.model" attribute
Blockquote I've been trying to build the backend of a forum board for a mobile application and I've been running into an issue when trying to test the API endpoints over Postman. It says that the my ThreadSerializer class is missing the "Meta.model" attribute. My serializer code ` from rest_framework import serializers from forum.models import Thread from forum.models import Post class ThreadSerializer(serializers.ModelSerializer): class Meta: Thread_Model = Thread Thread_Fields = ['id', 'thread_id', 'title', 'desc', 'created_at'] class PostSerializer(serializers.ModelSerializer): class Meta: Post_Model = Post Post_Fields = ['id', 'post_id', 'post_content', 'post_time', 'thread_id'] Model code --- from django.db import models from django.conf import settings from Authentication.models import User # Create your models here. class Thread(models.Model): userid = models.ForeignKey(User, on_delete=models.CASCADE) thread_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() created_at = models.DateTimeField(auto_now_add=True) class Post(models.Model): userid = models.ForeignKey(User, on_delete=models.CASCADE) thread_id = models.ForeignKey(Thread, on_delete=models.CASCADE) post_id = models.AutoField(primary_key=True) post_content = models.TextField() post_time = models.DateTimeField(auto_now_add=True) ` Any advice on how to fix this? This is the error I got on VSC and Postman. -
Django test connection strings with django-environ
At the moment we are using django-environ to store a database connection string. We are using mssql-django to connect to a Microsoft SQL Server database. Test database connection strings require more parameters - so is there a simple way to store an entire connection for a particular environment - ala test? Or perhaps a better approach? Project Code This project uses the django-environ to load a connection string from a .env file for a particular environment within a single settings.py file. This is specified by environment setting ENVIRONMENT_FILE. environments/dev.env DATABASE_URL=mssql://localhost:1433/ACME_APP_DB settings.py import environ environ.Env.DB_SCHEMES['mssql'] = 'mssql' env = environ.Env( DEBUG=(bool, False) ) BASE_DIR = Path(__file__).resolve().parent.parent ENVIRONMENT_DIR = os.path.join(BASE_DIR, "environments") ENVIRONMENT_FILE = os.environ.get("ENVIRONMENT_FILE", default=".env") ENVIRONMENT_FILE_FULL_PATH = os.path.join(ENVIRONMENT_DIR, ENVIRONMENT_FILE) root = environ.Path(__file__) - 3 environ.Env.read_env(ENVIRONMENT_FILE_FULL_PATH) env = environ.Env() DATABASES = { "default": env.db_url(), } This allows us to specify the environment for either dev or prod. We don't have any tests at the moment. Having investigated this - the alternative below allows a test database to be used when running tests against a database. Alternative This was an alternative investigation I did. We want a finer control including the driver and test database we need to specify further information. Settings Base This … -
psql: error: connection to server at "localhost"
Let me first mention I don't have admin privilege on my PC, So I could not install PostgreSQL with the normal process. I just download the binary files from here enterprisedb.com/download-postgresql-binaries, and added it to environment variable paths. My problem when I try to start a new server from pgAdmin it gives me the below error. connection to server at "localhost" (::1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? I searched a lot for a solution The first recommendation I got is to restart postgress from windows services but I couldn't find it. Second recommendation was to edit the psogress config file but also I can't find it at all they say that I can find it in the main directory of postgress. -
complex filters method in django
I am stuck with a problem where I need to send remainder emails to all users whos training is expiring in some period of time like ratio of 5/6. I have setup a scheduling system it will be filter all training programs who are expiring everyday and send them remainders. The problem I am facing is I am unable to figure out the query. This is the model I am using: class Training(models.Model): class Meta: ordering = ('-pk',) uuid = models.UUIDField(default=uuid.uuid4, editable=False) customer = models.ForeignKey('customer.Customer', on_delete=models.CASCADE, related_name='trainings') name = models.CharField(max_length=512) presentation = models.FileField(upload_to='trainings') data = models.JSONField() description = models.TextField(default='', blank=True) released = models.BooleanField(default=False) start_at = models.DateField() end_at = models.DateField() codes_file = models.FileField(null=True, max_length=1024) contact = models.EmailField(blank=True) is_archived = models.BooleanField(default=False) is_reminded = models.BooleanField(default=False) This is the query I am trying to run. trainings = Training.objects.filter(is_reminded=False, ).annotate( deadline=(datetime.today() - F('start_at')).days / (F('start_at') - F('end_at')).days, output_field=DateField() ).filter(deadline__gt=0.833) Error I am getting from this. I understand why this error is coming but I cannot figure out how to pull this data out. Internal Server Error: /testing/ Traceback (most recent call last): File "C:\Users\HP\.virtualenvs\apaa_backend-tCJa5vIy\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\HP\.virtualenvs\apaa_backend-tCJa5vIy\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\HP\.virtualenvs\apaa_backend-tCJa5vIy\lib\site-packages\django\views\decorators\csrf.py", line … -
Is querying reverse foreign keys lazy?
I need to check if user has at least one connected product of many types that we have in a system. I'm trying to make it more efficient so I added any() and made a generator for connection check. But I wonder if it still will query all reverse relationships and evaluate them. User can have a lot of products of each type. My code: def has_connected_product(self): def check_product_set_on_connected(product_sets): for product_set in product_sets: if product_set.model.__name__ == 'ShopifyProduct': yield product_set.exclude(shopify_id__isnull=True).exclude(shopify_id=0).exists() else: yield product_set.exclude(source_id__isnull=True).exclude(source_id=0).exists() return any(check_product_set_on_connected([ self.user.shopifyproduct_set, self.user.commercehqproduct_set, self.user.wooproduct_set, self.user.ebayproduct_set, self.user.fbproduct_set, self.user.googleproduct_set, self.user.gearbubbleproduct_set, self.user.groovekartproduct_set, self.user.bigcommerceproduct_set, ]))