Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a "check-in/check-out" system with timestamps?
I have an app that sort of works in a check-in/check-out manner. People just enter their ID, area, and click check in and it sends the timestamp to the db with their info. There is also a "check-out" button that currently does nothing. It's supposed to work so that, once the person fills the form and submits, it'll will either do one of these things: Find the previous check in entry based on the ID and Area entered and update the check out from NULL to timestamp. If the person forgot to previously check in, then it will create a new record with just the check out timestamp and the ID/Area. I thought that trying to find the user by matching both ID AND Area would be better since the same person can check in/out of different areas several times a day so matching only by ID could generate the problem of the program updating the wrong field at one point. models.py class WorkArea(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class StationNumber(models.Model): work_area = models.ForeignKey(WorkArea, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.IntegerField(max_length=50, help_text="Employee #", blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, … -
Django throws "[12728] ERROR: CREATE DATABASE cannot run inside a transaction block" when tried to create postgresql database
I'm running django 2.1.4 on python 3.6 with latest Postgresql. Problem is, when I'm trying to create database from django code, it returning "current transaction is aborted, commands ignored until end of transaction block". Here is my code -> database create code But it creates the database from django shell -> shell image Here's the postgres log error -> [12728] ERROR: CREATE DATABASE cannot run inside a transaction block Here's the terminal errors generated -> Traceback (most recent call last): File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\promise\promise.py", line 487, in _resolve_from_executo r executor(resolve, reject) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\promise\promise.py", line 754, in executor return resolve(f(*args, **kwargs)) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\graphql\execution\middleware.py", line 75, in make_it_p romise return next(*args, **kwargs) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\contextlib.py", line 52, in inner return func(*args, **kwds) File "D:\xERP\graphqltest\users\schema.py", line 68, in mutate db.save() File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 718, in save force_update=force_update, update_fields=update_fields) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 748, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 831, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py", line 869, in _do_insert using=using, raw=raw) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\manager.py", line 82, in manager_metho d return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\query.py", line 1136, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\sql\compiler.py", line 1289, in execut e_sql cursor.execute(sql, params) File "C:\Users\Envy\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\utils.py", line 100, in … -
Setup nginx-ingress to match two paths to the same serviceName and servicePort
What I'm tryng to do Traffic to / needs to go to the FE client running on 3000. Traffic to /api needs to go to the BE server. apiVersion: extensions/v1beta1 kind: Ingress metadata: name: ingress-service annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/add-base-url: "true" nginx.ingress.kubernetes.io/rewrite-target: /$1 spec: rules: - http: paths: - path: /?(.*) backend: serviceName: client-cluster-ip-service servicePort: 3000 - path: /api?/(.*) backend: serviceName: server-cluster-ip-service servicePort: 5000 The problem # urls.py urlpatterns = [ path('auth/', include('authentication.urls')), path('admin/', admin.site.urls), ] Fetches to /api/auth work fine. Fetches to /api/admin do not. Django removes the /api from the URL making it just /admin which doesn't exist. This seems to be the default behavior of Django. As far as I can tell there is no way to override it. What does work - path: /?(.*) backend: serviceName: server-cluster-ip-service servicePort: 5000 Navigating to /admin works fine. However, this removes the ability for traffic to be routed to the client. Somehow, I need to prevent Django from stripping off the prefix. Or maybe there is a way to handle this type of routing from nginx-ingress. What doesn't work Any variation of the following: - http: paths: - path: /?(.*) backend: serviceName: client-cluster-ip-service servicePort: 3000 - path: /api?/(.*) backend: serviceName: server-cluster-ip-service … -
Unable to access webcam on other devices connected to local server of Django app
I am creating a camera web app using Django. My aim is to access the webcam or camera of the user's device and display it on screen. I hosted the web app locally. I am able to access the webcam on main device but I am unable to access it on other devices that are connected to it. I am using javascript to access the webcam. <script> var video = document.getElementById('videoElement'); function webcam(){ if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }) .then(function(stream) { video.srcObject = stream; }); }} </script> How to solve this problem? -
RuntimeError("populate() isn't reentrant") on elastic beanstalk
I'm running django on Elastic Beanstalk and after pushing a new version of the app I'm getting a 500 internal server error. The logs show this: apps.populate(settings.INSTALLED_APPS) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py", line 83, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant mod_wsgi (pid=21994): Target WSGI script '/opt/python/current/app/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=21994): Exception occurred processing WSGI script '/opt/python/current/app/wsgi.py'. Traceback (most recent call last): File "/opt/python/current/app/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup Any advice on debugging this? My attempts to understand it/google it so far have been unsuccessful. -
How to upload csv to Django display csv data in table
How to upload CSV data into given field, but not save the data, save the only file into media/folder. I would like to display the data in table format and push the data out to do something via python. Here is the flow: USER(upload .csv) >> save the file >> read the file and display in table >> (no need to save the data) >> Button to run python script to take csv data and to other server. Do I need Model define each field, if I am not saving the data? How to save the file into the directory? In the form, should it form.Form() Thanks for the help -
django: Can not find the Data table row of the Extra field on many-to-many relationships?
Hello i am trying to understand Django Data Models and it´s possibilities. After using one-to-one and m2m i am now trying to understand the m2m extra fields. So i followed the Example of the Django Doc and populated the models with some Data. models.py class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) So far everything is fine, but as i looked into the model tables, via pgAdmin 4 ( i am using PostgreSQL), i could not find any members column in the Group model. So i made a little visual of my model and some screenshots of pgAdmin, for better understanding. As you can see Group has only a id and name column. Question my question: Is this m2m members relation of Group, only some kind of "virtual" created relation via the Membership.person.fk and Membership.group.fk? Meaning there is no field which will be populated? I try to imagine that it works like a recursive, instance query? -
How to Implement Non-endpoint API Functions?
This is a pretty high level question but I have been unable to find anything that explains it elsewhere: I have a django class-based view with endpoints (GET, POST) but I have another method that's not an endpoint but I would like to include as it's used in the GET/POST methods. What would be the best practice for implementing this? For example: class users(APIView): def get(self, request): # get method helperFunction() def post(self, request): # post method helperFunction() def helperFunction(): # not an endpoint Would this be the right way to do something like this? Should helperFunction() be standalone function outside of a class? Or should non-endpoint methods be in a separate class? Apologies for the lack of specificity. -
DRF: Add a new endpoint to a detail view
In my Django and DRF app, I already have an endpoint that looks something like this: /myapp/countries/<country_id>/ and it shows the details pertaining to a specific country. Now I want to add a new endpoint that would look like this: /myapp/countries/<country_id/cities/. Note that in my particular case, there is no database relationship between countries and cities. The list of cities that belong to the specified country would be calculated by parsing a file. This is how my urls.py looks like: router = DefaultRouter() router.register(r'countries', views.CountriesViewSet) How could I add this new /myapp/countries/<country_id/cities/ endpoint? Remember that the cities associated to a country would be "calculated" in the viewset, there is no DB relation between those two entities. -
Assigning list as value to many to many filed in my model django
I have a table with many to many to field, Now i have a variable with nested list(list with multiple list ex. [[],[],[]] like this) i want to put that variable as values to my many to many field by obj.fieldname.set() or .add() method . But it is showing error unhashable list type . Anyone can help?? Thanks in advance -
I am working with Django inclusion_tag and Wagtail Site Setting
I am new in Django and Wagtail and I am facing little problem. I want to assess Wagtail Site Setting using Django inclusion_tag. in short, {{ settings.app_1.SimpleHtmlSettings.heading }} and {{ settings.app_1.SimpleHtmlSettings.body }} in index.html is not printing any thing. I tried total two solutions but non of them is working app_1_extras.py (simple_html = SimpleHtmlSettings.for_site(context['request'].site)) app_1_extras.py (simple_html = SimpleHtmlSettings.objects.first) models.py from django.db import models from wagtail.contrib.settings.models import BaseSetting, register_setting # Create your models here. @register_setting class SimpleHtmlSettings(BaseSetting): heading = models.CharField( max_length=255, help_text='Enter heading') body = models.CharField( max_length=255, help_text='Enter body content') views.py from django.shortcuts import render from app_1.models import SimpleHtmlSettings from django.http import HttpResponse # Create your views here. def index(request): return render(request, 'app_1/test.html') app_1_extras.py from django import template from app_1.models import SimpleHtmlSettings register = template.Library() @register.inclusion_tag('app_1/index.html', takes_context=True) def show_results(context): # simple_html = SimpleHtmlSettings.for_site(context['request'].site) simple_html = SimpleHtmlSettings.objects.first return {'simple_html': simple_html} index.py {% load wagtailsettings_tags %} <h1>{{ settings.app_1.SimpleHtmlSettings.heading }}</h1> <p>{{ settings.app_1.SimpleHtmlSettings.body }}</p> <p>Check</p> test.py {% load wagtailsettings_tags %} {% load app_1_extras %} {% show_results %} test.html only printing "Check" Thanks!!! -
Search input on every pages django
i want to add search in my website and i want search from my pages (html) ** note : i want take the label tag , i mean i have label tag called ' test ' and when user write in search bar 'test' i want view the label to user always i got this message in result page : not found so i create this form in home html page <form class="" action="{% url 'test_search_page'%}" method="get"> <div class="md-form mt-0 search-bar" id="search_form"> <input id="search_box" autocomplete="off" onkeyup="searchFunction()" class="form-control" type="text" placeholder="Write Here to Search ..." aria-label="Search" name="search"> </div> </form> and this is my view.py code : def search(request): input= 'search' my_template_keyword = ['label'] if 'search' in request.GET and request.GET['search'] and input == my_template_keyword: return render(request, 'home_page/testforsearch.html', {'search:':search}) finally this is my code in html result page : ` <div class="container"> {% if search%} {{search}} {%else%} <h2>not found</h2> {%endif%} </div> ` -
Query django model to retrieve set lists
I want to get all objects associated with a user and split the retrieved list into three different lists in the UI according to some additional logic. I'm currently doing this by setting a @property on the model and then in doing a bunch of loops and if/else in the template. This is obviously sub optimal, because I'd like to not include the section headers if there is nothing in the actual section, but since I'm pulling in one large list, there's no empty state. Current: model class Entry(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) publish_date = models.DateField(null=True, blank=True) favorite = models.BooleanField(default=False) view entries = Entry.objects.filter(user=request.user) template <strong>FAVORITES</strong> {% for obj in entries %} {% if obj.group == 'favorites' %} ... {% endif %} {% endfor %} <strong>PUBLISHED</strong> {% for obj in entries %} {% if obj.group == 'published' %} ... {% endif %} {% endfor %} <strong>DRAFT</strong> {% for obj in entries %} {% if obj.group == 'draft' %} ... {% endif %} {% endfor %} How should I add a method on the model (e.g. get_groupings) that could return a dict with three separate querysets in it ('entries['favorites]=') in a database efficient way? -
EXEC spawning gunicorn: No such file or directory when deploy a Django project
I try to deploy a django project with nginx and gunicorn. But when I start gunicorn I get error gunicorn.service: Failed at step EXEC spawning /home/project/projectenv/bin/gunicorn: No such file or directory /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/project/project/ ExecStart=/home/project/projectenv/bin/gunicorn --access-logfile - --error-logfile error.log --workers 2 --bind unix:/home/project/project.sock project.wsgi:application [Install] WantedBy=multi-user.target ls /home/project/projectenv/bin/gunicorn - it's ok. Structure of the project home oddsportal oddsportalenv bin ... oddsportal app ... oddsportal settings wsgi ... manage.py ... -
Why isn't Heroku reading my Django urls.py?
I successfully deploy using git push heroku master, but when I click "open app" inside heroku, I receive this message. I've looked at so many different threads and solutions I think I'm starting to make a mess of my settings file. ModuleNotFoundError at / No module named 'politicalexperimentpollapp.urls' Request Method: GET Request URL: https://politicalexperiment.herokuapp.com/ Django Version: 2.2.5 Exception Type: ModuleNotFoundError Exception Value: No module named 'politicalexperimentpollapp.urls' Exception Location: <frozen importlib._bootstrap> in _find_and_load_unlocked, line 965 Python Executable: /app/.heroku/python/bin/python Python Version: 3.7.3 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python37.zip', '/app/.heroku/python/lib/python3.7', '/app/.heroku/python/lib/python3.7/lib-dynload', '/app/.heroku/python/lib/python3.7/site-packages'] My folder structure: /Users/Jamie/politicalexperimentpoll/ politicalexperimentpollproject (contains wsgi, urls.py, settings.py, etc.) politicalexperimentpollapp (contains urls.py) manage.py Procfile runtime.txt requirements.txt venv .vscode urls.py in project folder: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('politicalexperimentpollapp.urls')), path('admin/', admin.site.urls), ] urls.py in app folder: from django.contrib import admin from django.urls import path from .import views urlpatterns = [ path('', views.index, name='index'), path('tr', views.tr, name='tr'), ... ] settings.py import django_heroku import os SECRET_KEY = x DEBUG = True ALLOWED_HOSTS = ['127...my ip', 'politicalexperiment.herokuapp.com'] INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'politicalexperimentpollapp', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'politicalexperimentpollproject.urls' TEMPLATES = … -
WhiteNoise "Resource interpreted as Stylesheet but transferred with MIME type text/html" when in K8S, but fine with local gunicorn deployment
When I run WhiteNoise locally with gunicorn the assets for the admin portal work just fune. Using this command: gunicorn -b :5000 --log-level=debug config.wsgi:application However, when I run them in K8S with Skaffold, I get the following: I've tried just about every solution that comes up when googling the warning message. Not sure what I'm doing wrong here, but trying to resolve it. This is all after running python manage.py collectstatic. Project structure (Django under server) settings.py import os import mimetypes mimetypes.add_type("text/css", ".css", True) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ['SECRET_KEY'] DEBUG = False ALLOWED_HOSTS = [ 'localhost', '192.168.99.106', '127.0.0.1' ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Third-party packages 'rest_framework', # Local packages 'authentication' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'config.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ['PGDATABASE'], 'USER': os.environ['PGUSER'], 'PASSWORD': os.environ['PGPASSWORD'], 'HOST': os.environ['PGHOST'], 'PORT': os.environ['PGPORT'] } } REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, … -
Is it possible to use 'disabled' argument on a choice field in UpdateView
I have been trying to disable the dropdown field (Choice) in my UpdateView. Tried out many things some of which on my own using the little expertise(!) gained so far and majorly from the suggestions available of the net (including SO). But as is clear (the reason I am posting a query here) a solution has so far eluded me. This page talks about the issue and the answer by Mike Mahmud talks about possible solution. In response to Mike's post, @bcsanches asked if the solution may be applied for UpdateView. Unfortunately there has not (so far) been a reply to the query. My question is: Can we apply the '**disabled' argument on a dropdown field?** When I tried to use this: 'plant': forms.Select(attrs={'disabled': 'disabled', 'style': 'background:lightgrey'}) it leads to error "This field is required" on form submission. When I used 'readonly' as this: 'plant': forms.Select(attrs={'readonly': 'readonly', 'style': 'background:lightgrey'}) there is no effect (the user can select the choice field and manipulate selections). When I used 'readonly' on widget TextInput (which I presume is not the right thing to do for a dropdown), I get only the field's FK field's value (which incidentally is a char field in the Plant … -
initMap is not a function when I try to add multiple click listeners to markers django
I've used Google maps in my Django project's HTML page and it works great, added multiple markers and it was good. When I tried to catch the clicking event for each marker, it gave me this error initMap is not a function, Here is my code: <style> #map { height: 400px; /* The height is 400 pixels */ width: 100%; /* The width is the width of the web page */ } </style> <div id="map"></div> <script> // Initialize and add the map function initMap() { var gmarkers = []; const cairo = {lat: {{the_lat}}, lng: {{the_long}}}; const map = new google.maps.Map( document.getElementById('map'), {zoom: 15, center: cairo}); // The marker, positioned at Uluru {% for item in all_data %} var location{{ item.val.station_geohash }} = { lat:{{item.val.station_latitude}}, lng:{{ item.val.station_longitude }} }; var marker{{ item.val.station_geohash }} = new google.maps.Marker({ position: location{{ item.val.station_geohash }}, map: map, draggable: false, title: "{{item.val.station_name}}", animation: google.maps.Animation.DROP, }); gmarkers.push(marker{{ item.val.station_geohash }}); google.maps.event.addListener(marker{{ item.val.station_geohash }}, 'click', function () { var name = marker.title; alert(name) } {% endfor %} ); } </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=***************************&callback=initMap"> </script> -
Finding Django template inheritance chain?
Given the path to a Django template, is there any easy way to find a list of the template's inheritance chain? For example, if mytemplate.html inherited from user-section-base.html, which inherited from global-base.html, it would be something like: >>> print(get_template_chain('myapp/mytemplate.html')) >>> ['/project/myapp/templates/myapp/mytemplate.html', '/project/myapp/templates/myapp/user-section-base.html', '/project/myapp/templates/myapp/global-base.html'] I'm trying to write a static site generator that automatically regenerates static pages from Django templates, and I need to detect when the underlying template changes since last generation. For a single flat template with no inheritance, this is trivial, but for a template that inherits from a parent, which also inherits from a parent, I need to track changes of those files as well. However, I can't find any simple way to retrieve this, short of manually parsing the {% extends ... %} tags directly. What's the best way to do this? -
Babel/Core-JS not finding own files -- AWS EB Django
I'm having a hard time getting ReactJS and all its dependencies working properly on an AWS Elastic Beanstalk environment. Currently, I'm trying to get Babel to work. It doesn't seem to know where it has installed itself to -- what folder it's in. For example, you should be able to use "@babel/preset-env" for a preset name, but I've found I need to give the full path, "/opt/elasticbeanstalk/eb_infra/node_modules/@babel/preset-env", or else it won't be able to find it. (Similar with other presets/plugins.) I've gotten most things into a working state using this approach, except for core-js. It seems to be looking in /tmp/ to find its own modules. Weird, but I was able to add a symbolic link from there to its actual location. But now, it can't find core-js/modules/es.string.split. I looked in the real modules folder and sure enough, that file doesn't exist. So my question is, what is the file es.string.split (apart from the obvious -- some polyfill for String.split), why is it not looking for e.g. es6.string.split (which also doesn't exist), why is it missing, etc. etc. How do I get this to work. Error message I'm getting: [Application update [...]/Command 02_compress] : Activity execution failed, because: CommandError: An … -
Django view doesn't output correctly
I have a view which should output if the domain on the database is online or offline. def pingDomain(request, page): page_object = get_object_or_404(Table, page=page) try: subprocess.check_call(['ping', '-c', '1', page_object.page]) except subprocess.CalledProcessError: host_online = True else: host_online = False context = { 'online': host_online, } return render(request, 'home.html', context) On the html template <th class="center-align red-text text-darken-4" scope="row"> {% if online %} <i class="small material-icons green-text">check_circle</i> {% else %} <i class="small material-icons red-text">close</i> {% endif %} </th> The problem is, on the html template, it shows that the domains are offline but are actually online. Where did I make a mistake? Anyone familiar with this? -
Django DictReader change " " values in name[""] == " " in None
I want to replace from all 40 columns the null data from an uploaded csv file. Can i loop trough all columnnames in one and replace the " " with none at the moment i have: f = io.TextIOWrapper(form.cleaned_data['data_file'].file, encoding='utf-8') f.readline() reader = csv.DictReader(f) for item in reader: if(item['columnname'] == ''): item['columnname'] = None but i dont want to do that for 40 column names.. But is this possible? Can i loop trough all columnnames in one and replace the " " with none at the moment i have: f = io.TextIOWrapper(form.cleaned_data['data_file'].file, encoding='utf-8') f.readline() f.readline() reader = csv.DictReader(f) for item in reader: if item == '': item = None if(item['columnname'] == ''): item['columnname'] = None -
Toggling favorite item(s) on a list of items - how can i autosave items by the user, without using a submit <input>
I have a list of items displayed on a web page and i want the user to be able to favorite items on that list and for it to autosave/update in the db. How could this be done without having a submit input/btn? function myStar(id) { document.getElementById("Star_"+ id).classList.toggle("hidestar"); document.getElementById("Starfill_"+ id).classList.toggle("showstar"); } Thanks -
How to use complete database from MySQL without using models in Django
I am new to Django, and I was given a complete MySQL database with all relations and tables set. I am trying to put this data from MySQL database into my admin site. I want to know if there is any other way to retrieve data from MySQL database without using Django models. MySQL Database MySQL database I tried to use autogenerated model, but it did not work for me. Data doesn't show up in the admin site. (P.S. I do not necessarily require data to be in admin site, I am just trying to use it any ways possible) Auto-generated model by django python manage.py inspectdb > models.py admin.py from django.contrib import admin # Register your models here. from .models import Ligand admin.site.register(Ligand) Please, let me know if you know any ways to use data from MySQL database that was not created using Django model. Thanks in advance -
channels_rabbitmq connection immidiatly killed
I am running django channels on daphne behind nginx with via docker-compose. I am using rabbitmq for the channels layer. When channels attempts to connect to rabbitmq on my production server, the connection is immidiatly killed. channels log output (repeated every second): web_channels_1 | 2019-10-22 14:15:03,991 INFO Channels connecting to RabbitMQ at amqp://user:bitnami@rabbitmq:5672 web_channels_1 | 2019-10-22 14:15:03,994 ERROR An open stream was garbage collected prior to establishing network connection; call "stream.close()" explicitly. web_channels_1 | 2019-10-22 14:15:03,995 WARNING Connect/run on RabbitMQ failed: OSError(9, 'Bad file descriptor'); will retry in 1.000000s This is only a problem on the production server running debian 9, i cannot reproduce it on any of my local machines, also running debian 9. The problem also persist when using the build in django debugging server instead of nginx + daphne. Django channel layer settings: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_rabbitmq.core.RabbitmqChannelLayer", "CONFIG": { "host": 'amqp://user:bitnami@rabbitmq:5672', }, }, } Docker-compose rabbitmq service: rabbitmq: image: 'bitnami/rabbitmq:latest' networks: - database_network restart: always The network has a bridge driver and is shared with the daphne service amongst several others. If anyone has any idea what this could be, it would be really appreciated.