Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter a query in Django for week_day using a specific timezone?
I am trying to filter data by the day of the week. That's easy enough with the week_day filter. The problem is, since all dates are stored as UTC, that is how it's filtered. How can I localize a query? For instance, trying to count all the records that have been created on specific days, I use this: chart_data = [ data.filter(created__week_day=1).count(), # Sunday data.filter(created__week_day=2).count(), # Monday data.filter(created__week_day=3).count(), # Tuesday data.filter(created__week_day=4).count(), # Wednesday data.filter(created__week_day=5).count(), # Thursday data.filter(created__week_day=6).count(), # Friday data.filter(created__week_day=7).count(), # Saturday ] How can I get these queries to count those records localized to the 'America/New_York' timezone, for instance? -
Postbuild command in elastic beanstalk doesn't work but command works when ssh into EC2 instance
In my current setup, I have a django backend running in Elastic Beanstalk and a private RDS instance using mysql engine. When I deploy, I want to migrate any migrations that haven't been migrated yet. This is the config file in my .ebextensions: container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 /var/app/current/python/manage.py migrate --noinput" leader_only: true This deploys successfully, but when I check the logs it gives me this output: [INFO] Command 01_migrate [INFO] -----------------------Command Output----------------------- [INFO] Operations to perform: [INFO] Apply all migrations: admin, app, auth, contenttypes, sessions [INFO] Running migrations: [INFO] No migrations to apply. It says no migrations to apply when there are migrations that haven't been applied yet. I ran the same exact command after I ssh into the EC2 instance for my EB application and it applied the migrations successfully. I can't troubleshoot what the problem may be. -
Auto-fill form fields in clean() method
I use model form for editing records in DB. I have some business logic for auto-fill attributes, which should happen after passing validation of some business rules. In some cases, that auto-fill is based both on instance initial attributes values and current form fields values. For example, different rules apply whether it was a change of some attribute or not. Note: I have no such cases when auto-fill based on other models except one that model form based on. So my question: Is it correct to auto-fill attributes in form clean() method? After reading a few various sources, I'm not sure I fully understood if it's acceptable and if it is, in what cases. A few words why it's not convenient for me to separate validation and auto-fill: My case is that I have quite complex validation rules and almost every time these rules passed, I need to do some auto-filling. For now I have 2 methods, one in form clean() method for validation, and one in form save() method for auto-filling. Every time I need to change business rules, I should make changes in both these methods. It's not very convenient and besides that can lead to slowing down … -
Django: Templates template not found when attempting to access function rendering template
I have a file structure: Resilience_Radar_R2 Leadership_Questions_App Leadership_Questions templates questions.html I have defined a function, riskindex, that should render questions.html and include some text on the page. I also have an index function that simply sends an HttpResponse if teh request is blank The index function works fine at http://127.0.0.1:8000/Leadership_Questions_App/ but the riskindex at http://127.0.0.1:8000/Leadership_Questions_App/riskindex returns an error: TemplateDoesNotExist at /Leadership_Questions_App/riskindex/ Leadership_Questions/questions.html Request Method: GET Request URL: http://127.0.0.1:8000/Leadership_Questions_App/riskindex/ Django Version: 5.0.7 Exception Type: TemplateDoesNotExist Exception Value: Leadership_Questions/questions.html Exception Location: /Users/xxx/Documents/Work/Python Projects/Dashboard/Reslience_Radar_R1/.venv/lib/python3.12/site-packages/django/template/loader.py, line 19, in get_template Raised during: Leadership_Questions_App.views.riskindex Python Executable: /Users/xxx/Documents/Work/Python Projects/Dashboard/Reslience_Radar_R1/.venv/bin/python Python Version: 3.12.3 Python Path: ['/Users/xxx/Documents/Work/Python ' 'Projects/Dashboard/Reslience_Radar_R2', '/Library/Frameworks/Python.framework/Versions/3.12/lib/python312.zip', '/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12', '/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/lib-dynload', '/Users/xxx/Documents/Work/Python ' 'Projects/Dashboard/Reslience_Radar_R1/.venv/lib/python3.12/site-packages'] Server time: Sat, 10 Aug 2024 19:44:06 +0000 Terminal directory is: (.venv) (base) xxx@MacBook-Pro Reslience_Radar_R2 % It appears to be looking in different directory than the one where the python code resides. Reslience_Radar_R2 urls.py rom django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('Leadership_Questions_App/', include("Leadership_Questions_App.urls")) ] Leadership_Questions_App urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("riskindex/", views.riskindex, name="riskindex"), ] views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Leadership Questions") def riskindex(request): description = … -
Why is it possible to create a model with a ManyToManyField without providing a value for the ManyToManyField?
As every field in django model is required. So how when creating an object of model which is having a field with many to many relationship to another model. We can create this model object without specifying many-to-many field value ? -
Cant serve static files in Django but serving from media
Django is v5.1 Have this settings.py: STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') This urls.py: urlpatterns = [ path('graphql', include('api.urls')), path('mdeditor/', include('mdeditor.urls')), path('admin/', admin.site.urls), path('', RedirectView.as_view(url=reverse_lazy('admin:index'))), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This overridden admin/base.html: {% extends 'admin/base.html' %} {% load static %} {% block extrahead %} <link rel="shortcut icon" href="{% static 'favicon.ico' %}" /> {% endblock %} This structure: And it's not serve static files from static folder. Just shows 404. But serving static files from media folder. I have absolutely no idea where the error can be found here. -
Import could not be resolved by any source; ModuleNotFound
I cannot make migrations due to the issue stated in the title. All of the files shown in explorer have the same issue. I didn't notice the issue until I went to make migrations for polls and returned the error: ModuleNotFoundError: No module name 'polls.apps.PollsConfigdjango'; polls.apps is not a package I am doing the basic Django tutorial and this is the only issue I have had so far. I tried changing polls.apps.PollsConfig in the installed apps section to have django at the end (as it is shown in the console error). I tried changing polls\apps.py to 'from mysite.apps' which shows the same error, as well as 'from polls.apps' which shows a circular error. I did this to see if VSCode would remove the underline showing there was no longer an error. 'from polls.apps' did remove the underline, however when making the migration it showed a circular error in powershell. I'm figuring on this being a simple beginner error and am hoping someone will know what the issue is at a glance. It wouldn't bother me at all to start this over and do it again but since I clearly made an error and therefor likely didn't understand something it would … -
Django Rest Framework - testing serializers vs testing views
I'm writing a new Django app with Django Rest Framework and trying to use TDD as much as I can but I'm a bit unsure as to where to draw the line between testing the serializer and testing the view. Let me give you an example. If I have the following serializer:- class EventMembershipSerializer(serializers.ModelSerializer): select = serializers.BooleanField(required=False) class Meta: fields = ['event'] def validate(self, attrs): if not attrs["event"].started: if "is_selected" in attrs: raise serializers.ValidationError( {"select": "Cannot set selected for event in the future."} ) return super().validate(attrs) and the following view:- class EventMembershipViewSet(viewsets.GenericViewSet): queryset = Event.objects.all() serializer_class = EventSerializer then I can write this to test the serializer:- def test_create_select( self, past_event_factory, ): event = past_event_factory() data = { "event": event.hashid, "select": True } with pytest.raises( ValidationError, match="Cannot set selected for event in the future." ): serializer = EventMembershipSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() and this to test the view:- def test_create( self, past_event_factory, api_client ): url = reverse(<url>) event = past_event_factory() data = { "event": event.hashid, "select": True, } response = api_client.post(url, data, format="json") assert response.status_code == status.HTTP_400_BAD_REQUEST assert response.data["non_field_errors"][0] == "Cannot set selected for event in the future." But this really feels like I'm testing the same thing twice to me. If … -
Django Query calculate date with `relativedelta` error: can't adapt type 'relativedelta' [Updated]
I'm facing a tricky problem and couldn't find a solution online. I hope someone here can help me figure out a "clean" way to do this. What I want to do? I want to calculate the expiration date based on the model fields: rate_type, rate_repeat, timestamp. My Django Model looks like this (I omitted unnecessary parts): class LoanModel(ContractBase): class RateType(models.TextChoices): DAILY = "DAILY", _("Daily") WEEKLY = "WEEKLY", _("Weekly") MONTHLY = "MONTHLY", _("Monthly") YEARLY = "YEARLY", _("Yearly") timestamp = models.DateTimeField( auto_now_add=True, editable=True, db_comment=_("Creation date"), help_text=_("Creation date"), verbose_name=_("Creation date"), ) rate_type = models.CharField( max_length=255, choices=RateType.choices, db_comment=_("Contract rate type: Daily, Weekly, Monthly, Yearly"), help_text=_("Contract rate type: Daily, Weekly, Monthly, Yearly"), verbose_name=_("Rate type"), ) rate_repeat = models.PositiveIntegerField( validators=[MinValueValidator(1), MaxValueValidator(8)], db_comment=_("Interest rate repetition value"), help_text=_("Interest rate repetition value. The Contract is Active for: Rate repeat * Rate type"), verbose_name=_("Rate repeat"), ) ... def get_expiration_delta(self): """ Calculate the delta of the loan """ if self.rate_type == LoanModel.RateType.DAILY.name: delta = relativedelta(days=+self.rate_repeat) elif self.rate_type == LoanModel.RateType.WEEKLY.name: delta = relativedelta(weeks=+self.rate_repeat) elif self.rate_type == LoanModel.RateType.MONTHLY.name: delta = relativedelta(months=+self.rate_repeat) elif self.rate_type == LoanModel.RateType.YEARLY.name: delta = relativedelta(years=+self.rate_repeat) else: raise ServerError(_("Unknown rate type: %(rate_type)s") % {'rate_type': self.rate_type}) return delta def loan_expired_date(self): """ Return the date when the loan will expire :return: date """ … -
Hosting django rest framework and react in shared hosting like milesweb
Currently I am developing a web app using django rest framework as backend and react as frontend. I have almost completed my development. Next I need to deploy my web app. But I am so confused which hosting technique should I use. The hosting budget is atmost ₹4000. Can I able to host my app in shared hosting platform like milesweb. Could anyone please guide me by helping me to choose the right hosting platform I am currently developing a web app with python django rest framework backend and react as frontend. I want to deploy it in any shared hosting platform. -
Docker & Django : How to dockerize my django project and run it in a specific server ip?
I want to dockerize my django project and run it on a specific server says 192.168.156.94:8000. How do I do that? Thank you Dockerfile # Use Python 3.12.2 image based on Debian Bullseye in its slim variant as the base image FROM python:3.12.2-slim-bullseye # Set an environment variable to unbuffer Python output, aiding in logging and debugging ENV PYTHONBUFFERED=1 # Define an environment variable for the web service's port, commonly used in cloud services ENV PORT 8080 # Set the working directory within the container to /app for any subsequent commands WORKDIR /app # Copy the entire current directory contents into the container at /app COPY . /app/ # Upgrade pip to ensure we have the latest version for installing dependencies RUN pip install --upgrade pip # Install dependencies from the requirements.txt file to ensure our Python environment is ready RUN pip install -r requirements.txt # Set the command to run our web service using Gunicorn, binding it to 0.0.0.0 and the PORT environment variable CMD gunicorn server.wsgi:application --bind 0.0.0.0:"${PORT}" # Inform Docker that the container listens on the specified network port at runtime EXPOSE ${PORT} command line docker build -t django-docker-project:latest . docker run -p 8000:8080 \ --env PIPELINE=production … -
Why the html and css codes is not appearing in the page of a django form wizard page?
contest_selection.html: {% extends "wizard_form.html" %} {% load widget_tweaks %}` {% load i18n %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Landing Page</title> <link rel="stylesheet" href="{% static 'styles/mainStyle.css' %}" /> <link rel="stylesheet" href="{% static 'styles/LandingPageStyle.css' %}" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> <div class="container"> <div class="Header"> <img src="{% static 'images/###.png' %}" alt="######" class="headerimg1"> <span>######################</span> <img src="{% static 'images/#####.png' %}" alt="######" class="headerImg2"> </div> <hr /> <br /><br /> <div> <p class="subtitle" style="margin-bottom: 20px;">Choose the <span style="color: #C83762;"> contests </span> you are registering in:</p> <br /> <form method="post" > {% csrf_token %} <div class="container_box"> {% for contest in contests %} <div> <label class="checkbox-container"> <input type="radio" name="contest" value="{{ contest.id }}" id="checkbox{{ forloop.counter }}" data-color="{{ contest.color }}"> <span class="checkmark" id="checkbox{{ forloop.counter }}" data-color="{{ contest.color }}"> <!-- color edit it later below--> <p style="font-weight: 800; font-size: 24px;">{{ contest.name.split('-')[0] }}-<span style="color:black;">{{ contest.name.split('-')[1] }}</span></p> <p>{{ contest.description }}</p> </span> </label> </div> {% endfor %} </div> <button type="submit">Next</button> </form> </div> <br /> <hr /> <br /> <div class="footer"> <span>Strategic partner</span> <img src="{% static 'images/#####.png' %}" alt="#######"> </div> </div> <script> document.addEventListener('DOMContentLoaded', (event) => { const radioButtons = document.querySelectorAll('input[type="radio"][name="contest"]'); radioButtons.forEach(radio => { radio.addEventListener('change', (event) => { radioButtons.forEach(rb => { const checkmark … -
Production Deployment (Apache24 with VueJS/Axios to Django DB)
I’ve hit a brick wall trying to understand how to get my PROD SSL front-end (Apache with VueJS/Axios) talking to my back-end (Django apps/views/models + database using SQLite for very lightweight I/O). All hosted on private Windows Server 2022 VM]. Clearly many options exist for the myriad configs possible but none I’ve read seem to fit this setup specifically ie running django purely as db server serving queries from rest axios calls from vuejs code, and with django sitting outside of apache (reviewed mod_wsgi, wsgi, gunicorn, etc, etc). Mod_wsgi may be the way fwd but not convinced yet. This is my 1st dep so still a bit of a newbie - just want to ensure I’m going down the right track tech wise. So at a high-level (happy to do the detailed reading) which route should I be taking?? Many thanks! PS: I ack the collectstatic step. NB: My localhost setup is all working fine using npm run serve for the front end and runsslserver for the backend. -
Django Query calculate date with `relativedelta` error: can't adapt type 'relativedelta'
I'm facing a tricky problem and couldn't find a solution online. I hope someone here can help me figure out a "clean" way to do this. This is my current function to retrieve all expired loans (it works): queryset = super().get_queryset().filter(is_active=True) expired_loans_ids = {loan.pk for loan in queryset if loan.is_expired()} expired_loans = queryset.filter(pk__in=expired_loans_ids) return expired_loans However, it's not ideal because I'm not just using a query; I must retrieve everything first. What I wanted to do was something like this: from dateutil.relativedelta import relativedelta queryset = super().get_queryset().filter(is_active=True) expired_loans = queryset.annotate( expiration_date=ExpressionWrapper( F('timestamp') + relativedelta(months=1), output_field=DateField() ) ).filter(expiration_date__lt=Now()) return expired_loans But I get this error when using relativedelta: django.db.utils.ProgrammingError: can't adapt type 'relativedelta' It works with timedelta, but each month has a different number of days... How can I accomplish something like this? -
Deploying the Django project in IIS
I'm having trouble deploying my Django project on IIS. I'm getting a 500 error, and it says that the FastCGI is either not pointing to the right place, is misconfigured, or the settings file might be incorrect. I'm having a hard time figuring out where the problem is. Could you guide me towards some concrete examples or tell me exactly what I need to do? I'm trying to deploy the Django project through the IIS, and I expect to be able to display my app through a web browser. -
Why is nothing displayed on the page in Django?
Here's a question, I have products on a page and each product has its own slug. This slug redirects to the personal page of the product, which displays all the necessary information about the product (name, description, images, etc). But for some reason the page is just empty, i.e. what is written in the html file is not displayed and I don't understand why. The redirect is error free and the product slug appears in the url, but there is no product information. P.s in the view, I use print to see in the terminal if I actually go to the product page and get the product name. And yes, I do get it in the terminal views.py def product_detail(request, post): product = get_object_or_404(ProductModel, slug=post) print(product.title) return render(request, 'products/detail-products.html', { 'product': product, }) urls.py from django.urls import path from products import views app_name = 'products' urlpatterns = [ path('', views.products, name='products'), path('product/<slug:post>/', views.product_detail, name='product_detail'), ] product-detail.html {% extends 'main/base.html' %} {% block title %}Detail {{ product.title }}{% endblock title %} {% block content %} <style> .product__detail__photo img { width: 60%; height: auto; background-size: cover; object-fit: cover; border-radius: 5px; } </style> <div class="product__detail"> <div class="product__image"> {% if product.product_images %} <img src="{{ … -
How do I successfully integrate Django and Flowbite framework
I followed the entire documentation of integrating Django and Flowbite on Flowbite's official site. Just when I thought I i successfully integrated the two frameworks, I noticed some flowbite components are not displaying the way they are supposed to. But for some components yes, the styling are working. This is causing me headache because the dashboard is among the components which are not displaying the way they're supposed to. But then the dashboard was set to be part of my main site. What might be the problem? Is there any straight forward procedure i can follow to achieve this integration? I tried using CDN, but it is causing issues to the functionalities of changing the site's background -
Django: count duoble nested revers Foreignkey
my models: class Course(models.Model): ... class Section(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='sections') ... class SubSection(models.Model): section = models.ForeignKey(Section, on_delete=models.CASCADE, related_name='subsections') registration_required = models.BooleanField(default=True) now I want to know if less than 5 subsections of a course are registration_required = False. something like: def validate(self, attrs): course = self.instance if course.sections.subsections.filter(registration_required=False).count() < 5: # do something ... what is the best way to do that ?? -
How to Retrieve Nested Form-Data in Django Rest Framework?
postman data I send this form-data in postman but request.data empty my code: class DentalClientMedicalRecordCreateAPIView(APIView): def post(self, request, *args, **kwargs): try: print(request.data) branch = request.user.branch data = request.data # Extract nested data tooth_service_data = request.data.get('tooth_service', []) print(tooth_service_data) response how to I get this multiple related entries -
Trying to match Django template table headers with values in columns when there are missing cell values
I have a Player model, an Event model, and a Pick model. Theoretically, a Player should submit a Pick for each Event, but this doesn't always happen and there may be times when a Pick is not yet submitted but will be in the following days. I have a table displaying each Player's Picks for each Event. Table header row loops through Events, then I have a regroup and loop through each Player's Picks for each table row. Below is an image of how I'd like it work. When a Pick is missing, don't print a Pick value, but skip that cell (or show a useful message to the Player): My template is pasted below, but when a Pick is missing, there aren't enough items in the queryset to match the number of table headers, and since template language is intentionally a bit naive (ie I can't break a loop, or do some other features) I am having difficulty coming up with a way to arrange this template so that an empty table cell is added. This is what my table resembles - Player 2's picks are out of alignment. The orange cells don't match the header Event, and the … -
How to resolve the error Method Not Allowed (POST) in Django?
I'm creating a POS application in Django. Currently I'm using the template bellow for adding items to a current order, modifying quantities, deletes some items that are unecessary to be in the current order, and finaly, after adding all needed items, to click on the Checkout button for validation. {% load multiply %} <!DOCTYPE html> <html> <head> <title>Order Details</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="{% url 'posApp:home' %}">POS System</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'posApp:category_list' %}">Categories</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'posApp:order_list' %}">Order list</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'posApp:create_order' %}">Create Order</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'posApp:add_category' %}">Add Category</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'posApp:product_list' %}">Products list</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'posApp:add_product' %}">Add Product</a> </li> </ul> </div> </nav> <div class="container mt-5"> <h1>Order {{ order.id }}</h1> <div class="row"> <div class="col-md-6"> <form id="add-item-form" method="post"> {% csrf_token %} <div class="form-group"> <label for="barcode">Barcode</label> <input type="text" class="form-control" id="barcode" name="barcode" placeholder="Enter Barcode" required> </div> <div class="form-group"> <label for="quantity">Quantity</label> <input type="number" class="form-control" id="quantity" name="quantity" placeholder="Quantity" min="1" value="1" … -
how to inert (not update) into a table on conflict by generating a new primary key
Currently I have two postgresql tables table1 and table2, shown below, primary key is id. table1: id | name ---------- 1 | Bob 3 | Steven table2: id | name ---------- 2 | John 3 | Jack I would like to combine these two tables by inserting table2 to table1, and table1 should look like below after the operation. Essentially, it can maintain the same primary key if there is no conflict, but when it has conflict, it will generate a new id for the incoming data from table2, and insert that as a new row in table1. In this example, Jack from table2 will be inserted as a new row with a new id of 4 (max id from table1 + 1). id | name ---------- 1 | Bob 2 | John 3 | Steven 4 | Jack Below is my current approach. Which updates the id in conflicted row in table1. INSERT INTO table1 (id, name) SELECT id, name FROM table2 ON CONFLICT(id) DO UPDATE SET id=nextval(pg_get_serial_sequence('table1', 'id')); I need help figuring out how to insert into a new role with a new id. -
django tenant local and server resolve problem
hello i develop django tenant app in localhost when i request to ebsalar.localhost:8000 every think is ok but when upload on server and use curl to check i got Could not resolve host: ebsalar.localhost local: on server: note: /etc/hosts same ... need run the same in server and local -
jQuery editable-select : validate option that is not in the list
In Django, I'm using jQuery editable-select to convert selectboxes to searchable selectboxes. https://github.com/indrimuska/jquery-editable-select/blob/master/README.md I'm searching for a way to save the value entered in the search field if it's not one of the options listed in the original dropdown list (as if it was a regular charfield) For now, If I'm saving the django form with a value not in the list, the form doesn't save and return error. Is there a way to force the saving of the form with the value entered in the widget field ? form.py class forms_bdc(forms.ModelForm): [...] bdc_description_1 = forms.ChoiceField(required=False,choices=list(models_products.objects.values_list( 'product_denomination','product_denomination')),widget=forms.Select(attrs={'id': 'bdc_editable_select_description_1','style': 'width:200px','onchange': 'populate_selected_product(this.id,this.value)'})) template.html <div style="width: 200px;">{{ form5.bdc_description_1 }}</div> #script that convert regular dropdown to editable-dropdown and trigg a function called 'populate_selected_product' <script> var selectedIDs = ['bdc_editable_select_description_1','bdc_editable_select_description_2','bdc_editable_select_description_3','bdc_editable_select_description_4','bdc_editable_select_description_5']; for (let i = 0; i < selectedIDs.length; i++) { $('#'+selectedIDs[i]).editableSelect({ effects: 'fade' }).on('select.editable-select', function (e, li) { populate_selected_product($('#'+selectedIDs[i]).attr('id'),li.text()) }); } </script> -
Django MQTT Subscriber save to database and update view
I am creating a live dashboard for race data where timings and other information will be published by multiple clients on a per lap basis. I am using Mosquitto as my broker. Guided by this solution I am able to subscribe to the different topics amd see the published results. on_message received from lap_data QOS:0 retain:False - `{"LapCompleted": 32 ... }` on_message received from weather_data QOS:0 retain:False - `{ "RelativeHumidity":0.449} I have completed the channels chat tutorial and have Redis running on WSL. Now, I would like to: add the received messages to the database update the view when a message is recieved. I hoped to me able to add records via the on_message_callback but when I try to import the models into my MQTTClient.py file I get the following error: raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. If anyone was able to point me in the right directions for 1 & 2 I would be grateful. Thank you. MQTT is started via the app ready function def ready(self): if os.environ.get('RUN_MAIN'): mqtt_client = MqttRemote() mqtt_client.start()