Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How does the site react if there are too many requests?
I'm calling the API through another site with Django. How can I do a simple performance test? How long will it last when I make a request.get 500,000 for example? I tried something like this, but it's ridiculous. a = 1 while a < 1000: a += 1 requests.get('http://www.test.crm/api/v1/User/' + user_id, headers={"Authorization": credentials}).json() -
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'routing'
I am trying to build a multiplayer game in Django, for which I needed to work on Django channels. but here's the issue while running it. Performing system checks... System check identified no issues (0 silenced). September 27, 2019 - 05:38:35 Django version 2.2.5, using settings 'multiproject.settings' Starting ASGI/Channels version 2.1.5 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Exception in thread django-main-thread: Traceback (most recent call last): File "/home/augli/.local/lib/python3.6/site-packages/channels/routing.py", line 33, in get_default_application module = importlib.import_module(path) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'routing' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/augli/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/augli/.local/lib/python3.6/site-packages/channels/management/commands/runserver.py", line 101, in inner_run application=self.get_application(options), File "/home/augli/.local/lib/python3.6/site-packages/channels/management/commands/runserver.py", line 126, in get_application return StaticFilesWrapper(get_default_application()) File "/home/augli/.local/lib/python3.6/site-packages/channels/routing.py", line 35, in get_default_application raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'routing' Here's my settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', … -
How do I get data from html form in Django with similar name?
I know how to get the data for 1 item with a specific name, but no idea how to with a list of item with similar name. view.py request.POST.get("item_1") request.POST.get("item_2") request.POST.get("item_3") ... I also don't know the number of item. The number of item depend on the user since I'm using dynamic add. Please help! -
Post of data from ListBox is not being rendered to the database
I have an app that takes as one of the form fields a multiple listbox. The data is defined on the html page as "temp_groups", then in the view.py the form.cleaned_data['actual field'] is set to the extracted temp field. The data extracted appears correct (2,3) and looking at the same field after the form.save() is executed looks correct. But the data is not rendered to the database that way. It is using the value set on the actual "hidden" field on the html page. Here is the code Tried using the actual field name (group_members) but the result is only the last value selected from the list is actually posted. Also tried setting up a widget on the forms.py file where the data used in supplying comes from the query of the User object (auth_user). But this had no impact. url.py urlpatterns = [.. path('newgroups/', views.newgroups, name='newgroups'),.. forms.py class QueryGroupsForm(forms.ModelForm): class Meta: model = QueryGroups fields = ['group_name', 'group_desc', 'group_members', ] models.py class QueryGroups(models.Model): group_name = models.CharField(max_length=40, null=True, blank=True) group_desc = models.CharField(max_length=100, null=True, blank=True) group_members = models.CharField(max_length=100, null=True, blank=True) querygroups.html ... <div class="col-3"> <div class="form-group"> <label for="temp_members" class="" style="font-weight: bold;">Group Members<label> <select id="temp_members" name="temp_members" class="form-control" multiple="multiple"> {% for nextUser in … -
Django storages + Dropbox API: get files by name
I have a Django app set to use Dropbox to store media files with Django Storages package. It works fine and I can retrieve uploaded files. Now I want to do the following. I created a folder in Dropbox where I copied a bunch of PDF invoices manualy. In my database I have the invoice numbers, so I want to seek the corresponding file and show it. PDFs have the number as file name. I tried simple links using {{ MEDIA_ROOT }} but I get a path diferent tha the ones generated by Django Storages when files are uploaded. I´m not able to set the right path. Is there a way I can achieve this? Can I retrieve files by name using Django Storages and Dropbox API? Thanks! -
django rest framework dynamic url route
I'm currently doing a small project in Django (2.2.5) and djangorestframework (3.10.3). I'm having a problem getting the view connected to the router. I'd really appreciate a second pair of eyes to help me try to figure out what is wrong For the urls I have tried the following 2: router = routers.DefaultRouter() router.register(r'<chatroom>', views.ChatRoomViewSet) router.register(r'<str:chatroom>', views.ChatRoomViewSet) and then added the router to urlpatterns. The viewset is: class ChatRoomViewSet(viewsets.ModelViewSet): queryset = ChatRoom.objects.all().order_by('name') serializer_class = ChatRoomSerializer lookup_field = 'name' def get_viewset(self, request, name=None): name = self.kwargs.get('name', None) queryset = ChatRoom.objects.filter(name=name) return queryset And the serializer is class ChatRoomSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ChatRoom fields = ['url', 'name'] lookup_field = 'name' The model is: class ChatRoom(models.Model): name = models.CharField(max_length=255, default="") def __str__(self): return self.name Is there something I obviously missed? -
Show help for command from within Django management command
I want to show the output of manage.py <command> help if there are not enough meaningful args to execute the command. My code looks like: class Command(BaseCommand): def __init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs) def add_arguments(self, parser): parser.add_argument( 'args', metavar='item', nargs='*', help="item = 'users'|'data'|..." ) def handle(self, *args, **options): items = [x.lower() for x in set(args)] if not items: call_command('startapp', '--help') call_command() seems like an expensive way to call help. Is there a method that I can call on self that will do the same thing? -
How Do I Display The Category Name and Description?
How do I go about displaying the category name and short description from the category model onto the categories.html page? I ask this because I can't figure it out and I go the code from the internet so a little unclear how it works. So the code right now takes you to a page like example.com/cat-slug and then shows all the post under that category but how do I display the current category's name on that page (categories.html) as along with the category description too? models.py: class Category(models.Model): name = models.CharField(max_length=100) short_desc = models.CharField(max_length=160) slug = models.SlugField() parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "categories" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) class Post(models.Model): user = models.CharField(max_length=50, default=1) title = models.CharField(max_length=120) short_desc = models.CharField(max_length=50) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) tags = TaggableManager() content = models.CharField(max_length=1000) publish = models.DateField(auto_now=False, auto_now_add=False,) slug = models.SlugField(unique=True) def __str__(self): return self.title def get_cat_list(self): k = self.category breadcrumb = ["dummy"] while k is not None: breadcrumb.append(k.slug) k = k.parent for i in range(len(breadcrumb)-1): breadcrumb[i] = '/'.join(breadcrumb[-1:i-1:-1]) return breadcrumb[-1:0:-1] views.py: def show_category(request, hierarchy=None): category_slug = … -
Django prevent superuser from seeing data in /change/ page
I'm using Django 2.1.5 and have been using the list_display in ModelAdmin-based classes to limit what our superusers can see in the admin pages. There is some sensitive data that only the user should have access to. Say I have a app based on model SensitiveObject with id, name, secret, etc., I can simply exclude secret from the list_display and it will never show up in the Admin page. However, when I browse to /admin/full/myapp/sensitiveobject/ I will have a list of those object IDs and can simply go to /admin/.../sensitiveobject/<id>/change/ which will show all of the fields, including the ones that I excluded from list_display. Is there a way to limit what I'm seeing in the /change/ endpoint, as well? -
How To Solve An Error After I Install Python Manage.py Migrate?
I follow the tutorial from Traversy Media on Youtube videos. When i put the command python manage.py migrate Then i got such an error like this C:\Users\Acer\Project\djangoproject>python manage.py migrate Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\importlib\__ init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\db\models\base.py", line 117, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\db\models\base.py", line 321, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\db\models\options.py", line 204, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length( )) File "C:\Users\Acer\AppData\Local\Programs\Python\Python37-32\lib\site-package s\django\db\__init__.py", line 28, … -
Soft delete with unique constraint in Django
I have models with this layout: class SafeDeleteModel(models.Model): ..... deleted = models.DateTimeField(editable=False, null=True) ...... class MyModel(SafeDeleteModel): safedelete_policy = SOFT_DELETE field1 = models.CharField(max_length=200) field2 = models.CharField(max_length=200) field3 = models.ForeignKey(MyModel3) field4 = models.ForeignKey(MyModel4) field5 = models.ForeignKey(MyModel5) class Meta: unique_together = [['field2', 'field3', 'field4', 'deleted'],] The scenario here is that I never want users to delete data. Instead a delete will just hide records. However, I still want all non-soft-deleted records to respect unique key constraints. Basically, I want to have as many duplicated deleted records, but only a single unique un-deleted record can exist. So I was thinking to include "deleted" field (provided by django-safedelete library), but the issue becomes that Django's unique checks fail with "psycopg2.IntegrityError: duplicate key value violates unique constraint" for ['field2', 'field3', 'field4', 'deleted'] because NULL is not "equal to" NULL and it yields false in PostgreSQL. Is there a way to enforce a unique_together constraint with the Django model layout as mine? Or is there a better idea to physically delete the record, then move it to an archive database, and if the user wants the record back, then software will look for the record in the archive and recreate it? -
How can I use one database with multiple django servers?
I saw lots of information about using multiple databases with one server but I wasn't able to find contents about sharing one database with multiple servers. Using Micro Service Architectures, If I define a database and models in a django server, named Account, How can I use the database and models in Account server from another server named like Post?? What I'm thinking is to write same models.py in both servers and use the django commands --fake Then, type these commands python manage.py makemigrations python manage.py migrate and in another server python manage.py makemigrations python manage.py migrate --fake I'm not sure if this would work and I wonder whether there is any good ways. -
CRITICAL WORKER TIMEOUT
I am building an app with Docker, Django and Postgresql. I was trying to parse thourhg rows in an excel file (about 7000 rows) and got this error: web_1 | [2019-09-26 23:39:34 +0000] [1] [CRITICAL] WORKER TIMEOUT (pid:11) web_1 | [2019-09-26 23:39:34 +0000] [11] [INFO] Worker exiting (pid: 11) web_1 | [2019-09-26 23:39:34 +0000] [12] [INFO] Booting worker with pid: 12 I searched for solution and found a suggestion to increase the TIMEOUT but I don't know where to find it. Here is my yml files. version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 command: gunicorn bookstore_project.wsgi -b 0.0.0.0:8000 # new environment: - SECRET_KEY=<secret_key> - DEBUG=1 - ENVIRONMENT=development volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: docker-compose-prod-yml version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 environment: - ENVIRONMENT=production - SECRET_KEY=<Secret_key> - DEBUG=0 ports: - 8000:8000 depends_on: - db db: image: postgres:11 heroku.yml: setup: addons: - plan: heroku-postgresql build: docker: web: Dockerfile release: image: web command: - python manage.py collectstatic --noinput run: web: gunicorn bookstore_project.wsgi Any help is appreciated! Huy. -
Unable to update Django object when declaring only one field in template form
For some reason I can't seem to update my Django models object when declaring only one of its field versus all fields in the template form. Here are two cases that should seemingly get the same results but do not. When I pass the whole form to the template as so: {{ form.as_p }} the whole object updates. Whereas when I pass a single field to the template: {{ form.field }} the object doesn't seem to get updated. If you look at my views file this should not matter because the form is being passed the object instance. Therefore it should not matter if all fields are specified in the templates form because they should have already been passed to the form through the object instance. object_instance=get_object_or_404(object,pk=pk) if request.method=="POST": form=Form(request.POST,instance=object_instance) if form.is_valid(): new_object=form.save(commit=False) new_object.method() new_object.save() return redirect('results',pk=new_object.pk) else: form=Form(instance=object_instance) return render(request,'template.html') Please tell me where I am going wrong. I do not see why I can't update an object by rendering a template that displays only a single field from the objects form. -
How to configure Nginx and Django to redirect from http to https?
Sorry for the general asking. I encountered an wired problem when setting up https for a web server. It holds a website Using Nginx. The website files are generated by Django. I have already got the certificate. I configure it for Nginx: server{ listen 80; server_name: example.com; return 301 https://$host$request_uri; } server{ listen 443 ssl default server; listen [::]:443 ssl default_server; ssl_certficate /location/to/certificate/certificate.cer ssl_certificate_key /location/to/key/key.pem } It can be reached by https://example.com up to now. However, the problem is: When in the http version, there is a button, which I click it, it will show an login page with the http://hr.example.com/login in the address bar. However, after I configuring ssl for it, there is no login page , it only shows the homepage again with the https://hr.example.com/ showing in the address bar (in the http version, this address is also shown in the address bar after click the button before the login page appearing). If I manually added the /login after https://hr.example.com/, it will show the page: page not found 404 and the folowing info Using the URLconf defined in splash.urls, Django tried these URL patterns, in this order: [name='index'] <int:instance_id>/ [name='detail'] admin/ The current path, login, didn't match any … -
Django templates unexpectedly omit results from Elasticsearch
Django templates seemed to omit part of results returned by Elasticsearch_dsl. The Elasticsearch low-level python client works fine. If it is just {{source}} without "for loops", it works fine as well. The code is simply: {% for item in source %} {{item}} {% endif %} Expected results rendered by Django templates: {'_index': 'search', '_type': '_doc', '_id': '1', sentence:'abc'} Actual results: {'_index': 'search', '_type': '_doc', '_id':...} Any help will be appreciated. -
How Do I Display The Right Category Name and Description For That Category Page?
I was wondering how I can display the category name and short description from the category model onto the categories.html page? I ask this because I can't figure it out and I go the code from the internet so a little unclear how it works. So the code right now takes you to a page like example.com/cat-slug and then shows all the post under that category but how do I display the current category's name on that page as along with the category description too? models.py: class Category(models.Model): name = models.CharField(max_length=100) short_desc = models.CharField(max_length=160) slug = models.SlugField() parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name_plural = "categories" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) class Post(models.Model): user = models.CharField(max_length=50, default=1) title = models.CharField(max_length=120) short_desc = models.CharField(max_length=50) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) tags = TaggableManager() content = models.CharField(max_length=1000) publish = models.DateField(auto_now=False, auto_now_add=False,) slug = models.SlugField(unique=True) def __str__(self): return self.title def get_cat_list(self): k = self.category breadcrumb = ["dummy"] while k is not None: breadcrumb.append(k.slug) k = k.parent for i in range(len(breadcrumb)-1): breadcrumb[i] = '/'.join(breadcrumb[-1:i-1:-1]) return breadcrumb[-1:0:-1] views.py: def show_category(request, hierarchy=None): category_slug = … -
Applied CSS causes anchors to be unclickable
I have come across a very odd issue, I have noticed that all of a sudden my anchors stopped working, as in became unclickable. Then I figured it must be something related to applied CSS, and when I started disabling parts of my CSS, I narrowed down the issue to this couple of lines: .content { width: 960px; margin: auto; } My page structure looks like this: <!DOCTYPE html> <html> <head> <title>CoinShop v1.0</title> <link rel="stylesheet" type="text/css" href="/static/pages/css/reset.css"> <link rel="stylesheet" type="text/css" href="/static/pages/css/navbar.css"> <link rel="stylesheet" type="text/css" href="/static/pages/css/base.css"> <link rel="stylesheet" type="text/css" href="/static/pages/css/searchbar.css"> <link rel="stylesheet" type="text/css" href="/static/pages/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="/static/products/css/detail.css"> </head> <body> <div class='top-grid'> <div class='branding-grid-container'> <div class='branding-grid'> <div class='branding-grid-buttons-not-authenticated'> <a href="/help/" class='button-help'>Help</a> <a href="/accounts/register/" class='button-register'>Register</a> <a href="/accounts/login/" class='button-login'>Login</a> </div> </div> </div> <div class='nav-grid'> <div class='search-bar'> <form action="/shop/" method="GET"> <input type="text" name="q" placeholder="Search" class='search-box'> <input type="submit" value='Search' class='search-button'> </form> </div> <div class='nav-bar'> <nav> <ul id='menu'> <li class='menu-item'><a href="/">Home</a></li> <li class='menu-item'><a href="/shop">Shop</a></li> <li class='menu-item'><a href="/contact">Contact</a></li> <li class='menu-item'><a href="/about">About</a></li> </ul> </nav> </div> </div> </div> <div class='content'> <a href="/shop/1/">spam (2018)</a> <h1>spam (2018)</h1> <p>eggs</p> <p>Price: 200.00</p> </div> </body> </html> ...and all applied CSS combined looks like this: .top-grid { margin: auto; background-color: #3D005A; } .branding-grid-container { background-color: #4e0e7c; } .branding-grid { display: grid; grid-template-columns: 1fr 1fr 400px; … -
Update Django backend and angular fronted with rest framework
I'm trying to edit data stored in Django(backend) and angular(fronted), I have the insert and delete but I don't have an idea, how I can edit that data in Django from angular, I using in Django rest_framework. getUsuarios(): Promise<Usuario[]> { return this.http.get('http://127.0.0.1:8000/users?format=json', { headers: this.headers }) .toPromise() .then(response => response.json() as Usuario[]) } deleteUsuario(id: number): Promise<void> { const url = `${"http://127.0.0.1:8000/users"}/${id}`; return this.http.delete(url, { headers: this.headers }) .toPromise() .then(() => null) } createUsuario(d: Usuario): Promise<Usuario> { return this.http .post("http://127.0.0.1:8000/users/", JSON.stringify(d), { headers: this.headers }) .toPromise() .then(res => res.json() as Usuario) } urlpatterns = [ url(r'^doctor$', views.DoctorList.as_view()), url(r'^doctor/(?P<pk>[0-9]+)$', views.DoctorDetail.as_view()), url(r'^paciente$', views.PacienteList.as_view()), url(r'^paciente/(?P<pk>[0-9]+)$', views.PacienteDetail.as_view()), url(r'^categoria$', views.CategoriaList.as_view()), url(r'^categoria/(?P<pk>[0-9]+)$', views.CategoriaDetail.as_view()), url(r'^examen$', views.ExamenList.as_view()), url(r'^examen/(?P<pk>[0-9]+)$', views.ExamenDetail.as_view()), path(r'api-token-auth/', obtain_jwt_token), path(r'api-token-refresh/', refresh_jwt_token), url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] -
Multiple Ajax request fails after one of the requests successfully processed
I have a form to upload a picture and to do certain process on it. Since the process is time consuming I don't want to wait for the response but should be able to submit next form. In my case I am able to submit multiple form from the same web page one by one. But this issue is, when one of the request process successfully it throws an error like "Exception happened during processing of request from ('127.0.0.1', 55522)" and thus remaining process stops in the middle. I am using Djnago framework with Ajax request for this. -
How To Use Django-AutoComplete-Light Outside of Admin
I am trying to use django-autocomplete-light to create dependent dropdowns in my project as described in the 'Filtering results based on the value of other fields in the form' section of the following documentation. I am reading the docs here: https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html However, I can only find examples of how to make this work in django admin. I want this to be in my form. Can someone please clarify for me if it is possible to use django-autocomplete-light outside of the admin, and if possible provide a link to an example? -
How to filter a ModelChoiceField for an InlineFormset that is nessted?
In my forms.py, I want the referenceBFlow with the modelchoicefield to only have the related BasicFlow. Currently, all the BasicFlows are being returned when I used queryset=BasicFlow.objects.all(). I would like to know how to filter the query dynamically. For instance: If I have a profile (prof1) and basicGroup (bg1), basicflow (bf1, bf2, bf3...), AltGroup (ag1). Now, in my template, if I click on the dropdown for the referenceBFlow for ag1, it should have basicflow (bf1, bf2, bf3...). If another profile, profile (prof2) and basicGroup (bg2), basicflow (bf4, bf5, bf6...), AltGroup (ag2), the referenceBFlow for ag2 should have basicflow (bf4, bf5, bf6...). models.py - class Project(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) ... class Profile(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) ... class B_FlowGroup(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True) class BasicFlow(models.Model): basicflGroup = models.ForeignKey(B_FlowGroup, on_delete=models.CASCADE, null=True, blank=True) ... class A_FlowGroup(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True) referenceBFlow = models.ForeignKey('BasicFlow', on_delete=models.CASCADE, null=True, blank=True) class A_Flow(models.Model): altflGroup = models.ForeignKey(A_FlowGroup, on_delete=models.CASCADE, null=True, blank=True) ... forms.py - In this .py I have nested and regular inlineformsets class B_FlowGroupForm(ModelForm): class meta: model = B_FlowGroup class AltFlowGroupForm(ModelForm): class meta: model = AltFlowGroup referenceBFlow= forms.ModelChoiceField(widget=forms.Select, queryset=BasicFlow.objects.all()) class BasicFlow(ModelForm): class meta: model = BasicFlow BasicFlowFormSet = inlineformset_factory(B_FlowGroup, BasicFlow, form=BasicFlowForm, extra=1) … -
Customizing Django's error email reporting
Prior to Django 2.2, I was using a custom middleware to catch and email all error reports, including a lot of useful information, including server name and Python traceback. In Django 2.2, similar functionality is now enabled by default. Unfortunately, it's not quite as verbose as I'd like, and it overrides my custom middleware, so now I'm getting less information. Despite the doc's claims, Django's error email does not include the Python traceback nor the error from the exception. All emails are titled "Internal Server Error" and just contain a URL and the GET and POST dictionaries. You can imagine how frustrating it is to diagnose the error "Internal Server Error" with little more than a URL. How do you disable Django's custom error emailer? The docs claim it's enabled and configured by the logging settings, but even if I remove all references to django.utils.log.AdminEmailHandler in my logging configuration, Django still sends the default error emails instead of using my middleware. Alternatively, is there any way to fix the email content so it includes something useful? This is my current logging configuration: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' … -
How to update FileField filename after it's saved in Django and using S3 as the storage
I have a model that has a FileField. I want to save a generated file content before I send it to a 3th party service, after I have the response, I would like to rename it without changing the content. I think the code below would generate another file on S3 instead of renaming it to the final name. class SomeModel(models.Model): record = models.FileField() model.record.save('initial_filename', ContentFile(generated_content)) model.record.save('final_filename', model.record.read()) -
What is the recommended NOSQL database for Django Framework?
I am working on building software for analytics, I want to choose NoSQL database for my application database system. I am thinking about