Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
bootstrap 5 tabs not working in Django template on click no action
my base.html contains on head: <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>{% block title %}Orphea{% endblock title %}</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Professional T"> <meta name="author" content="philippe Haumesser"> <link rel="icon" href="{% static 'images/favicons/favicon.ico' %}"> {% block css %} <!-- Bootstrap CSS --> <!-- Latest compiled and minified Bootstrap CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" integrity="sha512-GQGU0fMMi238uA+a/bdWJfpUGKUkBdgfFdgBm72SUQ6BeyWjoY/ton0tEjH+OSH9iP4Dfh+7HM0I9f5eR0L/4w==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <!-- Your stuff: Third-party CSS libraries go here --> <!-- This file stores project-specific CSS --> <link href="{% static 'css/project.css' %}" rel="stylesheet"> {% endblock %} <!-- Le javascript ================================================== --> {# Placed at the top of the document so pages load faster with defer #} {% block javascript %} <!-- Bootstrap JS --> <script defer src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.min.js" integrity="sha512-OvBgP9A2JBgiRad/mM36mkzXSXaJE9BEIENnVEmeZdITvwT09xnxLtT4twkCa8m/loMbPHsvPl0T8lRGVBwjlQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <!-- Your stuff: Third-party javascript libraries go here --> <!-- Popper.js for Bootstrap --> <script src="https://unpkg.com/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz4fnFO9gybBud7M4aw3bN3q5jUQ1g8B5lDfzj5p13bVEE2W5h5+gaawxI" crossorigin="anonymous"></script> <!-- place project specific Javascript in this file --> <script defer src="{% static 'js/project.js' %}"></script> {% endblock javascript %} </head> It is Cookiecutter base except one modification for popper.js My template is : {% extends 'base.html' %} {% load crispy_forms_tags %} {% block javascript %} <script type="text/javascript"> const commandeFormset = document.querySelector('#commande-formset'); const addCommandeFormButton = document.querySelector('#add-commande-form'); const emptyCommandeForm = ` {% with form=formset.empty_form %} <tr … -
enabling submit button based on input
There is a form having a textarea and a submit button I want the submit to be enabled and disabled based on 'if there is any input in the textarea' both the submit and content is being selected correctly (ill send a screenshot of it) JS file: document.addEventListener('DOMContentLoaded',() => { document.querySelector('#all-posts').addEventListener('click', () => loadAllPosts()) if (document.querySelector('#following') != null){ document.querySelector('#following').addEventListener('click', () => loadFollowing()) } loadAllPosts(); }); function loadAllPosts(){ document.querySelector('#allPosts-view').style.display = 'block'; document.querySelector('#following-view').style.display = 'none'; fetch('/api/post') .then(response => response.json()) .then(data => { const posts = data.data.posts; const postCards = posts.map(post => { let likeBtnClass = 'fa fa-heart-o'; if (post.liked_by_user) { likeBtnClass = 'fa fa-heart'; } const on = new Date(post.posted_on).toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', month: 'long', day: 'numeric', year: 'numeric', timeZone: 'UTC' }); return ` <div class="card text-white bg-dark mb-3" style="margin-bottom: 5px;"> <div class="card-body"> <h5 class="card-title">${post.posted_by.username}</h5> <p class="card-subtitle mb-2 text-muted" style="font-size: 12px;">${on}</p> <hr style="border: none; height: 1px; background-color: #FFFFF0; margin: 0px;"> <p class="card-text" style="margin-top: 5px; font-size: 25px;">${post.content}</p> <div class="like-container"> <i id="like-btn" class="${likeBtnClass}" style="font-size:24px; cursor:pointer; margin-right: 10px;"></i> <p class="card-subtitle mb-2 text-muted" style="margin-top: 0.5rem; padding: 0px; font-size: 12px;">${post.likes}</p> </div> </div> </div> `; }); document.querySelector('#allPosts-view').innerHTML += postCards.join(''); }) .catch(err => console.error(err)); const likeBtnsContainer = document.querySelector('#allPosts-view'); likeBtnsContainer.addEventListener('click', (event) => { if (event.target.matches('#like-btn')) { event.target.classList.toggle('fa-heart'); event.target.classList.toggle('fa-heart-o'); … -
How can I create relationship in 3 django models
Is it possible to create Microsoft Access Design View in django, I want to create something similar to Microsoft Access Design View in django model using these model: class Type(models.Model): TYPE_OF_DATA = ( ('Number', 'Number'), ('character', 'character'), ('boolean', 'boolean'), ('date', 'date'), ('image', 'image'), ) data_type = models.CharField(max_length=1000, choices= TYPE_OF_DATA) def __str__(self): return self.data_type class Column(models.Model): name = models.CharField(max_length=100) selec_type = models.ForeignKey(Type, on_delete= models.CASCADE) class Table(models.Model): number = models.IntegerField() character = models.CharField(max_length=30) check_box = models.BooleanField() date = models.DateField() image = models.ImageField(upload_to='image-table') I successfully created 30 Column in the form: From .forms import ColumnForm From django.forms import modelformset_factory def design(request): ColumnFormSet = modelformset_factory(Column, 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}) Using this view, a user can create a name of a field and assign it to the data type that a user want the field to be stored. My problem here is the Table model, where user can store all the information based on the Column table he created or design. How can I archive that using django, which method should I use to make that happen? -
I can not start the server in any way due to problems with installing libraries and starting wheels
I need to run this server on Django and React, I cloned it to myself, went to the "ozone-framework-python-server" folder, created a virtual environment and tried to install the libraries "pip install -r requirements.txt", but I got such errors I work for Windows Building wheels for collected packages: lxml, psycopg2-binary Building wheel for lxml (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [97 lines of output] - - - error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.35.32215\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2 ********************************************************************************* Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? ********************************************************************************* [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for lxml Running setup.py clean for lxml Building wheel for psycopg2-binary (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 - - - It appears you are missing some prerequisite to build the package from source. You may install a binary package by installing 'psycopg2-binary' from PyPI. If you want to install psycopg2 from source, please install the packages required for the build and try again. … -
Django: Group by and return multiple fields
In Django, Consider the following model class, class Report(models.Model): owner = models.ForeignKey( to=Owner, on_delete=models.CASCADE, related_name='data', ) balance = models.PositiveIntegerField() report_date = models.DateField() Assume this table has only the following four items, <QuerySet [{'owner': 1, 'balance': 100, 'report_date': datetime.date(2023, 3, 4)}, {'owner': 1, 'balance': 50, 'report_date': datetime.date(2023, 3, 9)}, {'owner': 2, 'balance': 1000, 'report_date': datetime.date(2023, 2, 2)}, {'owner': 2, 'balance': 2000, 'report_date': datetime.date(2023, 2, 22)}]> a simple group by owner and aggregating the minimum of report_date will be as follows, Report.objects.values('owner').annotate(min_report_date=Min('report_date')).values('owner', 'min_report_date') and the result will be as follows, <QuerySet [{'owner': 1, 'min_report_date': datetime.date(2023, 3, 4)}, {'owner': 2, 'min_report_date': datetime.date(2023, 2, 2)}]> Now I want to return the balance corresponding to the minimum of report_date field in addition to the owner and min_report_date fields like bellow, <QuerySet [{'owner': 1, 'min_report_date': datetime.date(2023, 3, 4), 'balance': 100}, {'owner': 2, 'min_report_date': datetime.date(2023, 2, 2), 'balance': 1000}]> My attempt was the bellow Django query, Report.objects.values('owner').annotate(min_report_date=Min('report_date')).values('owner', 'min_report_date', 'balance') but the result lost the effect of aggregation (i.e., all rows were returned) and was like bellow, <QuerySet [{'owner': 1, 'balance': 50, 'min_report_date': datetime.date(2023, 3, 9)}, {'owner': 1, 'balance': 100, 'min_report_date': datetime.date(2023, 3, 4)}, {'owner': 2, 'balance': 2000, 'min_report_date': datetime.date(2023, 2, 22)}, {'owner': 2, 'balance': 1000, 'min_report_date': datetime.date(2023, … -
Getting error during Django-MongoDB model migration
i've created a new model in the existing models.py file in my project and i'm trying to migrate this one specific model(not all) to the mongodb database,and it gives an error on performing the command.What exactly am i doing wrong here? Here is what i did:- I ran the command below ('Passengerems' is the model that i'm trying to migrate) python manage.py makemigrations flights --database=mongodb --name=Passengerems And it gave me the following error: (https://i.stack.imgur.com/3ikim.png) Even if i set it to default database by removing('--database')in above command,it gives another error:- "No installed app with label 'flights=mongodb'. I have also properly defined the databases in settings.py here Installed apps of django code block<-Also added the necessary apps too And also lastly,the mongodb server with 'airport' database is also running in the background. Can anyone please help me rectify this error? -
Finding a Real Time Dummy API provider
I am testing an app that updates its information in real time, and I am trying to use either REST API or Websockets to (fetch)GET the data. However I am unbale to find a service that provide an API that updates (hopefully in seconds) in regular intervals, so I can do the testing. I have tried several online tools, such as https://jsonplaceholder.typicode.com/, https://reqres.in/, and various others, The thing is none of them gives information that updates in regular intervals: either in seconds or minutes. -
Django CSRF Verification Failed Despite Correct Token
I'm having trouble with CSRF verification in Django. Despite including the correct CSRF token in my POST requests and following all the recommended steps in the Django documentation, I keep getting a "CSRF Missing" error. Here are my Axios and Django configurations. const service = axios.create({ baseURL, timeout: 4000, withCredentials: true, xsrfCookieName: 'csrftoken', xsrfHeaderName: 'X-CSRFToken', }); ... headers: { 'X-CSRFToken': Cookies.get('csrftoken'), }, # settings.py CSRF_COOKIE_NAME = 'csrftoken' CSRF_HEADER_NAME = 'X-CSRFToken' CSRF_TRUSTED_ORIGINS = [ 'http:127.0.0.1:5173' ] CORS_ALLOW_CREDENTIALS = True @ensure_csrf_cookie def get_csrf_token(request): request.META["CSRF_COOKIE_USED"] = True return JsonResponse({'msg': 'now csrftoken has been set in ur Cookies'}) When I send a POST request, the request headers already include the required X-CSRFToken and Cookie ` , but I still receive a 403 response. Here's what I've tried so far: Ensuring that the CSRF token as an X-CSRFToken header Checking that my browser is not blocking third-party cookies Changing the CSRF cookie name in my Django settings None of these solutions have worked for me. Does anyone have any other suggestions or ideas on how to fix this issue? Thanks in advance for your help! -
How to convert Django django.db.models.utils.Row to dict
For example a row like this: Row(added=datetime.date(2021, 2, 23), item='python knowledge', price=6301.0) I need this with whatever fieldname and value: { added:'2021-2-23', item:'python knowledge', price:6301.0 } In other words how I can loop through a row and store values in Dictionary generally? What I tried already: r=dict(row) #cannot convert dictionary update sequence element #0 to a sequence r=set(row) #It does work BUT lost field names r=dict(row.values())#'Row' object has no attribute 'values' r=json.dumps(row,default=str) #It does work BUT lost field names Thank you for your time. -
Embed Bokeh server with Django
I have tried to build a framework for a Django Bokeh application, but can't choose the bokeh server in a separate thread, so use server_document to build a script that can be sent to an html page. When I start the Django dev server and go to the demo.html page, the plot will not appear. I suspect that the Bokeh server may not have started correctly. But unable to see any solution here. demo.py (Bokeh application) from bokeh.plotting import figure from bokeh.layouts import column from bokeh.server.server import Server def modify_doc(doc): x_values = [1, 2, 3, 4, 5] y_values = [6, 7, 2, 4, 5] # Create a figure object fig = figure(title='Simple Bokeh Plot', x_axis_label='X-axis', y_axis_label='Y-axis') # Add a line glyph to the figure fig.line(x_values, y_values) # add the plot and slider to a layout and add to the document layout = column(fig) doc.add_root(layout) Bokeh_server = Server({'/': modify_doc}) view.py: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.shortcuts import render import threading import asyncio from bokeh.embed import server_document from tavla.bokehapp.demo import Bokeh_server def demo(request): script = server_document('http://localhost:5006/') return render(request, 'tavla/demo.html', {'script': script}) def start_bokeh_server(): Bokeh_server.start() if __name__ == '__main__': bokeh_thread = threading.Thread(target=start_bokeh_server) bokeh_thread.start() demo.html: {% extends "blog/base.html" %} … -
Django: Inconsistent "Page Not Found" Behaviour
I am currently working on a simple Asset Manager program in Django. In assman.html, there is this code snippet which deals with changing the details of an asset: {%if change_form%} <h2>Change Asset Details</h2> <form method="POST" name='change_asset' action="{% url 'assman_handler' %}"> {% csrf_token %} {% if NoSuchUser %} <script>window.alert('No such user!')</script> {% endif %} <table> <tr> <td><label for="qrcode">QR Code:</label></td> <td><input type="text" name="qrcode" class="form-control" id="qrcode" maxlength='13' value = "{{ asset.qrcode }}" required></td> </tr> <tr> <td><label for ="name" required>Asset Name: </label></td> <td><input type="text" name="name" class='form-control' value = "{{ asset.name }}" required ></input></td> </tr> <tr> <td><label for="user_id">User:</label></td> <td> <select name="user_id"> {%for user in users%} <option value="{{ user.id }}" {% if user.id == asset.user.id %}selected{% endif %}>{{ user.username }}</option> </option> {%endfor%} </select> </td> </tr> <tr> <td><label for="checkout_date">Checkout Date:</label></td> <td><input type="date" name="checkout_date" class="form-control" id="checkout_date" value = "{{asset.checkout_date}}" required></td> </tr> <tr> <td><label for="location">Location:</label></td> <td><input name="location" class="form-control" id="location" value = "{{asset.location}}" required></td> </tr> </table> <button type="submit" class="btn btn-primary" value='confirm' name='value'>Confirm Changes</button> </form> {%endif%} This form is previously summoned by clicking the button "change" as described in this code: <h2>Matched Items</h2> {%for asset in matches%} <li> {{asset.name}} at {{asset.location}} owned by {{asset.user}} expiring on {{asset.checkout_date}}</li> <form method="POST" action="{% url 'assman_handler' %}" style="display: inline-block;"> {% csrf_token %} <input type="submit" name="value" … -
Why can't I access MEDIA_URL or MEDIA_ROOT on my urls.py file?
Just trying to add on to my path but when I try adding MEDIA_URL OR MEDIA_ROOT, it just doesn't want to appear. I don't know if there's another method to this. I'm on Django v4.1.7 urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('base.urls')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] MEDIA_URL = '/images/' MEDIA_ROOT = 'static/images' CORS_ALLOW_ALL_ORIGINS = True urls.py settings.py I was expecting to for MEDIA_ROOT OR MEDIA_URL to appear right after 'settings.' but it didn't. All I want to do is extend the path. -
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.