Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django chat-fetch optimization
everyone, I am currently building a chat app using Django. In order to keep the app real time, I am making an API fetch from the Database every second using JSON and refreshing some parts (that contain the messages) of the page. As a result, a lot of queries are being sent to the database every second per user. Is there a better way to load these messages in real time? Please help. Thank you. PS: I wish to write custom code for the app and thus am not using any modules like django-channels. If you could suggest something NOT using this, I would be greatfull. -
Gunicorn Container: No module named 'app.wsgi.application'; 'app.wsgi' is not a package
I've created a python container to statically compile a simple django application, for use with WSGI, aptly named app hereafter. Dockerfile ## Stage 1: Install Python requirements into wheels path FROM python:3.9 as builder # Dont write .pyc to image or we cant build cryptography ENV PYTHONDONTWRITEBYTECODE 0 # Ensure all output is flushed to stdout ENV PYTHONUNBUFFERED 1 # Dont build crypto with rust ENV CRYPTOGRAPHY_DONT_BUILD_RUST 1 RUN apt-get update \ && apt-get install -y \ ca-certificates \ gettext \ libjpeg-dev \ libpq-dev \ libffi-dev \ postgresql-client \ zlib1g-dev WORKDIR /wheels COPY ./${REQUIREMENTS:-requirements/development.txt} /wheels/requirements.txt RUN pip install -U setuptools pip \ && pip wheel -r ./requirements.txt ## Stage 2: Build the Python wheels statically FROM python:3.9 as base ENV PYTHONUNBUFFERED 1 ENV DJANGO_SETTINGS_MODULE="app.settings" COPY --from=builder /wheels /wheels RUN pip install -U pip \ && pip install --no-cache-dir --no-index \ -r /wheels/requirements.txt \ -f /wheels \ && rm -rf /wheels \ && adduser --system --home /var/task --shell /sbin/nologin --no-create-home --disabled-password --disabled-login service \ && ln -s /dev/stdout /var/log/gunicorn-error.log \ && ln -s /dev/stdout /var/log/gunicorn-access.log \ && chmod o+w /dev/stdout COPY . /var/task/ WORKDIR /var/task # Precompile the application RUN python3 scripts/compile.py /var/task # Stage 3: Build a contianer FROM base … -
Pulling data from a PostgreSQL table and rendering to a web page using Django
I am unable to pull data from a newly populated PostgreSQL table and render it on a web page in my Django application. I have a small application where a user uploads a .json file. The app performs some operations on the json, resulting in a Pandas dataframe. This dataframe then populates a PostgreSQL data table, resulting in one column of data whose length corresponds to the initial data operations. So far, this works correctly. I have checked the postgres database to verify that the table has been populated, and it has. However, I'm having trouble pulling that column of data from the database and displaying it on the same page that the user uploaded the data from. I'm unsure why I can't easily retrieve the data from the database, loop over it, and render it to the page. The error message tells me that my app "id" does not exist, despite including an "id" primary key in my models.py. As you can see, in my views.py file, I have a ProcessedDataListView class that is intended to create the context and send data to my data_display.html file. Here is my error message: In template /home/linux/django_app/eef/myapp/templates/upload_json.html, error at line 12 column … -
Plotly to_html makes webpages very slow to load
I am using Django to create my first website. I have some plots made with Plotly which get passed to the render function as html. My plots are saved using to_html: return fig.to_html(config={'displayModeBar': False}) I found this is a total killer of webpage performance. It takes ages to load and it is very heavy. Is this expected? Is there a better approach than using to_html or Plotly is a non starter for webpage plots? -
django not redirecting to next page login required
I have multiple view function that has the @login_required decorator in my view.py. When i signout and try to access one of the page whose view function has the @login_required decorator, i get redirected to a page with this kind of url. http://localhost:8002/signin/?next=/pending/. However when i signin, i get redirected to index page instead of pending page and i already tried to solve my problem using solution from this question and this question but it doesn't work. Here is my view function for login def signin(request): if request.user.is_authenticated: return redirect(index) if request.method == "POST": form = Signin(request.POST) if form.is_valid(): username = request.POST.get("username") password = request.POST.get("password") user = User.objects.filter(username=username.lower()).exists() if user: get_user = User.objects.filter(username=username.lower()) check_pass = check_password(password, get_user[0].password) if not check_pass: messages.error(request, "Invalid Credentials") return redirect(signin) else: login(request, get_user[0]) return redirect(index) else: messages.error(request, "Invalid Credentials") return redirect(signin) else: form = Signin() return render(request, "accounts/login.html", {"form": form}) Here is my urls.py from django.urls import path from accounts import views urlpatterns = [ path("signup/", views.signup, name="signup"), path("signin/", views.signin, name="signin"), path("signout/", views.signout, name="signout"), And here is my login template <!DOCTYPE html> <html lang="en" class="supernova login-page"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>SignIn</title> <link rel="stylesheet" href="/static/signup/css/1.css"> <link rel="stylesheet" href="/static/signup/css/2.css"> <link rel="stylesheet" href="/static/signup/css/3.css"> <link rel="stylesheet" … -
model form set throws an error: ModelFormOptions' object has no attribute 'private_fields'
I'm trying to create 30 fields in one model that has only 2 fields, I know it can be done using formset but that one doesn't support save() method when submitted the form, so I changed it to: modelformset that supported save() method, but using modelformset throws me an error in the design.html saying: ModelFormOptions' object has no attribute 'private_fields' how can I solve this problem? From .forms import ColumnForm From django.forms import modelformset_factory def design(request): ColumnFormSet = modelformset_factory(ColumnForm, fields = ('name', 'selec_type'), extra=30) formset = ColumnFormSet if request.method == 'POST': formset = ColumnFormSet(request.POST) if formset.is_valid(): formset.save() return redirect('Home') else: formset = ColumnFormSet() return render (request, 'design.html', {'formset':formset}) forms.py: from django import forms from .models import Column class ColumnForm(forms.ModelForm): class Meta: model = Column fields = ['name', 'selec_type'] template: <form method='post'> {% csrf_token %} {{ formset.management_form}} {% for form in formset %} {{form.as_p}} {% endfor %} <button type='submit'>Save<button/> <form/> Models.py: class Type(models.Model): TYPE_OF_DATA = ( ('Number', 'Number'), ('character', 'character'), ('check_box', 'check_box'), ('date', 'date'), ('image', 'image'), ) data_type = models.CharField(max_length=1000, choices= TYPE_OF_DATA) class Column(models.Model): name = models.CharField(max_length=100) selec_type = models.ForeignKey(Type, on_delete=CASCADE) -
How to run recommit-hooks depend on application
I have several apps in project project: app1 app2 app3 And want to use pre-commit hooks, that will run tests for specific app example of my .pre-commit-config.yaml repos: - repo: local hooks: - id: test name: test # here I want to run test_app1 or test_app2 depending on # changes in directories(or maybe pre-commit configs) entry: make test language: system types: [python] -
How to suppress the `RemovedInDjango40Warning` warnings in a unit test?
We are working on a unit test in PyCharm and the test itself is passing now. However, the terminal output contains warning messages in the RemovedInDjango40Warning category. As we do not plan to upgrade to Django 4.0 for now, these warnings are verbose and distracting. We tried including the statement warnings.simplefilter("ignore", category=RemovedInDjango40Warning) but it did not suppress the warnings. So, we wonder how to suppress the RemovedInDjango40Warning warnings. Technical Details: Partial source code of the unit test: from unittest import TestCase import Django class TestPocFunctional(TestCase): @classmethod def setUpClass(cls): django.setup() return def test_all(self): from application.poc import PocFunctional import warnings from django.utils.deprecation import RemovedInDjango40Warning warnings.simplefilter("ignore", category=RemovedInDjango40Warning) # ... testing steps return The terminal output of warnings: /data/app-py3/venv3.7/bin/python /var/lib/snapd/snap/pycharm-professional/316/plugins/python/helpers/pycharm/_jb_unittest_runner.py --target test_poc.TestPocFunctional Testing started at 1:54 PM ... Launching unittests with arguments python -m unittest test_poc.TestPocFunctional in /data/app-py3/APPLICATION/tests /data/app-py3/APPLICATION/eav/models.py:84: RemovedInDjango40Warning: django.utils.translation.ugettext_lazy() is deprecated in favor of django.utils.translation.gettext_lazy(). value = models.CharField(_(u"value"), db_index=True, /data/app-py3/APPLICATION/eav/models.py:100: RemovedInDjango40Warning: django.utils.translation.ugettext_lazy() is deprecated in favor of django.utils.translation.gettext_lazy(). name = models.CharField(_(u"name"), unique=True, max_length=100) /data/app-py3/APPLICATION/eav/models.py:102: RemovedInDjango40Warning: django.utils.translation.ugettext_lazy() is deprecated in favor of django.utils.translation.gettext_lazy(). enums = models.ManyToManyField(EnumValue, verbose_name=_(u"enum group")) /data/app-py3/APPLICATION/eav/models.py:173: RemovedInDjango40Warning: django.utils.translation.ugettext_lazy() is deprecated in favor of django.utils.translation.gettext_lazy(). (TYPE_TEXT, _(u"Text")), /data/app-py3/APPLICATION/eav/models.py:174: RemovedInDjango40Warning: django.utils.translation.ugettext_lazy() is deprecated in favor of django.utils.translation.gettext_lazy(). (TYPE_FLOAT, _(u"Float")), /data/app-py3/APPLICATION/eav/models.py:175: RemovedInDjango40Warning: django.utils.translation.ugettext_lazy() … -
How can I translate this SQL query to Django ORM
I have the following sql query: SELECT messages1.id, messages1.channel FROM (SELECT * FROM messages WHERE timestamp >= datetime.now() AND channel IN ('ALL', 'UC')) messages1 LEFT JOIN read_messages ON messages1.id = read_messages.message_id WHERE read_messages.id IS NULL; and these are my models: from django.db import models class Messages(models.Model): channel = models.TextField(blank=True, null=True) message = models.TextField(blank=True, null=True) timestamp = models.TextField(blank=True, null=True) publisher = models.IntegerField(blank=True, null=True) type = models.CharField(max_length=5) class Meta: managed = False db_table = 'messages' class NotifiedMessages(models.Model): id = models.IntegerField(primary_key=True) user_id = models.IntegerField() message_id = models.IntegerField() class Meta: managed = False db_table = 'notified_messages' class ReadMessages(models.Model): user_id = models.IntegerField(blank=True, null=True) message_id = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'read_messages' i've tried to use subqueries and other things, but the main problem now is that subquery return an error: django.db.utils.ProgrammingError: subquery must return only one column because I was trying to do something like it: ts = Messages.objects.filter(timestamp__gte=datetime.today(), channel__in=['ALL', 'UC']) Messages.objects.annotate(messages1=Subquery(ts, output_field=models.CharField())) what is wrong with the code above and what can I do to translate the query correctly? -
Test database is flushed despite `--reuse-db` being specified
As per the docs: Using --reuse-db will create the test database in the same way as manage.py test usually does. However, after the test run, the test database will not be removed. The next time a test run is started with --reuse-db, the database will instantly be re used. This will allow much faster startup time for tests. This actually doesn't work and is not true: Here's pytest.ini [pytest] DJANGO_SETTINGS_MODULE = myproject.settings addopts = --reuse-db and here's django_db_setup import sqlite3 import uuid import pytest from django.conf import settings from django.contrib.auth.models import User from django.core.management import call_command @pytest.fixture(scope='session') def test_user(): return { 'username': uuid.uuid4().hex[:10], 'password': uuid.uuid4().hex, } @pytest.fixture(scope='session') def django_db_setup(django_db_blocker, test_user, django_db_keepdb): db_path = settings.BASE_DIR / 'test-db.sqlite3' sqlite3.connect(db_path.as_posix()) settings.DATABASES['default']['NAME'] = db_path with django_db_blocker.unblock(): call_command('migrate', '--noinput') User.objects.create_user( username=test_user['username'], password=test_user['password'], email=f'{test_user["username"]}@test', is_active=True, ) and django_db_keepdb evaluates to True. Here's the tests: def test1(django_user_model, django_db_keepdb): print(django_db_keepdb, django_user_model.objects.all()) def test2(django_user_model, django_db_keepdb): print(django_db_keepdb, django_user_model.objects.all()) which results in: True <QuerySet [<User: b18cd8369b>]> True <QuerySet []> and the expected results are True <QuerySet [<User: b18cd8369b>]> True <QuerySet [<User: b18cd8369b>]> So, how to actually obtain this outcome? -
Where is the code that creates a unit test database in Django?
For unit testing, Django creates a test database, runs unit tests, then destroys that database. Where is the code that does that? I looked in github, and couldn't find anything. For example, at the beginning of unit testing, I see this message: Creating test database for alias 'default'... but when I look in github for "Creating test database for alias", I find nothing. Related: how does the testing code connect to that database, given that it's not specified in the DATABASES settings? (That is, "default" is in settings, but the test database "test_default" is not.) Or, where is the code that connects to the test database? -
Django module not found
I have installed django, just like any other normal module, yet it says module not found. I can see the module package in the normal directory that it is on (python 3.11). I opened up vscode and it locates the module just fine. But i can't run it despite all of that. I have used python for a year or two and it has never done something like this, any solutions? -
Intermittent Large 'Initial Connection' times with Django Application + Fetch api
I have a Django view that takes about 30 seconds or so run, which is triggered by a POST requests from vanilla JS. It currently works about half the time - with either a 200 OK or an net::ERR_EMPTY_RESPONSE. When it errors out - I notice that the 'initial connection' time is very high in Chrome And when it works - I see nothing of the sort: The fact that is does work sometimes seems to suggest that it isn't my JS code or my Django code (per se). Does this suggest perhaps I should look into queues or something? I am trying to dynamically create some images with an AI tool and return them to the user. These APIs can take some time to run. I feel like there is something happening at the network/framework level that I can't get a good handle on. Sometimes the request on the server is showing as succesfull but returns this error to the client. -
ColumnFormFormSet objects has no attribute ‘save’
I want to create 30 fields in the design.html, after I successfully added that using django formset When I try to submit the form instead of saving the field to the database, it throws me an error saying 'ColumnFormFormSet' object has no attribute 'save' how can I solve this problem? models.py: class Type(models.Model): TYPE_OF_DATA = ( ('Number', 'Number'), ('character', 'character'), ('check_box', 'check_box'), ('date', 'date'), ('image', 'image'), ) data_type = models.CharField(max_length=1000, choices= TYPE_OF_DATA) class Column(models.Model): name = models.CharField(max_length=100) selec_type = models.ForeignKey(Type, on_delete=CASCADE) Forms.py: from django import forms from .models import Column class ColumnForm(forms.ModelForm): class Meta: model = Column fields = ['name', 'selec_type'] views.py: From .forms import ColumnForm From django.forms import formset_factory def design(request): ColumnFormSet = formset_factory(ColumnForm, extra=30) formset = ColumnFormSet if request.method == 'POST': formset = ColumnFormSet(request.POST) if formset.is_valid(): formset.save() return redirect('Home') else: formset = ColumnFormSet() return render (request, 'design.html', {'formset':formset}) template.design.html: <form method='post'> {% csrf_token %} {{ formset.management_form}} {% for form in formset %} {{form.as_p}} {% endfor %} <button type='submit'>Save<button/> <form/> -
Issue while trying to run data script in django
I have already checked this post but of no use for me. 'module' object is not callable Django from auth_app.models import UserModel from django.contrib.auth.hashers import make_password def UserData(apps, schema): UserModel( username="gargonlinejobs", email_address="gargonlinejobs@gmail.com", is_active=1, password=make_password("12345aA!") ).save(); Error Message: TypeError: 'module' object is not callable -
TemplateSyntaxError when accessing default django-allauth login and registration pages
I've just installed django-allauth with pip in my django course project. I am getting an error in browser when I try to access either "http://127.0.0.1:8000/account/login/" or "http://127.0.0.1:8000/account/signup/" : TemplateSyntaxError at /account/login/ Invalid block tag on line 17: 'trans', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/account/login/ Django Version: 4.1.7 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 17: 'trans', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? Exception Location: C:\FSSD Projects\Play2LearnFinal\Play2LearnFinal\.venv\Lib\site-packages\django\template\base.py, line 558, in invalid_block_tag Raised during: allauth.account.views.LoginView Python Executable: C:\FSSD Projects\Play2LearnFinal\Play2LearnFinal\.venv\Scripts\python.exe Python Version: 3.11.0 Python Path: ['C:\\FSSD Projects\\Play2LearnFinal\\Play2LearnFinal', 'C:\\Python311\\python311.zip', 'C:\\Python311\\DLLs', 'C:\\Python311\\Lib', 'C:\\Python311', 'C:\\FSSD Projects\\Play2LearnFinal\\Play2LearnFinal\\.venv', 'C:\\FSSD ' 'Projects\\Play2LearnFinal\\Play2LearnFinal\\.venv\\Lib\\site-packages'] Server time: Fri, 17 Mar 2023 13:38:15 -0500 Relevant versions I'm running: Python 3.11.0 Django==4.1.7 django-allauth==0.53.0 I have not modified any of the auth files; only the base settings.py with standard configuration that worked in previous course projects. Deleting the line did not work. I tried adding 'django.template.context_processors.i18n' to settings.py TEMPLATES, I also tried adding 'django.middleware.locale.LocaleMiddleware' to MIDDLEWARE. No luck. -
Docker. Django. Saving a file in a docker container after completing a celery task
I have deployed a django project in docker. The project works without errors. The paths to staticfiles and mediafiles are specified, and they work correct. The project uses celery, which creates several tasks, as a result of which files are generated and written to a directory. There are no errors when performing tasks, but files are not written to the necessary directories. What could this be related to? An example of my code with the result of the task and the problem is given below. My Dockerfile.prod \########### # BUILDER \########### FROM python:3.10 as builder WORKDIR /ea_v2 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update &&\ apt-get install netcat -y &&\ apt-get install -y binutils libproj-dev gdal-bin &&\ apt-get install -y --no-install-recommends gcc RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /ea_v2/wheels -r requirements.txt \######### # FINAL \######### FROM python:3.10 RUN mkdir -p /home/ea_v2 RUN groupadd ea_group RUN useradd -m -g ea_group ea -p Password RUN usermod -aG ea_group ea ENV HOME=/home/ea_v2 ENV APP_HOME=/home/ea_v2/ea_v2 RUN mkdir $APP_HOME RUN mkdir $APP_HOME/staticfiles RUN mkdir $APP_HOME/media RUN mkdir $APP_HOME/media/urban WORKDIR $APP_HOME RUN apt-get update &&\ apt-get install netcat -y &&\ apt-get install -qq -y libpq-dev &&\ … -
Elegant way to send m2m_changed signal
I have RelatedModel which has a OneToOne Field to the MainModel. It also has some normal Fields and a ManyToMany Field and. When I change the RelatedModel it updates the MainModel. It updates some ManyToMany Fields and some normal fields. When RelatedModel and the MainModel are linked with the OneToOne Field everything works fine: It updates normal fields and m2m fields easy with the post_save and m2m_changed signals. Where I struggle: First I create a RelatedModel and the MainModel. Later I add a link between the models and the RelatedModel should update the MainModel. The moment they are linked together the post_save signal is triggered to update all the normal fields. But the m2m_changed signal is not triggered. So the m2m field on the MainModel is never updated. I tried hacking this by manually changing the m2m to [] and setting it back. But it makes extra db_calls and it doesn't even work when the m2m field is [] to start with. I am looking for an elegant way to send an m2m_changed signal? Or call the function that is decorated with m2m? I would love to see both even if it is for educational purposes. Or maybe a 3rd … -
Django react app for receiving contact emails not working with front to backend communication
I have the django backend sending out emails to my email when I interactively try it from the django shell, but then when I try it from my front end, it doesn't work (yet gives a 200 response back). Here is where I interactively try it on the shell and I actually receive the email: % python manage.py shell >>> from django.core.mail import send_mail >>> send_mail('subject message here', "body content msg here", "<sender>@gmail.com", ["<recipient>@gmail.com"]) 1 I then receive the email within seconds of running this command. So I then go over to my front end, and send the request from there to the backend. I have connected the front and backend through CORS, and the rest authentication, and I even see the data outputted in the django debug toolbar when sending my request from the front end to the back end. Here is that data Here is the django view with exclusions for simplification: om django.shortcuts import render from rest_framework import viewsets from .serializers import TodoSerializer from django.http import HttpResponse, HttpResponseRedirect from .models import Todo from django.conf import settings # views.py from django.core.mail import send_mail from django.http import JsonResponse def send_email(request): if request.method == 'POST': # Get email data from … -
Returning queryset that uses a foreign key of a foreign key relationship
It sounds simple enough: get all the Users for a specific Company. But it is complicated by a few things: The User model is extended The model that extends it contains a UUID that uniquely identifies the user throughout various system integrations This UUID is what is used in the company relationship. So the relationship is user_to_company__user_uuid -> user_extended__user_id -> auth_user. That's what I'd like to return is the User model. What I have: # url /api/user_to_company/?company_uuid=0450469d-cbb1-4374-a16f-dd72ce15cf67 # views.py class UserToCompanyViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): filter_backends = [StrictDjangoFilterBackend] filterset_fields = [ 'id', 'user_uuid', 'company_uuid' ] permission_classes = [CompanyPermissions] def get_queryset(self): if self.request.GET['company_uuid']: queryset = User.objects.filter( user_to_company__company_uuid=self.request.GET['company_uuid']) return queryset def get_serializer_class(self): if self.request.GET['company_uuid']: serializer_class = UserSerializer return serializer_class # serializers.py class UserToCompanySerializer(serializers.ModelSerializer): class Meta: model = UserToCompany fields = '__all__' class UserExtendedSerializer(serializers.ModelSerializer): class Meta: model = UserExtended fields = '__all__' # models.py class UserExtended(models.Model): user_id = models.OneToOneField( User, on_delete=models.CASCADE, db_column='user_id') uuid = models.UUIDField(primary_key=True, null=False) class Meta: db_table = 'user_extended' class UserToCompany(models.Model): user_uuid = models.ForeignKey( UserExtended, on_delete=models.CASCADE, db_column='user_uuid', related_name='user_to_company') company_uuid = models.ForeignKey( Companies, on_delete=models.CASCADE, db_column='company_uuid', related_name='user_to_company') class Meta: db_table = 'user_to_company' unique_together = [['user_uuid', 'company_uuid']] Understandably, in this setup User.object.filter(user_to_company__company_uuid=self.reqest.GET['company_uuid'] doesn't make sense and it returns django.core.exceptions.FieldError: Cannot resolve keyword 'user_to_company' into field--There isn't … -
Is there a way to add a dot to a curve using recharts for React?
I'm trying to create a bell curve using Django and React with TypeScript and the ReCharts library. So far I have this code for the chart on my frontend: import { AreaChart, Area, XAxis, CartesianGrid, Dot, ResponsiveContainer, Label } from 'recharts'; import { generateMetricSelectorButton } from '../../utilities/generateMetricSelectorButton'; import { useEffect, useState } from "react"; import AllValuesDefined from '../../utilities/AllValuesDefined'; import GetRatingChartData from '../../utilities/requests/GetRatingChartData'; interface DataPoint { time: number; zScore: number; percentile: number; } interface Coordinates { x: number; y: number; } const RatingAnalysis = () => { const [distanceSelected, setDistanceSelected] = useState<string>('100m'); const [myDataPoint, setMyDataPoints] = useState<DataPoint>({time: 0, zScore: 0, percentile: 0}); const [coordinates, setCoordinates] = useState<Coordinates[]>([]); const getData = async () => { const response = await GetRatingChartData(distanceSelected); if(!AllValuesDefined(response?.data)) { console.error('Error: response from function AddCoreDetails has undefined value'); } else { const data = response?.data; setMyDataPoints(data.myDataPoint); setCoordinates(data.coordinates); } } useEffect(() => { getData(); console.log(myDataPoint) }, [distanceSelected]); return ( <div className="border-white border-2 rounded-lg row-span-5 w-full grid grid-cols-12 grid-rows-6"> <div className="border-white border-r-2 col-span-2 row-span-6 grid grid-rows-6"> {generateMetricSelectorButton('100m', setDistanceSelected)} {generateMetricSelectorButton('500m', setDistanceSelected)} {generateMetricSelectorButton('1000m', setDistanceSelected)} {generateMetricSelectorButton('2000m', setDistanceSelected)} {generateMetricSelectorButton('6000m', setDistanceSelected)} {generateMetricSelectorButton('10000m', setDistanceSelected)} </div> <div className=" col-span-10 row-span-6"> <ResponsiveContainer width="100%" height="95%"> <AreaChart data={coordinates} margin={{top: 20, right: 40, left: 40, bottom: 25}}> <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="x"> … -
Bokeh server django [closed]
I am looking for a recipe for how to implement a bokeh server application in a django application. Does anyone have an example for this? I've looked all over the internet, but haven't found any examples of this. I have also tried looking through bokeh's documentation, but have not found anything that can help me with this. -
How to create a Custom Field that sets the value of another Field in a Django model?
I'm trying to create a custom field for a model representing firewall service objects, such as 80/tcp = HTTP for example. I want to seperate the protocol from the port number to store the port as an integer and the protocol as a FK to an accepted protocol. Here are the models I've created for this : class ServiceObject(models.Model): name = models.CharField(max_length=100, unique=True, help_text='Name of the Service Object') description = models.CharField(max_length=200, null=True, blank=True) protocol = models.ForeignKey(to=Protocol, on_delete=models.PROTECT, related_name="service_objects", null=True, blank=True) source_port = PortField(null=True, blank=True) destination_port = PortField(null=True, blank=True) type = models.CharField(max_length=10, choices=SERVICE_CHOICES, null=True, blank=True) status = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Protocol(models.Model): name = models.CharField(max_length=10, unique=True, help_text='Name of the Protocol') description = models.CharField(max_length=200, null=True, blank=True) protocol_number = models.IntegerField(unique=True, help_text='Protocol Number') created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) The issue resides in the PortField logic, I've created a Custom Validator so that I can accept single ports and port ranges, and the validator will set the model_instance.type based on the validator, this works fine. class PortField(models.CharField): def validate(self, value, model_instance): # super().validate(value, model_instance) if value is None: return value try: self.type = self.validate_port(value) except ValueError: try: if '-' in value: self.type = self.validate_port_range(value) else: raise … -
Forms not submitting
Here FullMaid form and Cleaner form could not be submitted...It is not even entering into the request.POST .Other forms are working and it gets submitted. Only these two forms are not working. This is the views.py code def staffApply2(request, domestic_works, uid): user = User.objects.get(id=uid) staff = StaffApplicantTable.objects.get(user=user) formsets = [] if 'cook' in domestic_works: formsets.append(CookingForm(request.POST, prefix='cook')) if 'driver' in domestic_works: formsets.append(DriverForm(request.POST, request.FILES, prefix='driver')) if 'nanny' in domestic_works: formsets.append(NannyForm(request.POST, request.FILES, prefix='nanny')) if 'gardener' in domestic_works: formsets.append(GardenerForm(request.POST, request.FILES, prefix='gardener')) if 'elder-care-taker' in domestic_works: formsets.append(ElderCareTakerForm(request.POST, request.FILES, prefix='elder-care-taker')) if 'full-maid' in domestic_works: formsets.append(FullMaidForm(request.POST, request.FILES, prefix='full-maid')) if 'cleaner' in domestic_works: formsets.append(CleanerForm(request.POST, request.FILES, prefix='cleaner')) if request.POST and request.FILES: print("it came") forms_valid = True print("ygytgf",forms_valid) for form in formsets: if f'{form.prefix}-submit' not in request.POST: continue if not form.is_valid(): forms_valid = False print(f"Form {form.prefix} is not valid:") for field, errors in form.errors.items(): for error in errors: print(f"Error in field {field}: {error}") if forms_valid: for form in formsets: if isinstance(form, CookingForm): register_cook = form.save(commit=False) register_cook.cook = staff register_cook.save() elif isinstance(form, DriverForm): register_driver = form.save(commit=False) register_driver.driver = staff register_driver.save() elif isinstance(form, GardenerForm): register_gardener = form.save(commit=False) register_gardener.gardener = staff register_gardener.save() elif isinstance(form, ElderCareTakerForm): register_elder_care_taker = form.save(commit=False) register_elder_care_taker.elder_care_taker = staff register_elder_care_taker.save() elif isinstance(form, NannyForm): register_nanny = form.save(commit=False) register_nanny.nanny = staff register_nanny.save() elif … -
Why gunicorn is not able to import settings from my `prod.py` Django settings file?
I'm deploying Django app to production on nginx/gunicorn server, Azure VM. Instead of settings.py I'm using settings\base.py + prod.py \ dev.py structure. My folder structure is as follows: \home\username\git-level-project-name\django-manage.py-file-level\settings\ - at this level, both my base.py and prod.py reside. In the same folder I also have __init__.py file which is responsible to pick either base.py or prod.py based on the environment variable USER_DJANGO_ENV. import os from .base import * if os.environ['USER_DJANGO_ENV'] == 'prod': from .prod import * else: from .dev import * This works as expected on my local machine with internal Django dev server, but it doesn't work in production with gunicorn. Gunicorn is able to localize base.py and read settings from it, but base.py is not updated with prod.py. Any ideas how to configure gunicorn to read settings from prod.py? [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=user Group=www-data WorkingDirectory=/home/user/user/user_django EnvironmentFile=/home/user/user/user_django/user_django/.env ExecStart=/home/user/anaconda3/envs/user/bin/gunicorn \ --access-logfile '-' \ --access-logfile /home/user/user/logs/gunicorn-access.log \ --log-file /home/user/user/logs/gunicorn.log \ --workers 3 \ --chdir /home/user/user/user_django/user_django/settings \ --bind unix:/run/gunicorn.sock \ user_django.wsgi:application [Install] WantedBy=multi-user.target