Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to calculate the average duration/timedelta per date?
I have the following QuerySet: {'duration': datetime.timedelta(seconds=212), 'date': datetime.datetime(2022, 1, 17, 0, 0, tzinfo=<UTC>), 'count': 1} {'duration': datetime.timedelta(seconds=9), 'date': datetime.datetime(2022, 1, 17, 0, 0, tzinfo=<UTC>), 'count': 1} {'duration': datetime.timedelta(seconds=19), 'date': datetime.datetime(2022, 1, 17, 0, 0, tzinfo=<UTC>), 'count': 1} {'duration': datetime.timedelta(seconds=20), 'date': datetime.datetime(2022, 1, 17, 0, 0, tzinfo=<UTC>), 'count': 1} {'duration': datetime.timedelta(days=2, seconds=4681), 'date': datetime.datetime(2022, 2, 7, 0, 0, tzinfo=<UTC>), 'count': 1} {'duration': datetime.timedelta(seconds=1114), 'date': datetime.datetime(2022, 2, 7, 0, 0, tzinfo=<UTC>), 'count': 1} {'duration': datetime.timedelta(seconds=1683), 'date': datetime.datetime(2022, 2, 7, 0, 0, tzinfo=<UTC>), 'count': 1} and would like to calculate the average duration for each date, so for the above QS I'd get the following result: Duration Date 65 2022/01/17 60,092.67 2022/02/07 I tried to apply the Count function over the date so I can then divide the duration over the day's total, as following: qs.annotate(week_total=Count('date')) but it didn't work as the date itself is an aggregate and I get this error: FieldError: Cannot compute Count('date'): 'date' is an aggregate So after many attempts I'm out of ideas to try and I'd appreciate any tips. -
Django 404 error-page not found & No CSS renders
New-ish coder and first time stack overflow poster. I've made a django project with 3 pages. Sometimes no pages are found, sometimes the index page loads without 404 error but I can't link to other pages and the css files I've pointed it to doesn't render. Errors I'm getting is: 404 error I have slept on the problem, looked up file formats to make sure my project and app url.py is correct. added app to settings. imported correct classes. I have also tried clearing my browser data on chrome and using a different browser. If anyone could take a look at my small project on github that would be amazing. https://github.com/Connell-L/portfolio_website is the link or if anyone wants me to post code files on codepen or something I'm more than happy to do it. -
consumer:Cannot connect to amqp://guest:**@192.168.3.100%3A6379:5672//: failed to resolve broker hostname
Please Help. enter image description here -
How to apply condition in boolean field in django rest framework?
I am working on a blog type website. where students will ask question and teacher will answer it. I put two user role Teacher and student class User(AbstractBaseUser, PermissionsMixin): USER_TYPE = ( ('None', 'None'), ('Student', 'Student'), ('Teacher', 'Teacher'), ) user_type = models.CharField(choices=USER_TYPE, default='Student', max_length=50) This is the user model where the role is defined. Post model for submitting the question and Comment model for answering it. In the Post model I put on field is_answered and as default put it False class add_question(models.Model): created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE) is_answered = models.BooleanField(default=False) And the answer model [which is comment one] is referred to as the foreign key of the question class submit_answer(models.Model): question_id = models.ForeignKey( add_question, blank=False, on_delete=models.CASCADE) created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE) Both question and answer model contains created_by field and ForeignKey of User and answer model contains another ForeignKey of question. so I need when the teacher role will put a comment the is_answered Field in add_question model should turn as true. as student also can comment on his/er question so I need on condition to apply. I am using serializer as I need API of this So, should I modify on my views.py or serializers.py and how should … -
Django 4 how to do annotation over boolean field queryset?
I found this discussion about annotation over querysets. I wonder, if that ever got implemented? When I run the following annotation: x = Isolate.objects.all().annotate(sum_shipped=Sum('shipped')) x[0].sum_shipped >>> True shipped is a boolean field, so I would expect here the number of instances where shipped is set to True. Instead, I get True or 1. That is pretty inconvenient behaviour. There is also this discussion on stackoverflow. However, this only covers django 1. Seems this was not touched since then. Is that discussion in the second link still the state-of-the-art ??? Is there a better way to do statistics with the content of the database than this, now that Django is in version 4? My current database is sqlite3 for development and testing, but will be Postgres in production. I would very much like to get database independent results. SUM(bool_field) on Oracle will return 1 also, because bools in Oracle are just a bit (1 or 0). Postgres has a specific bool type, and you can't sum a True/False without an implicit conversion to int. This is why I say SUM(bool) is only accidentally supported for a subset of databases. The field type that is returned is based on the backend get_db_converters … -
Why Isn't My NodeJS Post Request Working? (From Django)
I am trying to send a request that I'm receiving in my Django view to my expressjs api on the same server and I am either getting 500 errors or empty response bodies on the express end. Here is my express.js code: var express = require('express'); var fs = require('file-saver'); var app = express(); var multer = require('multer'); var upload = multer({ dest: 'json/' }); const router = express.Router(); const bodyParser = require('body-parser'); //app.use(express.static('public')); app.use(bodyParser.urlencoded({ extended: true })); app.get('/example', function (req, res) { res.send('Hello World!'); }); app.post('/example', async (req, res) => { await fs.saveAs(req.body, 'json.json'); await console.log('Got body:', req.body); await res.sendStatus(200); }); app.listen('8080', function () { console.log('Test'); }); Here is my django view: from django.http import HttpResponse from django.core.mail import EmailMessage, send_mail from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from django.http import FileResponse from rest_framework.decorators import api_view import json from reportsappapi.utilities import logip import requests @method_decorator(csrf_exempt, name='dispatch') @api_view(['GET', 'POST']) def sendMail(request): url = 'https://example.com/example' clockout = request.FILES['clockout'] clockoutJSON = json.load(clockout) x = request.post(url, clockout) return HttpResponse(status=204) -
string index out of range? in django post request
I'm getting error string index out of range when I getting simple text from post request and want to show data in array. [["daveen brewster 218 tokay drive \u25aa fayetteville nc 28301 \u25aa 910 527 2739 email divineb79@gmail.com professional profile customer service orient professional with healthcare industry experience accustom to work in environment where accuracy and accountability be essential consistently model and inspire high level of integrity follow policy procedure and guideline to assure consistent quality \u25aa \u25aa \u25aa adaptable adapt to change situation and expectation and accept new idea and concept time management manage time and priority to meet goal deadline and objective problem solver identify and define a problem generate solution and determine appropriate strategy microsoft office application word excel outlook and powerpoint key qualification medical administrative assistant \u25aa medical terminology \u25aa medical transcription patient processing \u25aa patient registration \u25aa medical record management \u25aa check in \u25aa check out \u25aa datum entry release of information \u25aa hipaa compliance \u25aa medical law ethic \u25aa cms 1500 claim form \u25aa billing cycle claim appeal process \u25aa medical billing knowledge \u25aa third party billing \u25aa medicare \u25aa medicaid \u25aa hmo \u25aa ppo basic code skill for icd-10 cpt \u25aa insurance verification … -
Google Api Calendar Store Refresh Token for individuals
How would I store the refresh token from google api calendar and use it to access a user's calendar events. I tried using the python quickstart but it won't work. It always does a redirect url mismatch I need to figure how to add the refresh token to the model. login page: So currently from the login it associates a social account to a user and redirects correctly pass the login. AUTH_USER_MODEL = 'pages.Profile' SOCIAL_AUTH_USER_MODEL = 'pages.Profile' # social auth configs for google SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config('GOOGLE_OAUTH2_KEY') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config('GOOGLE_OAUTH2_SECRET') SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['https://www.googleapis.com/auth/calendar'] SOCIAL_AUTH_JSONFIELD_ENABLED = True SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = {'access_type': 'offline',} SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', # <--- enable this one 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) LOGIN_URL = 'login' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' Now in this section which has another url I would like to use the access token to show all the user's events. Not sure how I would use the access token. @login_required def calendar(request): context={} context['access_token']= get_access_token(request) results=get_events(request) context['results'] = results context['nmenu'] = 'calendar' return render(request, 'home.html', context) def get_access_token(request): social = request.user.social_auth.get(provider='google-oauth2') return social.extra_data['access_token'] -
Django model field custom validator returned value not saved
I have the following implementation for the phone number custom validation. It does the validation correctly, but the returned value (formatted) is not saved in the model instance. I don't use a custom form and data is entered from admin panel. custom validator def phone_number_validator(value): if value: value = value.strip() value = value.replace(' ', '') digits = [] non_digits = [] for c in value: if c.isdigit(): digits.append(c) else: non_digits.append(c) if len(non_digits): raise ValidationError('Only numbers and spaces are allowed for this field.') elif len(digits) < 10 or len(digits) > 10: raise ValidationError('Phone number should be exactly 10 digits.') elif (not value.startswith('07')) and (not value.startswith('0')): raise ValidationError('Invalid phone number.') if value.startswith('07'): # mobile number value = f'{value[0:3]} {value[3:6]} {value[6:]}' elif value.startswith('0'): # landline value = f'{value[0:3]} {value[3:4]} {value[4:7]} {value[7:]}' print(value) #### here the correct format is displayed return value models.py hotline = models.CharField(max_length=PHONE_NUMBER_LENGTH, validators=[phone_number_validator]) -
Django error showing none type when it isn't none when calling a function
can any one explain why the following error occurs AttributeError: 'NoneType' object has no attribute 'check_data' the error occurs when i tried to call "passdata = self.check_data(request)" method can any one explain why it occurs were iam going wrong class UpdateRepo: def update_marks(self,request): passdata = self.check_data(request) get_values = Marks.objects.filter(id=request.data['id']) if get_values.exists(): thr = get_values.update( English = passdata[0], Tamil = passdata[1], Maths = passdata[2] ) return thr def check_data(self,request): if int(request.data['English']) >50: English = request.data['English'] else: English = constants.Marks['English'] if int(request.data['Tamil']) >50: Tamil = request.data['Tamil'] else: Tamil = constants.Marks['Tamil'] if int(request.data['Maths']) >50: Maths = request.data['Maths'] else: Maths = constants.Marks['Maths'] return [English,Tamil,Maths] -
Django OAuth Google
I tried to import urlpatterns like this on project/urls.py. from allauth.socialaccount.providers.google.urls import urlpatterns as google_url But Django didn't seem to recognize that by underlining that code. shows underlining I don't have any clue. Applicable settings.py INSTALLED_APP here. 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', and others in settings.py here, SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email' ], 'AUTH_PARAMS': { 'access_type': 'online', } } } The path of project/urls.py below works. path('oauth_accounts/', include('allauth.urls')), But the next path of project/urls.py didn't work when I tried. path('oauth_accounts/', include(google_url)), result I am taking a Django tutorial, so I tried to execute the latter. Thanks in advance. -
My user roles returns either list index out of range or takes me back to log in even though the right role is logged in
I have created user roles within my Django application and have designated users their roles within the admin interface but when I log in an try to access the restricted access page using the correct role I am either returned to the log in page or met with a list index out of range error and I am very confused to as why this is. Models.py from pickle import TRUE from django.db import models from django.contrib.auth.models import User from django.template.defaultfilters import slugify from django.urls import reverse from django.utils import timezone ROLES = ( ('0','Researcher'), ('1','Clinician'), ('2','Superuser'), ) class UserProfile(models.Model): # This line is required. Links UserProfile to a User model instance. user = models.OneToOneField(User, on_delete=models.CASCADE) # The additional attributes we wish to include. picture = models.ImageField(upload_to='profile_images', default='default/default.jpg', blank=True) role = models.CharField(max_length=1000, choices=ROLES, default='0') is_active = models.IntegerField(default = 1, blank = True, null = True, help_text ='1->Active, 0->Inactive', choices =( (1, 'Active'), (0, 'Inactive') )) created_on = models.DateTimeField(default = timezone.now) updated_on = models.DateTimeField(default = timezone.now, null = True, blank = True ) Views.py from django.shortcuts import render, redirect from django.urls import reverse from django.http import HttpResponse from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib import messages from … -
Django REST Framework Authentication Tests Failing: rest_framework.request.WrappedAttributeError: 'HasAPIKey' object has no attribute 'authenticate'
I have some test cases in Django REST Framework to check user login and registration endpoints. I am currently in the process of configuring an API Key for my application. The tests are as follows. class AuthAPITestCase(APITestCase): def test_user_auth_endpoint(self): # User Registration factory = APIRequestFactory() req = factory.post('api/users/register/', data={'username': 'test_user', 'email': 'test_email@test.com', 'password': 'test_pwd', 'last_name': 'test_ln'}, format='json') view = UserRegistrationView.as_view() response = view(req) self.assertEqual(response.status_code, 200) # User Login req = factory.get('api/users/login/', data={'username': 'test_user', 'password': 'test_pwd'}, format='json') force_authenticate(req, user=User.objects.get(last_name='test_ln')) view = UserLoginView.as_view() response = view(req) self.assertEqual(response.status_code, 200) In my views, I have added the following permission classes based on the Django REST Framework API Key docs: https://florimondmanca.github.io/djangorestframework-api-key/guide/#creating-and-managing-api-keys. I have also configured relevant settings in settings.py. class UserLoginView(APIView): authentication_classes = (BasicAuthentication,) permission_classes = [HasAPIKey | IsAuthenticated, ] def get(self, request): return Response({'user': request.user.username, 'auth': request}) On running the tests, I get the following error : ====================================================================== ERROR: test_user_auth_endpoint (users.tests.AuthAPITestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/srinivaskini/opt/anaconda3/lib/python3.8/site-packages/rest_framework/request.py", line 74, in wrap_attributeerrors yield File "/Users/srinivaskini/opt/anaconda3/lib/python3.8/site-packages/rest_framework/request.py", line 227, in user self._authenticate() File "/Users/srinivaskini/opt/anaconda3/lib/python3.8/site-packages/rest_framework/request.py", line 380, in _authenticate user_auth_tuple = authenticator.authenticate(self) AttributeError: 'HasAPIKey' object has no attribute 'authenticate' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/srinivaskini/Desktop/SE/HIMMR/backend/users/tests.py", line … -
Django - Object list inside object list
I'm using Django to render a list of tube numbers with their attached ingredient. When clicking on a tube number it renders the list of all the ingredients. Then if I click on an ingredient I want it to replace the saved ingredient for this tube. But I don't know how to proceed, if I should do a sub-app for ingredients in my tube app, or if their is a way to keep the tube id. I tried many things, here is my actual views : def tube_view(request): tubes = Tube.objects.all() return render(request, 'tube_ing.html', {'tubes': tubes}) def tube_detail_view(request, my_id): obj = get_object_or_404(Tube, id=my_id) request.session['my_id'] = my_id ings = Ing.objects.all() return render(request, "tube_detail.html", {"obj": obj, "ings": ings) def tube_choice(request, id_ing): obj = get_object_or_404(Ing, id=id_ing) request.session['id_ing'] = id_ing data = {'qty': 100} form = TubeForm(data) return render(request, "tube_choice.html", {"obj": obj, 'form': form}) def tube_form(request): if request.method == 'POST': form = TubeForm(request.POST) if form.is_valid(): id_ing = request.session['id_ing'] form.cleaned_data['name_ing'] = my_id t = Tube(name_ing_tube=name_ing_ing) t.save() else: return HttpResponseRedirect('/tube_ing/') else: return HttpResponseRedirect('/tube_ing/') My models : class Tube(models.Model): tube_number = models.IntegerField() name_ing = models.CharField(null=False, blank=True, max_length=255, default='') qty = models.IntegerField(default=0) def get_absolute_url(self): return reverse('tube_ing:tube_detail', kwargs={"my_id": self.id}) class Ing(models.Model): name_ing = models.CharField(null=False, blank=True, max_length=255, default='') def get_absolute_url(self): … -
fatal no pg_hba.conf entry error when using Heroku and Postgresql
I'm getting this error when pushing my Django project to Heroku: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.8/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "jkkflotmzeoxrq" FATAL: no pg_hba.conf entry for host "54.171.72.104", user "jkkflotmzeoxrq", database "dcbe6ld5353s18", SSL off The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 92, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/app/.heroku/python/lib/python3.8/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/app/.heroku/python/lib/python3.8/site-packages/django/db/migrations/loader.py", line 216, in build_graph self.applied_migrations = recorder.applied_migrations() File "/app/.heroku/python/lib/python3.8/site-packages/django/db/migrations/recorder.py", … -
PermissionError: [Errno 13] Permission denied:/home/vagrant/?
I was trying to run the Django server in python env on Vagrant ubuntu 18.04 but it's throwing this error? the files are synchronized with window 11 if that will help and I used Virtualenv --always-copy to create the env (env1) vagrant@vagrant:~/desktop/python_files/djangoFirstApp$ python manage.py runserver 10.0.2.15:8000 Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/vagrant/desktop/python_files/env1/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/home/vagrant/desktop/python_files/env1/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/vagrant/desktop/python_files/env1/lib/python3.8/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/home/vagrant/desktop/python_files/env1/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 66, in execute super().execute(*args, **options) File "/home/vagrant/desktop/python_files/env1/lib/python3.8/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/home/vagrant/desktop/python_files/env1/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 101, in handle self.run(**options) File "/home/vagrant/desktop/python_files/env1/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 108, in run autoreload.run_with_reloader(self.inner_run, **options) File "/home/vagrant/desktop/python_files/env1/lib/python3.8/site-packages/django/utils/autoreload.py", line 646, in run_with_reloader exit_code = restart_with_reloader() File "/home/vagrant/desktop/python_files/env1/lib/python3.8/site-packages/django/utils/autoreload.py", line 265, in restart_with_reloader p = subprocess.run(args, env=new_environ, close_fds=False) File "/usr/lib/python3.8/subprocess.py", line 489, in run with Popen(*popenargs, **kwargs) as process: File "/usr/lib/python3.8/subprocess.py", line 854, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/usr/lib/python3.8/subprocess.py", line 1592, in _execute_child self._posix_spawn(args, executable, env, restore_signals, File "/usr/lib/python3.8/subprocess.py", line 1543, in _posix_spawn self.pid = os.posix_spawn(executable, args, env, **kwargs) PermissionError: [Errno 13] Permission denied: '/home/vagrant/desktop/python_files/env1/bin/python' (env1) vagrant@vagrant:~/desktop/python_files/djangoFirstApp$ -
Django - I get an error "invalid token in plural form: EXPRESSION", but that line of code it doesn't exists in my .po files
I get an error "invalid token in plural form: EXPRESSION" and from reading other posts I see that a common problem is a line "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n" that gives that error. But in my .po files that line doesn't exists. Up untill now my app, in which I have set 2 languages, worked perfectly. I changed my html text a little and tried to manually edit .po files and run compilemessages. That didn't work and I run makemessages again and then compilemessages. After that I get that error. I tried deleting the entire locale folder and rerun makemessages but I get the same error Any ideas why is happening? -
Qué es más óptimo a nivel de grandes datos: Almacenar datos fijos o dejar que el lenguaje los procese
Tengo una duda. Si tengo un sistema administrativo de empresa ¿Qué es mejor o más optimo en cuanto a rendimiento? Almacenar cifras totales de sumas de facturas en una base de datos o Dejar que el lenguaje opere con los subtotales y descuentos Les doy un ejemplo más explicito Imaginemos que tenemos una factura: Producto Cantidad Precio unitario Descuento Total Coche 2 10 1 18 Moto 3 5 1 13 Casa 1 50 0 50 Total Subtotal 71 Descuento 1 Iva 1 Total 69 NOTA: A pesar de que esos datos se pueden obtener por sumas que pudiera hacer el lenguaje, sigo cuestionandome qué sería más optimo esos datos en la BD o dejar que el lenguaje los procese. Porfavor imaginen la situacion con miles de registros y con miles de usuarios. Muchas gracias. -
Problem Generating PDF with PHANTOMJS, PDFTOPS, PS2PDF
The process was working fine until 1 month ago and now is just rendering blank pages. Base on a html template, it should renderize a PDF file. Here is the code i have subprocess.call([settings.PHANTOMJS, settings.SCRIPTS_PATH + "/cover.js", str(self.id), local_cover_output + ".raw", settings.HOSTNAME]) subprocess.call([settings.PDFTOPS, local_cover_output + ".raw", local_cover_output + ".ps", "-f", "1", "-l", "1"]) subprocess.call([settings.PS2PDF, "-q", local_cover_output + ".ps", local_cover_output]) clean_up_ps_raw_files(local_cover_output) -
Django loaddata fails with ElephantSQL-based Postgres
I've worked with Django for a few years, but always used sqlite (I only use it for small personal sites). I want to try to migrate one of my projects to Postgres, using a free ElephantSQL plan, and I need to transfer the existing data. I've used dumpdata for the first time, and it worked fine, a JSON file was generated. The command used was dumpdata --indent 2 -o db-dump.json Then I reconfigured the project to use Postgres and tried loaddata db-dump.json, which resulted in psycopg2.OperationalError: FATAL: no pg_hba.conf entry for host "xx.xxx.xx.xxx", user "xxxxx", database "postgres", SSL off I have no clue where this pg_hba.conf is and how to configure it. I installed pgAdmin 4, but not sure where to find that. -
Get list of users when it is midnight in their timezone
I need to send an email to my users when it is midnight in their timezone. I think my approach is fine, but I am having an issue with the Django F() function in my query. Here is the query: target_offset = 0 - timezone.now().hour users_to_email = User.objects.exclude( timezone__isnull=True ).annotate( tz_offset=Value( int (datetime.now(F('timezone')).strftime('%z')) / 100, models.IntegerField() ) ).filter( tz_offset=target_offset ) I get this error: int (datetime.now(F('timezone')).strftime('%z')) / 100, File "/Users/leeloftiss/Desktop/daisy_coder/website/djangoEnv/lib/python3.8/site-packages/freezegun/api.py", line 386, in now result = tz.fromutc(now.replace(tzinfo=tz)) + cls._tz_offset() AttributeError: 'F' object has no attribute 'fromutc' If I just call F('timezone') outside of the datetime.now() function, I get the actual value from the users TIMEZONE column. So I guess I just need to know how I can get that value in this case where I need it in the datetime.now() function. Note: I am using SQL, not Postgres -
DjangoQ is Triggering Twice For Each Task, also on Startup
I have a lot of recurring tasks and am suddenly having the issue that my tasks are being triggered Twice, as well as on startup even though the task was successfully triggered the first time. I'm wondering if I need to set a flag to ensure that DjangoQ knows the Task was completed successfully or there is some other reason this might happen? Here are my DjangoQ Settings in Testing: Q_CLUSTER = { "name": "DjangORM", "workers": 4, "timeout": 90, "retry": 91, "queue_limit": 50, "bulk": 10, "orm": "default", "sync": False, "save_limit": 0, "ack_failures": True, "max_attempts": 1, "attempt_count": 1, } -
Python/Docker - No matching distribution found for Django==3.1.3
I have a project that I am trying to run named Veganettest inside of my visual studio code editor, however, when I run docker-compose up I receive an error that says ERROR: No matching distribution found for Django==3.1.3 even though such a distribution does indeed exist. I have tried using pip to install the distribution itself both inside and outside of my docker container but when I run the program again it just gives me the same error. On top of that, I have tried various other solutions on here, but they are irrelevant to my problem specifically dealing with this library. The error seems to come from my requirements.txt file. Here is the full error that I am getting along with a few warnings initially: WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x000001B4E55BC430>: Failed to establish a new connection: [Errno 11002] getaddrinfo failed')': /simple/django/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x000001B4E55DE070>: Failed to establish a new connection: [Errno 11002] getaddrinfo failed')': /simple/django/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x000001B4E55DE220>: Failed to establish a new connection: [Errno … -
how to get date input from users in django models
I am working on api and testing it by postman so I want date from users as input in %d-%m-%y format also date field is not mandatory here is how my model.py looks like from django.db import models # Create your models here. class Vication(models.Model): travelDate = models.DateField(null=True) # Here I want date as input from users destination= models.CharField(max_length=50,blank=True) status = models.CharField(max_length=8,default='BOOKED') timestamp = models.DateTimeField(auto_now_add=True,editable=False) def __str__(self): return self.title -
How to retrieve data from a model of an App in the views of another application?
Hello django python developers. Indeed, I developed a django project composed of 2 applications. MyApp and Blog I want to retrieve the data from the MyApp App models from the database on the App Blog views without rewriting the same functions How do I do it