Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Graphene-django - Mutating types with enums
So, I have the following model: class Semester(models.Model): course = models.ManyToManyField(Course, through='CourseSemester') class SemesterType(models.TextChoices): A = 'A', 'Winter' B = 'B', 'Spring' SUMMER = 'SU', 'Summer' name = models.CharField( max_length=200, choices=SemesterType.choices, default=SemesterType.A, ) year = models.IntegerField() I try to add a mutation to add a new semester. Graphene-django seems to automatically generate an Enum field for me, but how can I get it inside the arguments? According to the github issues, something like SemesterType._meta.fields['name'] should work, but I can't get it right, even with wrapping it inside graphene.Argument. It is possible to tell Graphene not to convert it to Enum, however I'd rather avoid that if possible. Any clue how to get that right? -
Error:405 Method Not Allowed (POST) when trying to save/upload media files to my cpanel server
I keep getting HTTP ERROR 405 when trying to save/upload an image or file to my media directory located in the app root directory on Cpanel. When I checked the error log I got: App 8077 output: [ pid=8077, time=2020-09-02 21:24:43,037 ]: Method Not Allowed (POST): /accounts/profile/ App 8077 output: [ pid=8077, time=2020-09-02 21:24:43,038 ]: Method Not Allowed: /accounts/profile/ Everything works locally, but I don't get why the error appears now I hosted the site on Cpanel shared hosting. in my settings.py I have # ALLOWED_HOST = ['mysubdomain'] DEBUG = False STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT ='/path/to/subdomain/staticfiles' MEDIA_URL='/media/' MEDIA_ROOT='/path/to/subdomain/media' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' in my urls.py urlpatterns = [ ................., ...................... ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in my models.py class Profile(models.Model): # Columns for Profile Model user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(verbose_name="Image", upload_to=user_directory_path, default='default.jpg') def __str__(self): # Return the username on the database "e.g Anderson Dean Profile" return "{} {} Profile".format(self.user.first_name, self.user.last_name) # Saves a users profile def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img = Image.open(self.image) if img.mode != 'RGB': img = img.convert('RGB') if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size, Image.ANTIALIAS) fh = storage.open(self.image.name, "w") … -
ModuleNotFoundError: No module named 'errors'
I have a problem when I try to run my project in django, I put the command of "python3 manage.py runserver [localhost:..]. I have python 3.6.7 and django 2.2.2 in a venv. import errors ModuleNotFoundError: No module named 'errors' -
Extract hours & seconds from Django Interval
I have the following Django PostgreSQL query that calculates an interval; querySet = dbname.objects.all().annotate(duration=Func(F('date_start'), F('date_end'), function='age')) which gives me a date interval, evaluated as a timedelta when .values() is called. Now I'd like to further annotate the query to extract the hours & seconds. Tried django.db.models.functions.Extract, django.db.models.functions.Cast, but can't seem to find a solution. querySet.annotate(hours=Extract('duration', 'hour')) ProgrammingError: function pg_catalog.timezone(unknown, interval) does not exist querySet.annotate(seconds=Cast('duration', DateTimeField())) ProgrammingError: cannot cast type interval to timestamp with time zone -
Phoenix (Elixir) Error running test suite
I have inherited a web project with a backend written in Elixir using the Phoenix framework. I am a Python (Django) developer by trade and new to Elixir. There is 0 test coverage on this project, so I thought that would be a good place to start and get familiar with Elixir and Phoenix. But I get an error message running mix test before I can even get started. 16:27:35.818 [info] Application tzdata started at :nonode@nohost ** (Mix) Could not start application cowboy: exited in: :application.cowboy({:description, 'Small, fast, modular HTTP server.'}, {:vsn, '1.1.2'}, {:id, 'git'}, {:modules, [:cow_uri, :cowboy, :cowboy_app, :cowboy_bstr, :cowboy_clock, :cowboy_handler, :cowboy_http, :cowboy_http_handler, :cowboy_loop_handler, :cowboy_middleware, :cowboy_protocol, :cowboy_req, :cowboy_rest, :cowboy_router, :cowboy_spdy, :cowboy_static, :cowboy_sub_protocol, :cowboy_sup, :cowboy_websocket, :cowboy_websocket_handler]}, {:registered, [:cowboy_clock, :cowboy_sup]}, {:applications, [:kernel, :stdlib, :ranch, :cowlib, :crypto]}, {:mod, {:cowboy_app, []}}, {:env, []}) ** (EXIT) :already_loaded And this is where, I am hoping, my ignorance of Elixir and Phoenix is hindering my debugging capability. Is this tzdata that is throwing this error and not letting the test suite load properly? Any direction or insight is appreciated. -
What happens after Django clean method but before commit?
I am using an awesome library called Django Auditlog. It tracks what changes occurred to an object. For model Book if I changed the Author name from 'John' to 'Mary' it records the before value (John), after value (Mary), when it occurred, and what user made the change. It's working except that it is detecting changes that aren't changes for some of my decimal fields. It thinks a change occurs anytime I save this model: it thinks that I started with .00 and changed it to .0. But .00 is the existing value and I didn't change anything. I just saved() the record. I checked the output of the form itself in the clean() method: services_sub_total 44.00 sum_payments 33.00 And then in the database: I just can't figure out where/why this is detecting only one zero in the decimal place - I'm not seeing that .0 anywhere. So I'm wondering what is happening between the clean() method and the commit that might be truncating the .00 to .0 where Auditlog might be incorrectly detecting a change? -
How to correct CORS errors when redirecting to client from server
I have a django server and react client. My app has been making calls, unabated, to the server for various data I have stored to redux state. Furthermore, I have an authorization flow with an external API achieved via a link (not fetch request) to my backend and then, after obtaining the token, redirects back to my front end. All no problem. The issue comes when I try to refresh my token via get request to my backend. That all works, but then when my backend tries to redirect to my front end I get a CORS error: Access to XMLHttpRequest at 'http://localhost:3000/users/1/.../' (redirected from 'http://localhost:8000/api/callback?refresh_token=....') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. How do I deal with this? Again, note that the redirect works just fine when I initially authorize the user via the external API, it's almost the exact same flow. That's why I am confused about this error. -
DNS_PROBE_FINISHED_NXDOMAIN when trying to run a django webapp locally on 127.0.0.1:8000
So this weird issue came out after I pulled a project from pythonanywhere into github and then tried to run it locally. Every time I try to run ANY Django project I get this error and generally cannot use my localhost to open any Django projects This is what my settings.py looks like: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = *REDACTED* # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] PREPEND_WWW = True CORS_REPLACE_HTTPS_REFERER = False HOST_SCHEME = "http://" SECURE_PROXY_SSL_HEADER = None SECURE_SSL_REDIRECT = False # Application definition THUMBNAIL_PRESERVE_FORMAT = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'dynamic_raw_id', 'django.contrib.humanize', 'ckeditor', 'ckeditor_uploader', 'cachalot', 'sorl.thumbnail', 'cryptocracy' ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'website.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'cryptocracy/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'website.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { … -
ForeignKey child objects disappeared from table
So for some reason, when I refreshed my api view today the child objects in my model disappeared from the following JSON object: { "id": 1, "title": "test movie", "date": "2020-09-02", "start_date": "2020-09-23", "end_date": "2020-09-24", "location": "Manhattan", "overview": "Adrian", "studio": "Ghibli", "poster": "http://127.0.0.1:8000/media/", "genre": "Horror", "status": "Paid", "job_type": "Fulltime", "user": 1 }, Initially I had right after "id" an indented section "listing" with all the children objects. I've checked my models to make sure that I didn't accidentally delete anything, and I can't quite figure out what went wrong. user_applications is the many to one (Listings) class User_applications(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, default="1") listing = models.ForeignKey(Listings, on_delete=models.CASCADE, default="1", related_name="listing") ... class Listings(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, default="1") ... -
DRF with TokenAuthentication - Authentication credentials were not provided
I've deployed a project on Elastic Beanstalk and I can't figure out why Django Rest Framework returns this response: Authentication credentials were not provided. when I go to ../api/article I'm sending header - Authorization: Token curl -X GET http://environment.eba-etpcqsqk.us-west-1.elasticbeanstalk.com/api/article/ -H 'Authorization: Token MYTOKEN' {"detail":"Authentication credentials were not provided."} Views: class ArticleViewSet(ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer pagination_class = StandardResultsSetPagination filterset_class = ArticleFilter # user must be either logged in or must provide AUTH TOKEN authentication_classes = [TokenAuthentication, SessionAuthentication] permission_classes = [IsAuthenticated] I've DEBUG=True and it works on the development server. Do you know where is the problem? Maybe EBS doesn't forward Headers? -
Deploying Django project on Heroku: ModuleNotFoundError
No where in my project do I import users. Every single aspect of the project runs locally. I am using visual studio for my project. In my Project Directory Settings.py INSTALLED_APPS = # Add your apps here to enable them 'users.apps.usersConfig', 'resume.apps.resumeConfig', 'MainApp.apps.MainAppConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', Procfile: web: gunicorn Project.Project.wsgi:application Here is the error 2020-08-16T06:35:31.691841+00:00 app[web.1]: Traceback (most recent call last): 2020-08-16T06:35:31.691846+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-08-16T06:35:31.691850+00:00 app[web.1]: worker.init_process() 2020-08-16T06:35:31.691851+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 129, in init_process 2020-08-16T06:35:31.691852+00:00 app[web.1]: self.load_wsgi() 2020-08-16T06:35:31.691852+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2020-08-16T06:35:31.691852+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-08-16T06:35:31.691857+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-08-16T06:35:31.691857+00:00 app[web.1]: self.callable = self.load() 2020-08-16T06:35:31.691858+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 52, in load 2020-08-16T06:35:31.691858+00:00 app[web.1]: return self.load_wsgiapp() 2020-08-16T06:35:31.691858+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp 2020-08-16T06:35:31.691859+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-08-16T06:35:31.691859+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 350, in import_app 2020-08-16T06:35:31.691859+00:00 app[web.1]: __import__(module) 2020-08-16T06:35:31.691861+00:00 app[web.1]: File "/app/Project/Project/wsgi.py", line 29, in <module> 2020-08-16T06:35:31.691861+00:00 app[web.1]: application = get_wsgi_application() 2020-08-16T06:35:31.691861+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-08-16T06:35:31.691862+00:00 app[web.1]: django.setup(set_prefix=False) 2020-08-16T06:35:31.691862+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 24, in setup 2020-08-16T06:35:31.691863+00:00 app[web.1]: apps.populate(settings.INSTALLED_APPS) 2020-08-16T06:35:31.691863+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate 2020-08-16T06:35:31.691863+00:00 app[web.1]: app_config = AppConfig.create(entry) 2020-08-16T06:35:31.691864+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/config.py", … -
AttributeError: 'str' object has no attribute 'state_forwards' with django migrations migrations.RunSQL(
I am trying to set the autogenerated id of my postgres tables to a start value of 10000 for different models. I used this article and did the following: python3 manage.py makemigrations core --empty Then in the migration I added: operations = [ migrations.RunSQL( "ALTER SEQUENCE CORE_ORG_id_seq RESTART WITH 10000", "ALTER SEQUENCE CORE_USER_id_seq RESTART WITH 10000", "ALTER SEQUENCE CORE_PARTLISTING_id_seq RESTART WITH 1000", "ALTER SEQUENCE CORE_BOMITEM_id_seq RESTART WITH 1000", "ALTER SEQUENCE CORE_MANUFACTURER_id_seq RESTART WITH 1000;" ), migrations.RunSQL( "ALTER SEQUENCE CORE_BOM_id_seq RESTART WITH 1000", "ALTER SEQUENCE CORE_SPECIFICPART_id_seq RESTART WITH 10000", "ALTER SEQUENCE CORE_GENERICPART_id_seq RESTART WITH 10000;" ), ] I put these in two separate lines because I was getting an error that __init.py__ could only take 6 commands btw. When I run migrate on this, I get: File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/myname/.local/share/virtualenvs/mobiusAPI-NVQT3lgx/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/myname/.local/share/virtualenvs/mobiusAPI-NVQT3lgx/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/myname/.local/share/virtualenvs/mobiusAPI-NVQT3lgx/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/myname/.local/share/virtualenvs/mobiusAPI-NVQT3lgx/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/myname/.local/share/virtualenvs/mobiusAPI-NVQT3lgx/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/Users/myname/.local/share/virtualenvs/mobiusAPI-NVQT3lgx/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "/Users/myname/.local/share/virtualenvs/mobiusAPI-NVQT3lgx/lib/python3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, … -
Django model manager isn't working as expected
I have a model "Name" in models.py file of a django app. from .managers.py import NameManager class Name(models.Model): ....................... objects = NameManager() I have created NameManager in managers.py file. class NameManager(models.Manager): def get_func(self, arg): .............. def check_func(self, arg1, arg2): .............. Now in my views.py file, when I write: from .models import Name if Name.check_func(arg1, arg2): ......................... I am getting an error: type object 'Name' has no attribute 'check_func' Where am I making mistake? -
Access request.GET or inject a variable in Django's auth login/registration form
I have a custom form using Django's auth library and I want some users to click on a link to login/register that will pre-populate the email field, without them having to enter their email (avoid entering it manually and make sure the user uses the email we have on file). A link like this: /account/login?email=name@domain.com However on the receiving page, I can't use this as Django doesn't permit in templates: <input type="text" name="username" placeholder="Email" class="form-control" required="" value="{{ request.GET.get('email', '') }}"> If there is a way to inject a variable in Django's auth template, I don't know how since the view is not accessible. Is there a way to access request.GET.get() in the templates, or is there a better way to do this? -
What do they mean when they are saying for you to put Authorization (eg. token) in header of each request?
I am using Django and doing calls for API. I have not used headers for Django before. Am I creating a header variable? E.G Let's say my API key is 'abcd', and ID is '123', from what I have in mind I do header = {'API':'abcd', 'ID':'123'} class CancelApt(APIVIEW): def post(request, id): pass Is this what they meant? Can someone give me an example? Thanks. -
Fail to deploy project to Google Cloud App Engine Standard
I have a project that has been running fine, but I want to make some changes and solve some bugs so I tried to deploy my app using the Google Cloud SDK (gcloud app deploy) Services to deploy: descriptor: [/home/projects/Myproject/app.yaml] source: [/home/projects/Myproject/] target project: [my-project] target service: [default] target version: [20200902t153320] target url: [https://my-project.uc.r.appspot.com] Do you want to continue (Y/n)? Beginning deployment of service [default]... ╔════════════════════════════════════════════════════════════╗ ╠═ Uploading 2 files to Google Cloud Storage ═╣ ╚════════════════════════════════════════════════════════════╝ File upload done. Updating service [default]...failed. ERROR: (gcloud.app.deploy) Error Response: [9] Cloud build 3ebf37fb-b18d-4c68-b352d-10bd8758f90b0 status: FAILURE Error type: OK Full build logs: https://console.cloud.google.com/cloud-build/builds/3ebf37fb-b18d-4c68-b32d-10bd8s78f90b0?project=my-projectid This used to work yesterday fine but now it gives me this error and I cannot make any changes: ERROR: build step 6 "us.gcr.io/gae-runtimes/buildpacks/python38/builder:python38_20200816_3_8_5_RC01" failed: step exited with non-zero status: 246 ERROR Finished Step #6 - "exporter" Step #6 - "exporter": ERROR: failed to export: failed to write image to the following tags: [us.gcr.io/my-project/app-engine-tmp/app/ttl-2h/default/buildpack-app:latest: GET https://us.gcr.io/v2/token?scope=repository%3Amy-project%2Fapp-engine-tmp%2Fapp%2Fttl-2h%2Fdefault%2Fbuildpack-app%3Apush%2Cpull&scope=repository%3Agae-runtimes%2Fbuildpacks%2Fpython38%2Frun%3Apull&service=us.gcr.io: DENIED: Token exchange failed for project 'my-project'. Access denied.] Step #6 - "exporter": *** Digest: sha256:bd8121f23cb362683e7c32a8bbdf2a900606373f8edfsdf36fe0ffb17014 Step #6 - "exporter": Step #6 - "exporter": us.gcr.io/my-project/app-engine-tmp/app/ttl-2h/default/buildpack-app:latest - GET https://us.gcr.io/v2/token?scope=repository%3Amy-project%2Fapp-engine-tmp%2Fapp%2Fttl-2h%2Fdefault%2Fbuildpack-app%3Apush%2Cpull&scope=repository%3Agae-runtimes%2Fbuildpacks%2Fpython38%2Frun%3Apull&service=us.gcr.io: DENIED: Token exchange failed for project 'my-project'. Access denied. Step #6 - "exporter": *** Images (sha256:bd8121f23cb362683e7c32adfssd73f8ea51326f36fe0ffb17014): I … -
I have a problem in integrating RASA chatbot with Django
After running the django and RASA server i'm getting these errors,somebody please help me to sort out this error -
Celery Worker Can't Find Template in Production
I have a task which gets run ever time a user gets created. The task is to send an email to a user. In that task, I have a line template = get_template('account/user_creation.html', using='post_office') to get a template for the email. The task was successfully executed when I ran it in development on my computer, but it's not the case when I deployed it to Elastic Beanstalk for production. The template is located in proj/templates/account/user_creation.html. The task is located in proj/account/tasks.py The error is as follow: [2020-09-02 12:51:01,196: ERROR/ForkPoolWorker-1] Task account.tasks.send_user_email_when_user_created_by_admin[3247eb86-ddf3-4b06-8e20-fe6c57329cff] raised unexpected: TemplateDoesNotExist('account/user_creation.html') Traceback (most recent call last): File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/celery/app/trace.py", line 412, in trace_task R = retval = fun(*args, **kwargs) File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/celery/app/trace.py", line 704, in __protected_call__ return self.run(*args, **kwargs) File "/var/app/staging/account/tasks.py", line 131, in send_user_email_when_user_created_by_admin File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: account/user_creation.html In settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, { # for post office 'BACKEND': 'post_office.template.backends.post_office.PostOfficeTemplates', 'APP_DIRS': True, 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.template.context_processors.request', ] } } ] -
airflow: django / logging
We're trying to use airflow with a custom django project and followed the advice of this answer (Django) ORM in airflow - is it possible? . When we implemented it on airflow v1.10.11, our tasks would always fail at the part of django setup where it reconfigures logging based on django settings. The error that we would get back looked like: [2020-09-02 18:54:29,344] {local_task_job.py:102} INFO - Task exited with return code Negsignal.SIGKILL Does anyone have any ideas on why / how airflow is detecting changes to the logging configuration and then killing the task? -
How to sort a query based on another model in Django
If I had: class Assets(models.Model): assetMake = models.CharField(max_length=50,blank=True,) assetModel = models.CharField(max_length=50,blank=True,) class Maintenance(models.Model): assetID = models.ForeignKey(Assets, on_delete=models.CASCADE) dateRequested = models.DateTimeField(null=True, blank=True) dateCompleted = models.DateTimeField(null=True, blank=True) complete = models.BooleanField(default = False) I want to list all of the assets on a view, and sort them by the last time they were maintained (dateCompleted). I have been trying to get this working below, but I feel like there is much easier way of accomplishing this, Any help is appreciated class MaintenanceAgeList(LoginRequiredMixin,TemplateView): template_name = 'maintenance_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) maintenanceList = [] assets = Assets.objects.filter(retire = False) today = timezone.now().date() for asset in assets: maintenance = Maintenance.objects.filter(assetID_id = asset.id, complete =True,).order_by('-dateCompleted') if maintenance.count() > 0: asset['maintDate'] = (maintenance[0].dateCompleted).date() maintenanceList.append(asset) asset['days'] = (today - lastMaintenance[0].dateCompleted.date()).days else: asset['maintDate'] = today - timedelta(days=365) asset['days'] = 365 maintenanceList.append(asset) maintenanceList = maintenanceList.sort(key=lambda r: r.maintDate) context['items'] = maintenanceList return context -
How to use cleaned_data before form validation condition?
I wanted to use cleaned_data['username'] before form.is_valid() condition as shown in the code. I want to get the value from Django form field and check in database if the username exist or not. But its giving me error " Form object has no attribute cleaned_data" how should I solve this or is there any other way to get value from Django form? view.py def RegistrationView(request): form=Registration_Form() if request.method=='POST': print("In Post") form=Registration_Form(request.POST) username=form.cleaned_data['username'] print(username) if form.is_valid(): form.save() return redirect('login_view') else: # messages.error(request,"Form is Invalid!") return redirect('registration_view') else: return render(request,'registration.html',{'form':form}) model.py class User_Registration(models.Model): company_name=models.CharField(max_length=250,blank=False) username=models.CharField(max_length=10,primary_key=True,unique=True,blank=False) password=models.CharField(max_length=10,unique=True,blank=False) email=models.EmailField(max_length=250,blank=False) forms.py class Registration_Form(forms.ModelForm): class Meta: model=User_Registration fields=('company_name','username','password','email') widgets={ 'company_name':forms.TextInput(attrs={'class':'form-control input-sm'}), 'username':forms.TextInput(attrs={'class':'form-control'}), 'password':forms.PasswordInput(attrs={'class':'form-control'}), 'email':forms.EmailInput(attrs={'class':'form-control'}), } -
How to change/ insert the djnago finite state machines on fly from terminal window
I have below a.py djnago finite state machine program: from django.db import models from django_fsm import transition, FSMIntegerField from django_fsm import FSMField, transition import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") import django django.setup() from django.core.management import call_command class Order(models.Model): STATUS_GO = 0 STATUS_COME =1 STATUS_CHOICES = ( (STATUS_GO, 'GO'), (STATUS_COME,'come') ) product = models.CharField(max_length=200) status = FSMIntegerField(choices=STATUS_CHOICES, default=STATUS_GO, protected=True) @transition(field=status, source=. [STATUS_GO], target=STATUS_COME) def walk(self): print("Target moved") I would run above program as : Press F5. >>> State= order() >>> State.walk # input >>> Target moved # output I would like understand by any chance, do djnago /python provide opportunities to insert STATES like ( STATUS_HOLD, STATUS_JUMP) from terminal window, in addition to already available. So that these news get positioned in programs. Any possibility. Thanks. -
Is the OS the reason this Django docker file fails to build?
Getting on boarded onto a project that says it's built with Linux, Python 2.7 and Bash. My work computer only has mac os installed and I'm trying to build this container without having to install Linux but I might have to. Everything is working as intended until I reach this error: Step 28/31 : RUN export COLLECTSTATIC=local && python manage.py collectstatic --settings=settings.{__SETTINGS__} --link --no-input ---> Running in 874e3c95b9b9 Traceback (most recent call last): File "manage.py", line 20, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 302, in execute settings.INSTALLED_APPS File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named {__SETTINGS__} ERROR: Service 'primatest_4' failed to build: The command '/bin/sh -c export COLLECTSTATIC=local && python manage.py collectstatic --settings=settings.{__SETTINGS__} --link --no-input' returned a non-zero code: 1 Since I have 0 domain knowledge of this problem I'm having a hard time diagnosing this error. Dockerfile.python27 ########################## # WARNING: {__WARNING__} FROM python:2.7 ############################################################################### # Update base container install ############################################################################### RUN if [ ! -d "/app/prima" ]; then mkdir -p /app/prima; fi WORKDIR /app/prima/ … -
Django: SSL + trailing slash cause URL in browser to show unusual path
Hosting: A2Hosting Reference for A2Hosting deploy: link Python: 3.8.1 Django: 3.1.1 Webserver: Apache When "SECURE_SSL_REDIRECT = False" in settings.py, having the trailing slash in the urls.py paths causes no issue. urlpatterns = [ path('admin/', admin.site.urls), path('login/', dashboard, name="dashboard"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) In fact, accessing the URL http://subdomain.domain.com/login (or admin) the correct page is shown. But when I set "SECURE_SSL_REDIRECT = True", if I maintain the trailing slash and I access the same URLs, the page is still correctly shown, but the URL in the browser address bar changes. Instead to be: https://subdomain.domain.com/login it becomes: https://subdomain.domain.com/home/user/a2hosting_python_app/login/ For admin path, instead to be: https://subdomain.domain.com/admin/login/?next=/admin/ it becomes: https://subdomain.domain.com/home/user/a2hosting_python_app/admin/login/?next=/home/user/a2hosting_python_app/admin/ At this point, if I edit the urls.py removing the trailing slash: urlpatterns = [ path('admin', admin.site.urls), path('login', dashboard, name="dashboard"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) the login URL shows correctly, but the admin URL won't. I have no APPENDING_SLASH set in settings.py. Does anyone know why Django behave like this? What am I doing wrong? Many thanks in advance. -
Django Timezone filter returns wrong results
I wrote the following code: date = self.request.query_params.get('date') queryset = Fixture.objects.all().order_by('-date') if(date): date = pytz.utc.localize(datetime.strptime(date, "%Y-%m-%d")).astimezone(pytz.UTC) queryset = Fixture.objects.filter(date__date=date).order_by('date') Upon excuting this with date = "2020-09-02" the queryset returns values containing the date "2020-09-03". How come this happens and how can this be solved?