Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Selenium KeyError from None 'GMAIL_PASSWORD'
ERROR: test_can_get_email_link_to_log_in (functional_tests.test_login.LoginTest) ---------------------------------------------------------------------- Traceback (most recent call last): File ".../Django/python-tdd-book/functional_tests/test_login.py", line 36, in test_can_get_email_link_to_log_in body = self.wait_for_email(test_email, SUBJECT) File ".../Django/python-tdd-book/functional_tests/test_login.py", line 72, in wait_for_email inbox.pass_(os.environ['GMAIL_PASSWORD']) File "/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 679, in __getitem__ raise KeyError(key) from None KeyError: 'GMAIL_PASSWORD' I'm following the obeythetestinggoat book which is awesome but i can't get passed this error, i found another unresolved question on here exactly the same but, not resolved, I've tried digging into gmail access docs eg. 'Allow insecure apps', triple checking i've got the env vars loaded, the system is actually working ie. sending emails out with the correct information and allowing login for that user when clicked, all is working except the tests, the env vars are loaded in the shell i am executing the test from ie. echo $GMAIL_PASSWORD, I did notice the python version for this states is the system python3 but when i run which python3 from my virtualenv it shows the virtualenv version, i've tried recreating my virtualenv even, any help would be awesome i've spent a day on this error. from django.core import mail from selenium.webdriver.common.keys import Keys import re import os import time import poplib def wait_for_email(self, test_email, subject): if not self.staging_server: email = mail.outbox[0] … -
Django is giving different date values for objects accessed via queryset
Context I get different values for datetime field when I access them differently. I am sure there is some utc edge magic going on here. (Pdb++) Foo.objects.all().values_list('gated_out__occurred__date')[0][0] datetime.date(2021, 9, 9) (Pdb++) Foo.objects.all()[0].gated_out.occurred.date() datetime.date(2021, 9, 10) How do I fix/figure out what is happening? -
DataError('value too long for type character varying(40) on Heroku but not on development
My project works fine under the development but got this error on Heroku. The error occurs when user try to register. I use registration redux Traceback (most recent call last): File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) The above exception (value too long for type character varying(40) ) was the direct cause of the following exception: File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\registration\views.py", line 53, in dispatch return super().dispatch(request, *args, **kwargs) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\edit.py", line 142, in post return self.form_valid(form) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\registration\views.py", line 56, in form_valid new_user = self.register(form) File "C:\Users\sdgy\SaaS\sdg\sdgenv\users\views.py", line 44, in register new_user = super(Register, self).register(form_class) File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\registration\backends\default\views.py", line 96, in register new_user = self.registration_profile.objects.create_inactive_user( File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\registration\models.py", line 185, in create_inactive_user registration_profile = self.create_profile( File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\registration\models.py", line 211, in create_profile profile.save() File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 763, in save_base updated = self._save_table( File "C:\Users\sdgy\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 868, … -
Can't connect to Pod in DevSpace following Django tutorial
The DevSpace-Django tutorial in question is the following: https://devspace.cloud/blog/2019/10/18/deploy-django-to-kubernetes Trying something completely barebones to understand how devspace works to decide if I want to make the switch from skaffold. There are a number of things in the above tutorial that seem to be no longer accurate or have changed in more recent versions of devpsace. At any rate, I'm not able to connect to the Django tutorial app when I navigate to localhost:8000. It just says "Can't connect to the server." This is the output I get when I devspace dev: devspace dev [warn] There is a newer version of DevSpace: v5.15.0. Run `devspace upgrade` to upgrade to the newest version. [info] Using namespace 'mysite' [info] Using kube context 'mysite' [info] Execute 'helm upgrade mysite component-chart --namespace mysite --values /var/folders/tl/wqf19mws155_7bkqyw401z_w0000gn/T/325113665 --install --repo https://charts.devspace.sh --repository-config='' --version 0.8.0 --kube-context mysite' [info] Execute 'helm list --namespace mysite --output json --kube-context mysite' [done] √ Deployed helm chart (Release revision: 5) [done] √ Successfully deployed mysite with helm [done] √ Port forwarding started on 8000:8000 (mysite/mysite-7b856bb78b-2ztpf-devspace) ######################################################### [info] DevSpace UI available at: http://localhost:8090 ######################################################### [0:sync] Waiting for pods... [0:sync] Starting sync... [0:sync] Sync started on /Users/cjones/Projects/Apps/Test/mysite <-> . (Pod: mysite/mysite-7b856bb78b-2ztpf-devspace) [0:sync] Waiting for initial … -
Deploy to Heroku State changed from up to crashed
I make prepare all requirements to deploy my project(Python Telegram Bot) to heroku: 1- git init 2- git add Professor_Bot.py Procfile requirements.txt Procfile: contains web: gunicorn Professor_Bot.wsgi 3- git commit -m "Added Files" 4- git push heroku master remote: Procfile declares types -> web remote: remote: -----> Compressing... remote: Done: 183.5M remote: -----> Launching... remote: Released v20 remote: https://professorbotapp.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy... done. To https://git.heroku.com/professorbotapp.git 05091a2..bbb4e1e master -> master 5- heroku logs --tail I'm new to django and gunicorn and Procfile But I see two error in logs I don't know how to solve them I searched a lot: 2021-09-09T21:50:40.076516+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=professorbotapp.herokuapp.com request_id=842e9e7e-fa91-4f77-836e-b31a818fecec fwd="5.0.176.16" dyno= connect= service= status=503 bytes= protocol=https 2021-09-09T21:50:40.400323+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=professorbotapp.herokuapp.com request_id=5207eba6-ddbc-4812-bff4-b0f980d69a16 fwd="5.0.176.16" dyno= connect= service= status=503 bytes= protocol=https 2021-09-09T21:53:26.281857+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=professorbotapp.herokuapp.com request_id=15b29462-518f-4240-b56c-1fb28e9a9e16 fwd="5.0.176.16" dyno= connect= service= status=503 bytes= protocol=https 2021-09-09T21:53:26.664929+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=professorbotapp.herokuapp.com request_id=d31bbda1-47c4-4a0e-878e-cb01ffaa81b1 fwd="5.0.176.16" dyno= connect= service= status=503 bytes= protocol=https Can anybody Please help me what's the wrong thing that I'm doing... -
Why Django inlineformset_factory getting save prohibited error while file uploading?
Info I am using django inlineformset_factory for file uploading which files are related with Aritcle model. So i have class based view where we are try to save two forms data one is ArticleForm second is FileformSet. ArticleForm data is saved successfully every time but sometime the FileformSet getting error while to uploading files. it's look like one time you can upload successfull second time you can get this error. i also read the documentation but i do not understand it. please anybody tell me how can i solve this issue? ERROR: save() prohibited to prevent data loss due to unsaved related object 'post'. django = Django==3.2.6 python = Python 3.8.10 class NewsCreateView(CreateView): template_name = 'create.html' form_class = ArticleForm model = Article success_url = '/' def get_context_data(self, **kwargs): data = super(NewsCreateView, self).get_context_data(**kwargs) if self.request.POST: data['formset'] = FileFormSet(self.request.POST, self.request.FILES) else: data['formset'] = FileFormSet() return data def form_valid(self, form): form.instance.author = self.request.user context = self.get_context_data() formset = context['formset'] with transaction.atomic(): if formset.is_valid(): formset.instance = form.instance formset.post = form.instance formset.save() return super(NewsCreateView, self).form_valid(form) -
can't cut slash at the end of url in django
I have Django app, There I use some lib. All urls in this lib are ends with slash( / ) path(f"sprite-{get_sprite_hash()}/", home.sprite, name="wagtailadmin_sprite"), path('login/', account.LoginView.as_view(), name='wagtailadmin_login'), I need to make that When I will go on this urls without slash in the end this urls steel working. APPEND_SLASH is not working here, becouse it's only redirect url -> url/ and I need working url without slash and redirections -
setting up django for deployment
I'm trying to deploy my Django app I've split the settings.py and put in a settings folder. Now before I run my server, I must first this set DJANGO_SETTINGS_MODULE=src.settings.dev How can I make the above command to be automatic so I don't have type it every time before running the server .thanks -
Modal forms in change list Django
I'm trying to make it so that when you select an action on the page open modal form. But I don't understand how to display the form when choosing an action. (Use bootstrap for make modal forms) I got only with render(*args) #admin.py from django.http import HttpResponseRedirect from django.shortcuts import render from django.contrib import admin, messages from servers.forms import SetValueForm def set_value_action(self, request, queryset): form = None if 'apply' in request.POST: form = SetValueForm(request.POST) if form.is_valid(): val = form.cleaned_data['val'] count = 0 for item in queryset: item.val = val item.save() count += 1 self.message_user(request, "Success add %d." % (count)) return HttpResponseRedirect(request.get_full_path()) if not form: form = SetValueForm(initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)}) return render(request, 'admin/actions/test.html', {'items': queryset,'form': form, 'title':u'Set new value'}) # forms.py class SetValueForm(forms.Form): VALUES = [ ('Val1', 'Val1'), ('Val2', 'Val2'), ('Val3', 'Val3')] _selected_action = forms.CharField(widget=forms.MultipleHiddenInput) val = forms.ChoiceField(label='value', choices=VALUES) # test.html <div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Set value</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <div class="form-group"> <form action="" method="post">{% csrf_token %} <label>val:</label> {{ form.val }} <p>New value set for:</p> <ul>{{ items|unordered_list }}</ul> <input type="hidden" name="action" value="set_value_action" /> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <input type="submit" name="apply" class="btn btn-primary"> </div> … -
AADSTS90102 error when using django-microsoft-auth for SSO with Azure AD
I followed the steps in this tutorial to enable SSO with Azure Active Directory for the admin portion (to start) of my Django app: https://django-microsoft-auth.readthedocs.io/en/latest/usage.html Navigating to /admin yields this page, which is good: Clicking Microsoft brings up this new window: The important error seems to be: AADSTS90102: 'redirect_uri' value must be a valid absolute URI. In this window, I used the browser console and found that a GET request was being made like this: https://login.microsoftonline.com/50ce...90ac7/oauth2/v2.0/authorize?response_type=code&client_id=f4...27&redirect_uri=https,https://example.org/microsoft/auth-callback/&s... Note the redirect_uri=https,https://.... It seems like that leading "https," is superfluous and is causing the problem. Any ideas where that could be coming from? In my Azure app, the redirect URI is set to https://example.org/microsoft/auth-callback/: I'm using Python 3.9.6, Django 3.2, django-microsoft-auth 2.4.0, NGINX 1.18.0, uvicorn 0.14.0 I've searched for help on this and haven't found anything relevant to my situation. Thanks in advance! -
Build fails for Django app running on Heroku
So I'm currently working on a project where I want my Django app to run. The app itself is hosted with Heroku and so, I have a requirements.txt file with the following packages: django-heroku==0.3.1 django==3.2.7 gunicorn==20.1.0 noise==1.2.1 numpy==1.19.2 pandas==1.2.4 scipy==1.6.3 scikit-image==0.17.2 Cython==0.29.23 opencv-python==4.4.0.46 I recently added the Cython and OpenCV packages as I require them for the POT package. However, when I try to deploy the app, the build log says there isn't a module named numpy. I presume this is because numpy hasn't been "installed" yet. Here's the full build log: -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> No Python version was specified. Using the same version as the last build: python-3.9.7 To use a different version, see: https://devcenter.heroku.com/articles/python runtimes -----> Requirements file has been changed, clearing cached dependencies -----> Installing python-3.9.7 -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 -----> Installing SQLite3 -----> Installing requirements with pip Collecting django-heroku==0.3.1 Downloading django_heroku-0.3.1-py2.py3-none- any.whl (6.2 kB) Collecting django==3.2.7 Downloading Django-3.2.7-py3-none-any.whl (7.9 MB) Collecting gunicorn==20.1.0 Downloading gunicorn-20.1.0-py3-none-any.whl (79 kB) Collecting noise==1.2.1 Downloading noise-1.2.1.tar.gz (125 kB) Collecting numpy==1.19.2 Downloading numpy-1.19.2.zip (7.3 MB) Installing build dependencies: started Installing build dependencies: finished with status 'done' … -
my sitemap link are not clickable using django sitemap
i am using django sitemap for my model but when i go to sitemap.xml it shown as plain text and not clickable at all any idea what i have done wrong here is my code which i executed my sitemap.py from django.contrib.sitemaps import Sitemap from .models import * class MovieSitemap(Sitemap): def items(self): return Movie.objects.all() under my movie model def get_absolute_url(self): return reverse('blogs:movie_read',kwargs={"title":str(self.urltitle)}) url for detail view path('<slug:title>/movie',views.movie_read,name="movie_read"), settings.py 'django.contrib.sites', 'django.contrib.sitemaps', then main projects url.py from django.contrib.sitemaps.views import sitemap from blogs.sitemaps import * sitemaps={ 'movie':MovieSitemap } path('sitemap.xml',sitemap,{'sitemaps':sitemaps}), and yes i do set site id = 1 in my settings.py screenshot what i mean -
Part of a celery task not being executed
Code: @task def task(): time.sleep(10) a=run() #run is a long running function with string as output logger.critical(a) logger.critical("after running celery") return def view() logger.critical("before running celery") task.delay() return http response Expected Output in log file: before running celery a(string stored in variable a) after running celery Actual Output in log file: before running celery(@time t) after running celery (@time t+10sec) The output of the long running function which is stored in variable a is not being logged. I even tried in the following way in the above mentioned task instead of logger.critical(a) try: a=run() #long running function logger.critical("success") except: logger.critical("failure") Still I got the same output neither success nor failure was logged. Questions Can someone please tell me why the function is not being executed and why I am not even getting an error? I am using a django-redis-celery setup so is it possible to cache the result of the function and display it onto a html page? -
Displaying items from sqlite to django
Hi I'm new and can't quite figure it out. I want to display one item on the last line. I know how for ... in works. But it will display all lines. models.py class shorturl(models.Model): original_url = models.URLField(blank=False) short_query = models.CharField(blank=False, max_length=8) visits = models.IntegerField(default=0) main.html <input class="list-group-item to-copy" placeholder="http://127.0.0.1:8000/{{ ???? }}"> <button class="write-btn">Copy</button> how can i display the last short_query in the database instead of "????" -
Aggregate for multiple instances with a ManyToOne relation
I am new to Django and I want to build a Website to track boardgames. What I want: For each round played a Player will get points and I want to create a table which shows the sum of all Scores for each Player. My model is as follows: class Player(models.Model): name = models.CharField(max_length=150) class Score(models.Model): player = models.ForeignKey(Player, blank=False, null=False, on_delete=models.PROTECT) scorevalue = models.IntegerField(blank=False, null=False) I would like to get a queryset with all players where an additional field with the sum of his scores is added. In SQL something like Select distinct playername, sum(scorevalue) over (partition by playername) from Players Join Scores My main problem is to understand the connection between "aggregate" and "annotate" functions in combination with instances and querysets. With an instance I can get Player.objects.get(pk=1).score_set.aggregate(score_sum=Sum('scorevalue')) but is it possible to do this for every instance in a queryset? Thanks for the help. -
Django - the requested resource was not found on this server
I recently started using django and I followed a tutorial however when I go on the website it states "Not Found The requested resource was not found on this server." Although people have had the same problems as me, I tried to do what they had to do but nothing seems to work. (I made leathercookie the project and leatherbiscuit the app) leatherbiscuit/views.py from django.shortcuts import render def index(request): return render(request, 'hello/index.html') I made index.html under leatherbiscuit/templates/hello index.html <h1>Hello World!</h1> leathercookie/urls.py from django.contrib import admin from django.urls import path from leatherbiscuit.views import index urlpatterns = [ path('admin/', admin.site.urls), path('leatherbiscuit/', index), ] leathercookie/settings.py DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'leatherbiscuit', ] -
ImportError: cannot import name 'Required' from 'typing_extensions'
i have installed typing extensions in my python 3.9.0 pip install typing_extensions then i have imported in urls.py from typing_extensions import Required from django.contrib import admin from django.urls import path from .views import index,add_post,delete_post,update_post, urlpatterns = [ path('admin/', admin.site.urls), path('',index,name="home"), path('updatepost/<int:id>',update_post,name='updatepost'), path('addpost/',add_post,name='addpost'), path('delete/<int:id>',delete_post,name='deletepost'), ] but in terminal it says File "C:\Users\ABU RAYHAN\Desktop\projects\miniblog\blog\urls.py", line 1, in <module> from typing_extensions import Required ImportError: cannot import name 'Required' from 'typing_extensions' (C:\Users\ABU RAYHAN\AppData\Local\Programs\Python\Python39\lib\site-packages\typing_extensions.py) how can i solve this? -
Django use request.META['HTTP_ORIGIN'] in django sites framework
So I have a task where I have to use django.sites framework in order to filter some objects in ApiViews depending on the client (there are different front-end clients hosted on different domains) which called the api. so www.frontend1.com and www.frontend2.com are calling www.myapi.com The problem is that both of the clients are calling the api and now I have to "divide" it depending on the request.META['HTTP_ORIGIN']. I've red about django.sites framework (I was asked to use it) but this framework should be useful if the site is hosted on different hosts with the samo codebase. But if the host is the same it renders the django.sites framework useless in my case. Or maybe I am wrong. I have to divide the api by site but instead ot HTTP_HOST I should relay on HTTP_ORIGIN. I've come up with two ideas. Override half of the django.sites framework, but im pretty shure that this will be an overkill Create a my own django.sites framework. Honestly I dont need the whole django sites framework, I will just add permissions in the staff users and filter the querysets depending on their rights and for the api I will just create an object_manager in the … -
using django's request.session with angular
I have a working Django app using session authentication. I am using request.user in my templates and views. I am also using several session variables like requst.session['some_variable']. Currently I am using Django for my backend and as well as for my frontend i.e. html templates, staticfiles etc. Everything's working fine. But I want to shift to angular for my frontend part. I tried using JWT authentication from my angular app. I am getting JWT token from django-restframework, this is my service file import {Injectable} from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; @Injectable() export class UserService { // http options used for making API calls private httpOptions: any; // the actual JWT token public token: string; public sessionid: string; // the token expiration date public token_expires: Date; // the username of the logged in user public username: string; // error messages received from the login attempt public errors: any = []; readonly APIUrl = "http://127.0.0.1:8000"; constructor(private http: HttpClient) { this.httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; } // Uses http.post() to get an auth token from djangorestframework-jwt endpoint public login(user) { this.http.post(this.APIUrl + '/api-token-auth/', JSON.stringify(user), this.httpOptions).subscribe( data => { this.updateData(data['token']); }, err => { this.errors = err['error']; } ); } … -
Empty QuerySet in django-mysql JSONField
When I am executing ModelName.objects.filter(firstName__contains="MyName") it returns an empty queryset but when I am executing it's SQL equivalent in dbshell it is fetching the rows perfectly. select * from AppName_ModelName where firstName like '%MyName%'; I have constructed the sql query as per the documentation -
AttributeError: '_UnixSelectorEventLoop' object has no attribute '_signal_handlers'
I've been upgrading our Django/Python app to Python 3.9.7 and Django 3.2.7 (from Python 3.5 and Django 1.11.23). Currently if I try to run python manage.py createsuperuser I get the following error Traceback (most recent call last): File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/asyncio/selector_events.py", line 261, in _add_reader key = self._selector.get_key(fd) File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/selectors.py", line 193, in get_key raise KeyError("{!r} is not registered".format(fileobj)) from None KeyError: '10 is not registered' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/instabrand/Development/instabrand_platform/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/instabrand/.pyenv/versions/insta9/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/instabrand/.pyenv/versions/insta9/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/instabrand/.pyenv/versions/insta9/lib/python3.9/site-packages/django/core/management/base.py", line 367, in run_from_argv connections.close_all() File "/Users/instabrand/.pyenv/versions/insta9/lib/python3.9/site-packages/django/db/utils.py", line 213, in close_all connection.close() File "/Users/instabrand/.pyenv/versions/insta9/lib/python3.9/site-packages/django/utils/asyncio.py", line 19, in inner event_loop = asyncio.get_event_loop() File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/asyncio/events.py", line 639, in get_event_loop self.set_event_loop(self.new_event_loop()) File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/asyncio/events.py", line 659, in new_event_loop return self._loop_factory() File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/asyncio/unix_events.py", line 54, in __init__ super().__init__(selector) File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/asyncio/selector_events.py", line 61, in __init__ self._make_self_pipe() File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/asyncio/selector_events.py", line 112, in _make_self_pipe self._add_reader(self._ssock.fileno(), self._read_from_self) File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/asyncio/selector_events.py", line 263, in _add_reader self._selector.register(fd, selectors.EVENT_READ, File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/selectors.py", line 523, in register self._selector.control([kev], 0, 0) TypeError: changelist must be an iterable of select.kevent objects Exception ignored in: <function BaseEventLoop.__del__ at 0x103307310> Traceback (most recent call last): File "/Users/instabrand/.pyenv/versions/3.9.7/lib/python3.9/asyncio/base_events.py", line … -
Celery periodic tasks being processed only if a post and get request is sent to a route containing .delay() and AsyncResult()
I want to run this task for every three minutes and this is what I have tasks.py @shared_task def save_hackathon_to_db(): logger.info('ran') loop = asyncio.get_event_loop() statuses = ['ended', 'open', 'upcoming'] loop.run_until_complete(send_data(statuses)) logger.info('ended') settings.py CELERY_BEAT_SCHEDULE = { "devpost_api_task": { "task": "backend.tasks.save_hackathon_to_db", "schedule": crontab(minute="*/3"), }, } However this doesn't get run every 3 minutes, it only gets run when I send a post request to http://0.0.0.0:8000/hackathon/task followed by a get request to http://0.0.0.0:8000/hackathon/<task_id> This is the code for the functions pertaining to the routes respectively @csrf_exempt def run_task(request): if request.method == 'POST': task = save_hackathon_to_db.delay() return JsonResponse({"task_id": task.id}, status=202) @csrf_exempt def get_status(request, task_id): print(task_id) task_result = AsyncResult(task_id) result = { "task_id": task_id, "task_status": task_result.status, "task_result": task_result.result } return JsonResponse(result, status=200) -
I can't create an object in the python shell because I can't import my app with the line "from products.models import Product"
I'm following a Django tutorial that has us creating an app named products I start the python interpreter in the root folder C:\Users\dancc\dev2\cfeproj using the line python manage.py shell when I run the line from products.models import Product I get the following error message ImportError: cannot import name 'Product' from 'products.models' (C:\Users\dancc\dev2\cfeproj\products\models.py) I read that this was a case of circular import, but I have no idea which file is the cause of it here is every part of files that includes the works with Products models.py #C:\Users\dancc\dev2\cfeproj\products\models.py from django.db import models # Create your models here. class Prodcut(models.Model): title = models.TextField() description = models.TextField() price = models.TextField() summary = models.TextField(default='this is so cool!') settings.py #C:\Users\dancc\dev2\cfeproj\cfehome\settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products', ] apps.py #C:\Users\dancc\dev2\cfeproj\products\apps.py from django.apps import AppConfig class ProductsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'products' 0002_summery.py #C:\Users\dancc\dev2\cfeproj\products\migrations\0002_summery.py from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0001_initial'), ] operations = [ migrations.AddField( model_name='prodcut', name='summery', field=models.TextField(default='this is so cool!'), ), ] I also read that the structure of my files might also be the issue, but I don't want to mess around with the location without fully understanding it. -
How to protect child app urls using auth in a Django DRF API
This is my scenario: I have a legacy db and an Django api that is using it. Now we are developing another package with Django DRF that will be installed in the 'parent' app. The parent app already have oauth authentication. So in the parent app's settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('oauth2_provider.contrib.rest_framework.OAuth2Authentication',) } Then the routes are protected under this auth system. This is routes.py: urlpatterns = [ path('api/v1/', include('myapp.routes', namespace='api')), # OAuth 2.0 path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')) ] I install my package, that basically is a DRF API with managed=False models, and it will be an API that will work against the legacy DB. (this is done and working ok) pip install -m my_new_child_package After I install the package and add it's urls I would like to have authentication as well. Basically apply same auth of the parent app. So I am going to have this: urlpatterns = [ path('api/v1/', include('myapp.routes', namespace='api')), path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')) # I want to protect routes under api/v2/ as well with existent auth system. path('api/v2/', include('my_new_child_package.urls')), ] Should I configure something in my child app, or can what other alternative do I have? A middleware? -
bigger and smaller between 2 numbers in a row problem
I am trying to make a guessing game , when I run it it is run correctly but when I guess its make it bigger and smaller between 2 numbers in a row2 this is the code: The code is here