Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Chromedriver not opening Django development server
I am formulating my first tests with Selenium and Chromedriver. I kept getting a NoSuchElementException in my test results. I tried to using an explicit wait but it timed out. I noticed that Chrome was raising ERR_FILE_NOT_FOUND so I made the path more explicit in my driver.get(file_uri()). Chrome found the html but was displaying my pure Django code instead of the generated html. If the development server was being launched properly I believe my test would be passing but I have no idea why it's not functioning as expected. Here is my test: class WebpageTests(unittest.TestCase): def test_title(self): driver.get(file_uri("network/templates/network/index.html")) open_form = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "new-post"))) open_form.click() form = driver.find_element_by_id("post-view") self.assertTrue(form.is_displayed()) if __name__ == "__main__": unittest.main() here is my setup: from sqlite3 import Timestamp from xxlimited import foo from django.test import Client, TestCase from .models import Post, User from selenium import webdriver import os import pathlib import unittest from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By def file_uri(filename): return pathlib.Path(os.path.abspath(filename)).as_uri() driver = webdriver.Chrome() Thank you in advance for your help! -
Django how to save User Model?
Good day again, so I have a form and a user can add multiple titles. Each submit will create a new object which includes the written title and the user who wrote it(submitted the form). I tried it with this but I don't know what to add in NewTitle.objects.create(title=title, ...) \views.py def title_view(request): try: profile = request.user.newtitle except NewTitle.DoesNotExist: profile = NewTitle(user=request.user) if request.method == 'POST': form = NewTitleForm(request.POST, instance=profile) if form.is_valid(): title = form.cleaned_data["title"] NewTitle.objects.create(title=title) #in the () I have to add the user= aswell return redirect('/another') else: form = NewTitleForm(instance=profile) return render(request, 'test.html', {'form': form, 'profile': profile}) \models.py class NewTitle(models.Model): user = models.OneToOneField( User, default=None, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=200) I am working with basic User model. Currently, a user can submit the form and a new object will create just with the given title but without the user who wrote it because I just added title=title and not user=... Any ideas? -
Out of memory: Killed process (gunicorn) on AWS Lightsail
I am hoping someone can give me some direction on how to determine what is causing this out of memory to continue to occur. I am a novice in this arena, so any help will greatly be appreciated. I have a Django app using Gunicorn, Ngnix, PostgreSQL. I am also using Supervisor to monitor the app. If I reboot the sever it restarts the app automatically...no issues. The app was built using Flask prior to this and I never experienced this issue. Both apps had the following AWS: AWS Lightsail 512 MB Memory 1 Core Processor 20 GB SSD Disk 1 TB Transfer* Here are lines from the gunicorn error log: [2022-01-20 02:06:15 +0000] [723] [INFO] Booting worker with pid: 723 [2022-01-20 02:06:15 +0000] [724] [INFO] Booting worker with pid: 724 [2022-01-20 02:06:15 +0000] [725] [INFO] Booting worker with pid: 725 [2022-01-20 07:43:42 +0000] [708] [CRITICAL] WORKER TIMEOUT (pid:723) [2022-01-20 07:49:11 +0000] [708] [CRITICAL] WORKER TIMEOUT (pid:724) [2022-01-20 07:49:11 +0000] [708] [CRITICAL] WORKER TIMEOUT (pid:725) [2022-01-20 02:49:11 -0500] [724] [INFO] Worker exiting (pid: 724) [2022-01-20 02:49:11 -0500] [725] [INFO] Worker exiting (pid: 725) [2022-01-20 07:49:11 +0000] [708] [WARNING] Worker with pid 723 was terminated due to signal 9 [2022-01-20 07:49:11 … -
Is it possible to use django with asgi and mantain some sync views?
Now I have an application running under wsgi protocol, and now we are thinking about make a transition to the asgi protocol. The doubt we have to solve to make this decision is if it's possible run django under asgi and keep some views as sync. Could anyone help me? -
Django Factory Boy loop return same value
I'm trying to generate fake objets from loop but always returns the same objet utilities.py: ... for _ in range(number_objects): try: element = app_factories.UserFactory() print(element) except Exception as e: print(e) print(type(e)) ... factories.py from faker import Faker from factory.fuzzy import FuzzyChoice from factory.django import DjangoModelFactory fake = Faker(['es-ES']) class UserFactory(DjangoModelFactory): name = fake.name() email = '{}@mailcom'.format(slugify(name)) height = fake.numerify(text='1##') friend = FuzzyChoice(app_models.User.objects.all()) class Meta: model = app_models.User Probably it will be from the seed or generator but I don't know how to solve it. Anybody could help me please ? Thanks in advance. -
Django get primary key with JSON response
How do I send each objects primary key with JSON response? I am sending json response to amend a table based on users state. Everything works fine, except not being able to get the PK associated with each user. Currently its sending all values except PK. class UserByState(View): page_limit = 100 def get_paginated_context(self, queryset, page, limit): if not page: page = 1 if limit: self.page_limit = limit paginator = Paginator(queryset, self.page_limit) page_obj = paginator.get_page(page) serialized_page = serialize("json", page_obj.object_list) serialized_page = [obj["fields"] for obj in json.loads(serialized_page)] return { "data": serialized_page, "pagination": { "page": page, "limit": limit, "has_next": page_obj.has_next(), "has_prev": page_obj.has_previous(), "total": queryset.count() } } def get(self, request, *args, **kwargs): user = self.request.user page = request.GET.get('page') limit = request.GET.get('limit') state = request.GET.get('state') queryset = User.objects.all() if state and state != "all": queryset = queryset.filter(state=state) to_return = self.get_paginated_context(queryset, page, limit) return JsonResponse(to_return, status = 200) -
Not getting correct output in django filter
I have following models. class Stocks(models.Model): ticker = models.CharField(max_length=30, primary_key=True, unique=True) company_name = models.CharField(max_length=100, blank=True, null=True) ... class Advice(models.Model): ticker = models.ForeignKey(Stocks, db_column='ticker', related_name='advices', on_delete=models.CASCADE) advice_date = models.DateField(blank=True, null=True) ... class Recommendation(models.Model): ticker = models.ForeignKey(Stocks, db_column='ticker', related_name='recommendation', on_delete=models.CASCADE) target = models.FloatField(blank=True, null=True) I want to fetch details where Advice.advice_date is latest. but following code gives me all records from advice reco = Recommendation.objects.all().values('ticker__advices__advice_date').filter(ticker__advices__advice_date=datetime.date(2022,1,19)) print(reco) this is what I get: <QuerySet [{'ticker__advices__advice_date': datetime.date(2022, 1, 10)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 11)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 12)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 13)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 14)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 17)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 18)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 19)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 10)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 11)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 12)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 13)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 14)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 17)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 18)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 19)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 10)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 11)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 12)}, {'ticker__advices__advice_date': datetime.date(2022, 1, 13)}, '...(remaining elements truncated)...']> this is what I need: <QuerySet [{'ticker__advices__advice_date': datetime.date(2022, 1, 19)}] -
Django FileField upload_to custom function error
I have created a custom utility function for Django FileField's upload_to parameter. This function accepts a prefix and returns a function that actually accepts instance and filename. But when I run manage.py makemigrations, the command throws ValueError. I have included the related files/data below. secret_upload function import uuid def secret_upload(prefix): def _path(instance, filename): file = filename.split(".") fuuid = uuid.uuid4() if len(file) == 1: filename = f"secrets/{prefix}/{file[0]}-{fuuid}" elif len(file) == 2: filename = f"secrets/{prefix}/{file[0]}-{fuuid}.{file[1]}" return filename return _path Django Model class SecretData(models.Model): name = models.CharField(max_length=100) secret_file = models.FileField(upload_to=secret_upload("files")) makemigrations error traceback (most recent call last): File "D:\Python\projects\keep-creds\keep_creds\manage.py", line 22, in <module> main() File "D:\Python\projects\keep-creds\keep_creds\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Python\projects\kc-venv\lib\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line utility.execute() File "D:\Python\projects\kc-venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Python\projects\kc-venv\lib\site-packages\django\core\management\base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "D:\Python\projects\kc-venv\lib\site-packages\django\core\management\base.py", line 417, in execute output = self.handle(*args, **options) File "D:\Python\projects\kc-venv\lib\site-packages\django\core\management\base.py", line 90, in wrapped res = handle_func(*args, **kwargs) File "D:\Python\projects\kc-venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 190, in handle self.write_migration_files(changes) File "D:\Python\projects\kc-venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 227, in write_migration_files migration_string = writer.as_string() File "D:\Python\projects\kc-venv\lib\site-packages\django\db\migrations\writer.py", line 141, in as_string operation_string, operation_imports = OperationWriter(operation).serialize() File "D:\Python\projects\kc-venv\lib\site-packages\django\db\migrations\writer.py", line 99, in serialize _write(arg_name, arg_value) File "D:\Python\projects\kc-venv\lib\site-packages\django\db\migrations\writer.py", line 63, in _write arg_string, arg_imports = MigrationWriter.serialize(_arg_value) File "D:\Python\projects\kc-venv\lib\site-packages\django\db\migrations\writer.py", line 271, in serialize … -
Django include template no data
I am trying to include a file, into my base.html Inside the base, inn the base.html {% block content %} {% include "something.html %} {% endblock %} But nothing shows up from the included file, and I have tried to have blocks inn the something.html {% block content %} something something inside the something.html {% endblock %} I have also tried without using blocks, but nothing. -
W/IInputConnectionWrapper getTextBeforeCursor on inactive InputConnection error coming when calling Django API from flutter app submit button
This is Error : W/IInputConnectionWrapper( 5696): getTextBeforeCursor on inactive InputConnection W/IInputConnectionWrapper( 5696): getSelectedText on inactive InputConnection W/IInputConnectionWrapper( 5696): getTextAfterCursor on inactive InputConnection W/IInputConnectionWrapper( 5696): beginBatchEdit on inactive InputConnection W/IInputConnectionWrapper( 5696): getTextBeforeCursor on inactive InputConnection W/IInputConnectionWrapper( 5696): endBatchEdit on inactive InputConnection I/TextInputPlugin( 5696): Composing region changed by the framework. Restarting the input method. W/IInputConnectionWrapper( 5696): getSelectedText on inactive InputConnection W/IInputConnectionWrapper( 5696): getTextAfterCursor on inactive InputConnection W/IInputConnectionWrapper( 5696): getTextBeforeCursor on inactive InputConnection W/IInputConnectionWrapper( 5696): getSelectedText on inactive InputConnection W/IInputConnectionWrapper( 5696): getTextAfterCursor on inactive InputConnection W/IInputConnectionWrapper( 5696): beginBatchEdit on inactive InputConnection W/IInputConnectionWrapper( 5696): getTextBeforeCursor on inactive InputConnection W/IInputConnectionWrapper( 5696): endBatchEdit on inactive InputConnection W/IInputConnectionWrapper( 5696): beginBatchEdit on inactive InputConnection W/IInputConnectionWrapper( 5696): getTextBeforeCursor on inactive InputConnection W/IInputConnectionWrapper( 5696): endBatchEdit on inactive InputConnection I/TextInputPlugin( 5696): Composing region changed by the framework. Restarting the input method. W/IInputConnectionWrapper( 5696): getTextBeforeCursor on inactive InputConnection * This is My Code : import 'package:fin_l/front.dart'; import 'package:fin_l/models/reg.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'dart:async'; import 'package:http/http.dart' as http; // Create a Form widget. class Registration extends StatefulWidget { const Registration({Key? key}) : super(key: key); @override MyCustomFormState createState() { return MyCustomFormState(); } } // Create a corresponding State class. // This class holds data related to the form. class MyCustomFormState extends State<Registration> { … -
Django embed/dispaly .pdf in page
I am attempting to display .pdfs that have been uploaded by users. I can display the path to the pdf but not document itself. I attempted to use "" in the template but this is not working. At least one issue is that the incorrect path to the document is used when the template is rendered. The correct file path is media/company1/documents/012022/document.pdf. The file path rendered in the template is: /documents/document/4/documents/012022/document.pd Here is my model: from django.db import models from constrainedfilefield.fields import ConstrainedFileField class Document(models.Model): title = models.CharField(max_length= 200) description = models.TextField() file = ConstrainedFileField( null=True, blank=True, upload_to='documents/%m%Y', content_types=['application/pdf'], max_upload_size=2097152, ) Here is my view: from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import ListView, DetailView, CreateView from .models import Document ... class CompanyDocumentsDetailView(DetailView): model = Document template_name = 'company_accounts/document_detail.html' ... Here is my template: <!-- templates/document_detail.html --> {% extends 'base.html' %} {% block content %} <div class="section-container container"> <div class="project-entry"> <h2>{{ document.title }}</h2> <p>{{ document.description }}</p> <p><embed src="{{document.file}}" type="application/pdf" height="700px" width="500"/></p> </div> </div> {% endblock content %} -
How to check for duplicate records in a Django admin inline?
How do you do perform validation checks involving multi-inline forms in Django admin inlines? For example, I have a simple Parent/Child model, with an admin interface showing the children in an inline table on the parent's admin change page. Each child has a "name" field which must be unique. On child model, I've implemented a clean() method to enforce this rule, raising a forms.ValidationError so the error is displayed in a user-friendly fashion in the admin UI. This method is called from the model's full_clean() method, which is called by Django admin during the validation step for each inline form. So, individually, if the user attempts to create a child record, that check caches the error. However, since Django runs the validation for each inline table separately before saving the records, it doesn't cache duplicates in the new data. So if the user creates two new inline rows and enters duplicate names in each of those rows, they pass the validation check, but then when Django goes to actually save the records, it encounters the exception, which is now handled like a very user-unfriendly 500 error. Is there an easy way to fix this? Looking through Django's code, I'm not … -
Restrict access to files from users except the superuser Django
I'm currently writing an app with Django and I want to restrict access to private files (except superuser). My files are served on Nginx For now, all the files request comes to the Django app and if the user has the right permission it will redirect to the Nginx to serve the file with the "X-Accel-Redirect" set in the Response: if user_has_right_permission or request.user.is_superuser: response = HttpResponse() response['X-Accel-Redirect'] = path return response else: raise PermissionDenied() These files need user authentication and to access each file user should send the token in the request header. The problem is when the superuser in the admin panel wants to download files got 403 Forbidden. because the token is not set in the request header. Can someone please tell me how to set the token in the request header when the superuser wants to download the file? Thanks. -
Can I manually feed the language code to Django gettext()?
I have a few strings in the backend I'd need to occasionally translate to other language before using them. I plan to save the user language selection into the database so it would be easy to get it from there. But, what is unclear for me, is if I implement localization and have a couple of different language files, how can I use the right language version? I can't read the language selection from cookies, url, user session etc. Can I use the language code from my database to choose which translation I'll use? -
Heroku / Django / MySQL : 2013 'Lost connection to MySQL server during query'
I've deployed a Django app to Heroku. The app works perfect in other environemnts, but in Heroku, one out of 5 request I got a Lost connection to MySQL server during query. I'm not hitting the app a lot, just testing it and it's unusable. I'm not sure where to start debugging this. I've added CONN_MAX_AGE = 60 to the django settings with the hope that keeping the connection alive would help, but no. -
App deployment failed via gcloud - 502 bad gateway
I have deployment my django app from Gcloud but when trying to open getting 502 bad gateway error. I checked the logs and found the below error message. I am unable to find the root cause of this. Please advise how to proceed. `2022-01-20 09:33:17 default[20220120t145947] [2022-01-20 09:33:17 +0000] [20] [INFO] Booting worker with pid: 20 2022-01-20 09:33:17 default[20220120t145947] [2022-01-20 09:33:17 +0000] [20] [ERROR] Exception in worker process 2022-01-20 09:33:17 default[20220120t145947] Traceback (most recent call last): File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/workers/gthread.py", line 92, in init_process super().init_process() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp return util.import_app(self.app_uri) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/gunicorn/util.py", line 358, in import_app mod = importlib.import_module(module) File "/opt/python3.9/lib/python3.9/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 986, in _find_and_load_unlocked File "", line 680, in _load_unlocked File "", line 850, in exec_module File "", line 228, in _call_with_frames_removed File "/srv/main.py", line 1, in from OCRdJANGO_BETA_PROJECT.wsgi import application File "/srv/OCRdJANGO_BETA_PROJECT/wsgi.py", line 12, in … -
Is it necessary to have a model and inheritance in class based views?
class home(ListView): template_name='blog/base.html' This doesn't work and gives this error -- ImproperlyConfigured at / home is missing a QuerySet. Define home.model, home.queryset, or override home.get_queryset(). but when I create a model with no data class home(ListView): model = Post template_name='blog/base.html' This works perfectly fine -> In same way when I don't inherit ListView class home(): model = Post template_name='blog/base.html' It gives the following error in urls.py from django.urls import path,include from . import views from .views import home urlpatterns = [ # path('',views.home,name='blog-home'), path('',home.as_view(),name='blog-home') ] AttributeError: type object 'home' has no attribute 'as_view' I don't have any idea about both of these -
Forbidden (Origin checking failed - chrome-extension:// does not match any trusted origins.)
Well it's been two days and I still stuck in this, help will be appreciated, first I will explain what I try to do: I'm trying to make a Django API app that allows me to save some actions that I will perform on my browser (web searchs, calls, message sending, etc.) and see all this later on my own web site, I made a simple chrome extension to do that. I deployed the web app already to heroku and it works fine when CSRF protection is off, but when I add this protection I get the 403 error because: Origin checking failed - chrome-extension://theIDofMyExtension does not match any trusted origins.) I already installed django-cors-headers library and make all the necesary setup (it worked on my own computer): https://pypi.org/project/django-cors-headers/ I added to the CSRF_TRUSTED_ORIGINS list the chrome-extension origin like this: CSRF_TRUSTED_ORIGINS = ['chrome-extension://nfbjppodghgcapmokljafeckhkmbcogd'] I guess is not working because this reference: https://docs.djangoproject.com/en/4.0/ref/settings/#csrf-trusted-origins says that origins need to be https or http, the reference also says that request must have a referer header that matchs with origin host so I added a referer header to the chrome extension request as follows: let request = new Request(url, { method: 'POST', credentials: 'include', … -
Can't login while data is true and login button seems doesn't work
I make authentication app which is register and login with email and password using django and when I run my app the button login is not responding and then back to login page I have tried to create new account and it saved on database (I use DBBrowser SqLite app) but when I want to do login then the login button is not working this is views.py def login_request(request): if request.method == "POST": form = FormPengguna(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(email=email, password=password) if user is not None: login(request, user) messages.info(request, "Berhasil Login") return redirect("halaman_utama:homepage") else: messages.error(request, "Email/Password Salah!") form = FormPengguna() print(request.POST) return render(request=request, template_name="masuk.html", context={"form": form}) this is html code <form method="POST" action="/login_request" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group row"> <label class="col-sm-2 col-form-label">Email :</label> <div class="col-sm-4"> {{ form.email }} </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Password :</label> <div class="col-sm-4"> {{ form.password }} </div> </div> <button class="btn btn-primary" type="submit">Login</button> </form> <br><br><br> <p class="text-center">Forgot Password? <a href="/password_reset_request">Click Here</a>.</p> -
How to send a text message from Django API in the response body to a React function at client end?
My requirement is to send a piece of JSON code from my React function to a Django server at the backend. The Django API will process the code and send a message if any error is found during processing or nothing (blank response). I am trying with the following piece of code, however not able to capture the response text in React API sent from Django API. The React API code looks as below: I could not find anything sent from the Django API in the body of the response object as it's coming as null. class Counter extends React.Component { constructor(props) { super(props); this.state = { code: {"name": "simon"} }; this.sendCode = this.sendCode.bind(this); } sendCode(code) { let url = "http://127.0.0.1:8000/api/sendcode?code="+ encodeURIComponent(code); fetch(url, { method:'GET', mode: 'no-cors', // body: JSON.stringify(code) }).then(function(response) { console.log("Response = ", response); }); } render() { return ( <React.Fragment> <button onClick={ ()=> this.sendCode(this.state.code)}className='btn btn-secondary btn-sm'>Send JSON code</button> </React.Fragment> ); } } The Django code looks as below: urls.py from django.urls import path from . import views urlpatterns = [ path("api/sendcode/", views.response_back, name='response_back') ] views.py Initially tried to send a JSON code back as response, getting no success, just trying to send a simple text message. from … -
Can I add large numbers of filters programmatically
I have a table with about 30 columns and I'd like to attach five filters to most columns in a highly repetitive manner. So I hoped that I could use a class decorator to define them as per this SO answer. No joy. TypeError: 'NoneType' object is not callable (at runtime when I invoke the view) Anyway, then I read up about "proper" metaclassing and tried class SettingsMeta(type): def __new__(cls, clsname, bases, attrs): for name in ('fx_t', 'status'): # just two for now but target ~60 with 5 different lookup_expr attr_name = name + '_start' attrs[attr_name] = FD.CharFilter( field_name = name, lookup_expr = 'istartswith' , label = name.replace('_t','').capitalize() + ' starts with', ) return super(SettingsMeta, cls).__new__(cls, clsname, bases, uppercase_attrs) class SelectMaskdataFilters( FD.FilterSet, metaclass=SettingsMeta): class Meta: model = Maskdata fields = { 'notes': [ 'icontains',], } #status_sw = FD.CharFilter( field_name='status', lookup_expr='startswith') ... Again no joy: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases at server start-up. SelectMaskDataFilters is itself working as expected in a view if I just remove metaclass=SettingsMeta I'm in over my head, but I really don't like repeating myself with a hundred or so filter … -
Django join ManyToManyField with Intersection Table - Soft Delete
There are three models - Role,Permission, and their intersection as RolePermission Every models have a active_status flag to denote soft delete. Now when we are trying to fetch all roles joined with their respective active positions through RolePosition model, the Inactive ones are still there. class Role(models.Model): name = models.CharField(_('Role Name'),null=False,max_length=255,unique=True,blank=False) organization = models.ForeignKey('organization.Organization',blank=False, null=True,on_delete=models.SET_NULL) active_status = models.CharField(max_length=40,choices=(('ACTIVE','ACTIVE'),('INACTIVE','INACTIVE')),default='ACTIVE') created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(null=True) permissions = models.ManyToManyField(Permission, through='RolePermission') #------------------plan details --------------------- class Meta: verbose_name = "role" db_table = 'ontym_roles' def __str__(self): return self.name def save(self, *args, **kwargs): ''' On save, update timestamps ''' timestamp = timezone.now() if not self.id: self.created_at = timestamp self.updated_at = timestamp return super(Role, self).save(*args, **kwargs) #----------------------- manp many to many role permissions ------------------- class RolePermission(models.Model): role = models.ForeignKey(Role,null=False,blank=False,on_delete=models.CASCADE) permission = models.ForeignKey(Permission,null=False,blank=False,on_delete=models.CASCADE) active_status = models.CharField(max_length=40,choices=(('ACTIVE','ACTIVE'),('INACTIVE','INACTIVE')),default='ACTIVE') created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(null=True) class Meta: verbose_name = "role_permission" db_table = 'ontym_role_permission' def save(self, *args, **kwargs): ''' On save, update timestamps ''' timestamp = timezone.now() if not self.id: self.created_at = timestamp self.updated_at = timestamp return super(RolePermission, self).save(*args, **kwargs) roles = Role.objects.filter(rolepermission__permission__active_status__exact='ACTIVE') And getting a response -> { "status": true, "code": 200, "message": "All Roles fetched sucessfully for current organization", "data": [ { "id": 1, "name": "ROLE_MANAGER", "active_status": "ACTIVE", "permissions": [ … -
504 Gateway Timeout The gateway did not receive a timely response from the upstream server or application
When i deployed my django project on ubuntu server, i got this error on webpage: Gateway Timeout The gateway did not receive a timely response from the upstream server or application. my custum apache error log is: [wsgi:error] [pid 395259:tid 139814842119936] [client 188.211.36.201:43695] Timeout when reading response headers from daemon process 'example.com': /home/myuser/apartment/apartment/wsgi.py [wsgi:error] [pid 395259:tid 139814850512640] [client 178.63.87.197:38586] Timeout when reading response headers from daemon process 'example.com': /home/myuser/apartment/apartment/wsgi.py Apache error log shows: Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f2936b06c40 (most recent call first): <no Python frame> Python path configuration: PYTHONHOME = '/home/myuser/envb9/lib/python3.8/site-packages' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/myuser/envb9/lib/python3.8/site-packages' sys.base_exec_prefix = '/home/myuser/envb9/lib/python3.8/site-packages' sys.executable = '/usr/bin/python3' sys.prefix = '/home/myuser/envb9/lib/python3.8/site-packages' sys.exec_prefix = '/home/myuser/envb9/lib/python3.8/site-packages' sys.path = [ '/home/myuser/envb9/lib/python3.8/site-packages/lib/python38.zip', '/home/myuser/envb9/lib/python3.8/site-packages/lib/python3.8', '/home/myuser/envb9/lib/python3.8/site-packages/lib/python3.8/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f2936b06c40 (most recent call first): <no Python frame> /etc/apache2/sites-available/apartment.conf is: <VirtualHost *:80> ServerName example.com … -
How to use several bootstrap modal in one view for CRUD action in Django?
I have a view by several modal and forms like Add_image , Add_birthday and a table for show all object. I want for every ROW create button and modal for edit. When user click Edit_button open a modal show form model object and user edit forms and save it. How to show special object and update it in modal. -
messages not appearing in admin on AWS dev server Django-3.1
context: Django 3.1 app deployed to a AWS lambda with terraform. I have not set up my production settings yet, this is my dev server. I'm using https://github.com/adamchainz/apig-wsgi I noticed that messages from django.contrib.messages don't appear when attempting to get the api key with djangorestframework-api-key via the admin. It being on the lambda means I'm unable to access the lambda REPL to create the api key programmatically. note: django-debug-toolbar also does not work and does so quietly, so I have a sneaking suspicion my context_processors settings are off so I don't have messages or DEBUG variables but I can't find the issue in my settings?? Below is my code without debug toolbar settings. project/settings/base.py DEBUG = True INSTALLED_APPS = [ 'app', 'rest_framework', 'rest_framework_api_key', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] 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', ], }, }, ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' AWS_STORAGE_BUCKET_NAME= [redacted] AWS_DEFAULT_ACL = [redacted] AWS_QUERYSTRING_AUTH= [redacted] AWS_S3_REGION_NAME = [redacted] AWS_LOCATION = [redacted] USE_I18N = True STATIC_URL = '/static/' REST_FRAMEWORK = { ... 'DEFAULT_PERMISSION_CLASSES': [ "rest_framework_api_key.permissions.HasAPIKey", …