Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Request data Modifiy in django
I have a class with APIView, which accept request. from there, I pass the request to 2 different methods, but when I print data from 2nd function, it is modified by first method. Sample class events(APIView): def post(self, request): data = request.data self.tinybird(data) self.events(data) I was expecting to have same copy of data in both method, but tinyBird method changes one line as del product['options'] and due to this I am not able to get product['options'] in events() method. As I am passing data separately to both functions, how data modification of 1st function affect data of 2nd function. Tried I tried to send copy of request to each function or one function but still same issue. data1 = request.copy() data2 = request.copy() self.tinybird(data1) self.events(data2) still data2 throw keyerror on data2['options'] -
Django tables2: Table reverts to previous value
I have a view where i display 2 tables and I have a form to create a new filter in my template. Using my code I would expect that the filter table to update and stay that way. However, after creating a new filter, it displays in the table but if i refresh the page or create a new filter, it reverts to the "original" table i.e. if i have 1 filter and I create one but i refresh the page or create a new filter afterwards, the table displayed will show just one filter. To illustrate in a more concrete way: original: [<trend_monitoring.tables.ReportTable object at 0x7f01e4d3b700>, <trend_monitoring.tables.FilterTable object at 0x7f01e4d3bc70>] [<trend_monitoring.tables.ReportTable object at 0x7f01e4d3b700>, <trend_monitoring.tables.FilterTable object at 0x7f01e4d3bc70>] 172.19.0.3 - - [10/Nov/2023:10:33:00 +0000] "POST /trendyqc/dashboard/ HTTP/1.0" 302 0 "http://localhost:8000/trendyqc/dashboard/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 OPR/106.0.0.0 (Edition developer)" original: [<trend_monitoring.tables.ReportTable object at 0x7f01e4d45670>, <trend_monitoring.tables.FilterTable object at 0x7f01e4d45bb0>] [<trend_monitoring.tables.ReportTable object at 0x7f01e4d45670>, <trend_monitoring.tables.FilterTable object at 0x7f01e4d45bb0>] 172.19.0.3 - - [10/Nov/2023:10:33:01 +0000] "GET /trendyqc/dashboard/ HTTP/1.0" 200 233735 "http://localhost:8000/trendyqc/dashboard/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 OPR/106.0.0.0 (Edition developer)" original: [<trend_monitoring.tables.ReportTable object at 0x7f01e4d3b700>, <trend_monitoring.tables.FilterTable object at 0x7f01e4d3bc70>] [<trend_monitoring.tables.ReportTable object at 0x7f01e4d3b700>, <trend_monitoring.tables.FilterTable object at … -
Use Absolute URLs for wagtail richtext
I have the following field defined on my model: email_body = RichTextField( verbose_name=_("Email Body"), help_text=_("Body of the email to send when you are out of office."), features=[ "bold", "italic", "ol", "ul", "hr", "h2", "h3", "h4", "h5", "h6", "code", "superscript", "subscript", ], max_length=2048, blank=True, null=True, ) However; when including links, images or documents in the features; the urls generated are all relative: <p data-block-key="e0dv1"><a href="/documents/14/Kunststof_Catalogus_F1204.pdf">Kunststof Catalogus (F1204)</a></p> <img alt="" class="richtext-image right" height="498" src="/media/images/aluminium-catalogus-f2204-page4_1.width-500.jpg" width="500"> <p data-block-key="5nssj"><a href="/nl/producten/">Producten</a></p> <p data-block-key="aa12u">Het <a href="/nl/"><b><i>(REDACTED)</i></b></a> team, 2023</p> As implied by the field name; this is used in emails; thus I cannot use relative URLs. The HTML is generated like so: (It is designed for template injection. Only to be used by admins.) template = util.template_from("from_string", self.email_body) body = richtext(template.render(context, request=request)) context["body"] = body context["email_body"] = body is_file = True as_html = True template_name = "office/emails/closed_email.html" How can I make the richtext editor always generate full (absolute) URLs? -
`channel_layer.group_send` won't call method in `AsyncWebsocketConsumer`
I wrote a WebSocket connection in a Django app, using Django Channels and I'm testing in my local environment with Daphne (I will use uvicorn for production) Here's a function that will be called in the save method of UserNotification model, to send title and message of notification, through user WebSocket connection. from typing import Type from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from django.conf import settings def send_user_notification( user_id: int | Type[int], title: str, message: str ): channel_layer = get_channel_layer() channel_name = settings.NOTIFICATION_WEBSOCKET_CHANNEL_NAME.format(user_id=user_id) group_name = settings.NOTIFICATION_WEBSOCKET_GROUP_NAME.format(channel_name=channel_name) async_to_sync(channel_layer.group_send)( group_name, { "type": "user_notify", "message": { "title": title, "message": message }, }, ) class UserNotification(models.Model): user = models.ForeignKey("users.User", on_delete=models.CASCADE) notification = models.ForeignKey( to="notification.Notification", on_delete=models.CASCADE ) def save(self, **kwargs): send_user_notification( user_id=self.user_id, title=self.notification.title, message=self.notification.message, message_type=self.notification.message_type, ) super().save(**kwargs) And here's my AsyncWebsocketConsumer: import json import logging from channels.generic.websocket import AsyncWebsocketConsumer from channels.layers import get_channel_layer from django.conf import settings class UserNotificationConsumer(AsyncWebsocketConsumer): async def connect(self): if self.scope["user"].is_anonymous: await self.close() self.channel_name = settings.NOTIFICATION_WEBSOCKET_CHANNEL_NAME.format( user_id=self.scope["user"].pk ) self.group_name = settings.NOTIFICATION_WEBSOCKET_GROUP_NAME.format( channel_name=self.channel_name ) self.channel_layer = get_channel_layer() await self.channel_layer.group_add(self.group_name, self.channel_name) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.group_name, self.channel_name) async def user_notify(self, event): print("Event: ", event) data = event["message"] await self.send(text_data=json.dumps(data)) And here's the asgi.py file: import os from channels.routing import … -
Change Model data after form submission in Django
Im writing a Booking System in Django with ModelForms, I Want to change value of a Boolean field in a ForeginKey model when form saves. models.py class AvailableHours(models.Model): free_date = models.ForeignKey(AvailableDates, null=True, blank=True,on_delete=models.CASCADE) free_hours_from = models.CharField(max_length=10,null=True, blank=True) free_hours_to = models.CharField(max_length=10,null=True, blank=True) status = models.BooleanField(null=True,default=True) class Bookings(models.Model): ... booked_time = models.ForeignKey(AvailableHours, on_delete=models.CASCADE,related_name='booked_time') views.py @login_required() def booking_form(request): form = forms.BookingForm() if request.method == 'POST': form = forms.BookingForm(request.POST) if form.is_valid(): book = form.save(commit=False) book.user = request.user form.save() return HttpResponseRedirect(reverse('creator:login')) return render(request, 'account/book.html', {'form': form}) forms.py class BookingForm(forms.ModelForm): class Meta: model = Bookings exclude = ('user','booking_code','confirmed',) Since I want each AvailableHours be able to get booked only once , I need the form to change value of AvailableHours status to False so I can filter it in templates. Can anyone suggest an approach to this issue ? I Tried something like form.booked_time.status = False in my views but it didnt work -
How can i work AJAX update JSON with Datatable (Datatable.JS) - Django?
I have tried to work ajax update from Django to Datatable templates like this code template [shipment.html] <table id="example"> <thead> <tr> <th>User</th> <th>Author</th> </tr> </thead> <tbody> </tbody> </table> i'm use this to got a json data and then now show this already. views.py def getlist(request): if request.method == "GET": data = serializers.serialize("json", Editors.objects.all()) respon = json.loads(data) return HttpResponse(json.dumps(respon, ensure_ascii=False), content_type="application/json") json (getlist) [{"model": "tracking.editors", "pk": 1, "fields": {"editor_name": "This AA", "num_users": 10}}, {"model": "tracking.editors", "pk": 2, "fields": {"editor_name": "This BB", "num_users": 20}}, {"model": "tracking.editors", "pk": 3, "fields": {"editor_name": "This CC", "num_users": 30}}, {"model": "tracking.editors", "pk": 4, "fields": {"editor_name": "This DD", "num_users": 40}}] Javascript <script type="text/javascript" language="javascript" class="init"> $(document).ready(function () { $('#example').DataTable({ ajax: { url: "{% url 'getlist' %}", type: 'GET', dataSrc: "", }, columns: [ {data: "fields.editor_name"}, {data: "fields.num_users"}, ], }); }); </script> Now it's data is already show on my Table but not Real-time update. How can i do it's to Real-time update when have a new record in my Database? i need someone to help for clear of this can be used like my method or need use by our method, Thanks -
dlopen symbol not found in flat namespace '_ffi_prep_closure'
I am getting the following error with the traceback. I have tried install reinstalling cryptography. Went through this as well https://github.com/ffi/ffi/issues/946 as well with no solution and a few other solution but nothing worked. ImportError: dlopen(/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/_cffi_backend.cpython-37m-darwin.so, 0x0002): symbol not found in flat namespace '_ffi_prep_closure' thread '<unnamed>' panicked at /Users/runner/.cargo/registry/src/index.crates.io-6f17d22bba15001f/pyo3-0.18.3/src/err/mod.rs:790:5: Python API call failed note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace Traceback (most recent call last): File "./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/Users/rj/.pyenv/versions/3.7.17/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/rj/vogo/consumer-api/api/accounts/models.py", line 2, in <module> from .users.models import ( File "/Users/rj/vogo/consumer-api/api/accounts/users/models.py", line 23, in <module> from libs.clients import paytm_client, redis_consumer_client, ola_client, amazonpay_client File "/Users/rj/vogo/consumer-api/api/libs/clients/__init__.py", line 35, in … -
Django Migration Error - Error comes that account_user model should have prior migration before admin migration
first migration was done before creation of the accounts application and then after creation of accounts model it starts throwing error when doing the migration on global level i.e running python manage.py makemigrations and python manage.py migrate. error like - django.db.utils.ProgrammingError: relation "accounts_user" does not exist 2. django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. 3.File "/home/dell/Desktop/foodOnline_main/env/lib/python3.10/site-packages/django/db/migrations/loader.py", line 327, in check_consistent_history raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'. -
django.core.exceptions.FieldDoesNotExist: CustomUser has no field named 'usermanager.CustomUser.full_name'
I am creating a custom user model as follows: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) full_name = models.CharField(max_length=100) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) phone_number = models.CharField(max_length=10) institution = models.CharField( max_length=100, blank=True, null=True ) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [full_name, phone_number] def __str__(self): return self.email It works correctly but when I create superuser, I get the following error django.core.exceptions.FieldDoesNotExist: CustomUser has no field named 'usermanager.CustomUser.full_name' -
DJANGO JWT "Authentication credentials were not provided."
i was trying to auth all my api with jwt i am getting this error when i try access api . i dont know how to resolve it .can you please help. i have tried all possible solution shown on internet but still i an unable to resolve it. the error that is display on termianl: Unauthorized: /action_items/ [10/Nov/2023 12:21:50] "POST /action_items/ HTTP/1.1" 401 58 enter image description here SETTINGS.PY type herefrom pathlib import Path from dotenv import load_dotenv import datetime from datetime import timedelta import os load_dotenv() BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.getenv('SECRET_KEY', None) DEBUG = True ALLOWED_HOSTS = ['*'] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication' ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', #'rest_framework.permissions.AllowAny' ] } INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'rest_framework', 'rest_framework.authtoken' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'expenses.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'expenses.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.getenv("DB_NAME", None), 'HOST': os.getenv("DB_HOST", 'localhost'), 'PORT': os.getenv("DB_PORT", 3306), 'USER': os.getenv("DB_USERNAME", None), 'PASSWORD': os.getenv("DB_PASSWORD", None), } } # Password validation # https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators … -
Django template error after parenthesis added by autoformat
I use VSCode and the Django Template Support extension for autoformatting templates. It adds parentheses to my code making it not work. before: {% elif n > page_obj.number|add:'-5' and n < page_obj.number|add:'5' %} after: {% elif n > (page_obj.number|add:'-5' and n < (page_obj.number|add:'5')) %} Template error: In template N:\Coding Projects\poc\templates\poc\product_list_grid.html, error at line 133 Could not parse some characters: |(page_obj.number||add:'-5' 123 : <a class="page-link" href="?page=1" aria-label="First"> 124 : <span aria-hidden="true">&laquo;</span> 125 : <span class="sr-only">First</span> 126 : </a> 127 : </li> 128 : {% endif %} 129 : 130 : <!-- with filter and pages in between --> 131 : {% for n in page_obj.paginator.page_range %} 132 : {% if request.GET.item_code or request.GET.brand__brand_name or request.GET.description %} 133 : {% if n == page_obj.number%} 134 : <li class="page-item active"> 135 : <span class="page-link"><b>{{ n }}</b><span class="sr-only"></span></span> 136 : </li> 137 : {% elif n > (page_obj.number|add:'-5' and n < (page_obj.number|add:'5')) %} 138 : <li class="page-item"> 139 : <a class="page-link" href="{% update_url n 'page' request.GET.urlencode %}">{{ n }}</a> 140 : </li> 141 : {% endif %} 142 : 143 : <!-- without filter and pages in between --> Is this a formatter issue? How can I solve this? Removing the parenthesis worked but … -
AttributeError: 'EmailMessage' object has no attribute 'get_all' when trying to send email with smtplib in django app
I use celery in my django web application to send mails. Here is the code: @shared_task def envoi_email(subject,body,to): smtp_host = os.environ.get('EMAIL_HOST') smtp_port = os.environ.get('EMAIL_PORT') email_from = os.environ.get('EMAIL_USER') pwd = os.environ.get('EMAIL_PASSWORD') msg = EmailMessage(subject,body,email_from,[to]) msg.content_subtype = "html" server = smtplib.SMTP(smtp_host) server.connect(smtp_host,smtp_port) server.ehlo() server.login(email_from, pwd) server.send_message(msg) server.quit() logging.info(f"Mail envoyé vers {to}") The message I get: [2023-11-10 07:07:58,508: ERROR/ForkPoolWorker-8] Task tasks.tasks.envoi_email[62cf0d90-ef4e-4f85-b7aa-bebd023289ae] raised unexpected: AttributeError("'EmailMessage' object has no attribute 'get_all'") celery-worker | Traceback (most recent call last): celery-worker | File "/py/lib/python3.9/site-packages/celery/app/trace.py", line 477, in trace_task celery-worker | R = retval = fun(*args, **kwargs) celery-worker | File "/py/lib/python3.9/site-packages/celery/app/trace.py", line 760, in __protected_call__ celery-worker | return self.run(*args, **kwargs) celery-worker | File "/electron/tasks/tasks.py", line 216, in envoi_email celery-worker | server.send_message(msg) celery-worker | File "/usr/local/lib/python3.9/smtplib.py", line 944, in send_message celery-worker | resent = msg.get_all('Resent-Date') celery-worker | AttributeError: 'EmailMessage' object has no attribute 'get_all' Need help please -
Django + daphne + StreamingHttpResponse return chunked data not streaming data
I am currently developing API using StreamingHttpResponse in Django. As far as I know, StreamingHttpResponse is supposed to output results in yield units, but in reality, it outputs yield value's' For example, I used generator below. def iterator(): for i in range(100000): yield {"iteration ":str(i)} Then, the result value is expected to have one yield value each time. {"iteration" : "1"} {"iteration" : "2"} ... However, in reality, it returns a certain buffer size(maybe 4000chars), waits, and then returns again. {"iteration" : "1"} {"iteration" : "2"} ~~ {"iteration" : "100"} In order to actually return a value every time without a buffer like above, which settings among django, daphne, and streaminghttpresponse should I add or remove? actual log : 2023-11-10 05:29:58,361 DEBUG 8 --- [MainThread] daphne.http_protocol:283 HTTP response chunk for ['192.168.192.1', 0] --- [7f6f53f9c0a393a547dccbdde2c59065] [24a60a12badf08b6] [user:6549c3c2c8fd4d4d6099d6d1] 2023-11-10 05:29:58,376 DEBUG 8 --- [MainThread] daphne.http_protocol:283 HTTP response chunk for ['192.168.192.1', 0] --- [7f6f53f9c0a393a547dccbdde2c59065] [24a60a12badf08b6] [user:6549c3c2c8fd4d4d6099d6d1] 2023-11-10 05:29:58,398 DEBUG 8 --- [MainThread] daphne.http_protocol:283 HTTP response chunk for ['192.168.192.1', 0] --- [7f6f53f9c0a393a547dccbdde2c59065] [24a60a12badf08b6] [user:6549c3c2c8fd4d4d6099d6d1] 2023-11-10 05:29:58,412 DEBUG 8 --- [MainThread] daphne.http_protocol:283 HTTP response chunk for ['192.168.192.1', 0] --- [7f6f53f9c0a393a547dccbdde2c59065] [24a60a12badf08b6] [user:6549c3c2c8fd4d4d6099d6d1] 2023-11-10 05:29:58,432 DEBUG 8 --- [MainThread] daphne.http_protocol:283 HTTP response chunk for ['192.168.192.1', 0] … -
dynamic menus with Django dont have the same height
Screenshoot from my Menuscards Views Der html und CSS code he height of the cards do not match, the first card is not a margin-top, the other one would easily be 10px. From my understanding, any new card they produce should have the same properties and the same position. I don't even know where to look. How i can fix this? -
gunicorn looking for deleted module; cannot run django application in GCP
I have a django application that's been running fine on GCP, and I recently removed a dependency: django-colorfields. I didn't need this functionality, so I removed these items from my models, migrated the database and uninstalled the module. Now when I deploy my project to GCP, I can't get past the admin login page. The admin page (https://myproject.com/admin) shows up just fine, but when I enter my username and password and hit enter, I get a HTTP 500 internal server error. I checked the internal server logs, and there's a number of gunicorn errors, but this one stands out: 2023-11-09 20:02:29.950 Traceback (most recent call last): File "/layers/google.python.pip/pip/lib/python3.11/site-packages/gunicorn/arbiter.py", line 609, in spawn_worker worker.init_process() File "/layers/google.python.pip/pip/lib/python3.11/site-packages/gunicorn/workers/gthread.py", line 95, in init_process super().init_process() File "/layers/google.python.pip/pip/lib/python3.11/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/layers/google.python.pip/pip/lib/python3.11/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() 2023-11-09 20:02:29.950 ^^^^^^^^^^^^^^^ 2023-11-09 20:02:29.950 File "/layers/google.python.pip/pip/lib/python3.11/site-packages/gunicorn/app/base.py", line 67, in wsgi 2023-11-09 20:02:29.950 self.callable = self.load() 2023-11-09 20:02:29.950 ^^^^^^^^^^^ 2023-11-09 20:02:29.950 File "/layers/google.python.pip/pip/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2023-11-09 20:02:29.950 return self.load_wsgiapp() 2023-11-09 20:02:29.950 ^^^^^^^^^^^^^^^^^^^ 2023-11-09 20:02:29.950 File "/layers/google.python.pip/pip/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2023-11-09 20:02:29.950 return util.import_app(self.app_uri) 2023-11-09 20:02:29.950 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2023-11-09 20:02:29.950 File "/layers/google.python.pip/pip/lib/python3.11/site-packages/gunicorn/util.py", line 371, in import_app 2023-11-09 20:02:29.950 mod = importlib.import_module(module) 2023-11-09 20:02:29.950 … -
Easiest way to integrate a Python program into a locally hosted website?
I'm currently working on a project for a course using Python and The Movie Database (TMDB) API. Our project brief doesn't require an interactive user interface, but we'd like to go a step further and at least have a locally hosted website that utilizes our script. We have a few inputs for the user to choose a genre, language, release date, etc. and the output is a list of recommended movies that fit the criteria. Is there any way for us to do this pretty easily? I have been looking into Streamlit, Flask, and Django, but there is a learning curve as I'm just learning Python. We would like to show a screen recording of the locally hosted website during class, it doesn't need to be available for users. I am familiar with HTML, CSS, and intermediate JavaScript. Integrating our finished Python code to work with a website is just new to me. I experimented a little bit with PyScript and Streamlit. I have installed Streamlit, Flask, and Django libraries but I'm getting mixed up with so many options. I am expected a simple webpage with 4-5 inputs that filter through TMDB using their API. Would Streamlit, Flask, or Django … -
How to make Dark and Light theme with django?
everyone I have a conflict with Django static files with javascript and jQuery. I'm making a website with two themes Dark and Light with my basic HTML, JS, and CSS it's working very well, but when I moved it to the Django template with static files I got an error although the full style and JS functions working very well. Uncaught TypeError: Cannot read properties of null (reading 'querySelector') That's my HTML <div class="color-modes position-relative ps-5"> <a class="bd-theme btn btn-link nav-link dropdown-toggle d-inline-flex align-items-center justify-content-center text-primary p-0 position-relative rounded-circle" href="#" aria-expanded="true" data-bs-toggle="dropdown" data-bs-display="static" aria-label="Toggle theme (light)"> <svg class="bi my-1 theme-icon-active"> <use href="#sun-fill"></use> </svg> </a> <ul class="dropdown-menu dropdown-menu-end fs-14px" data-bs-popper="static"> <li> <button type="button" class="dropdown-item d-flex align-items-center active" data-bs-theme-value="light" aria-pressed="true"> <svg class="bi me-4 opacity-50 theme-icon"> <use href="#sun-fill"></use> </svg> Light <svg class="bi ms-auto d-none"> <use href="#check2"></use> </svg> </button> </li> <li> <button type="button" class="dropdown-item d-flex align-items-center" data-bs-theme-value="dark" aria-pressed="false"> <svg class="bi me-4 opacity-50 theme-icon"> <use href="#moon-stars-fill"></use> </svg> Dark <svg class="bi ms-auto d-none"> <use href="#check2"></use> </svg> </button> </li> </ul> </div> and that's my JQuery and JS code: }(jQuery), APP = APP || {}, function (e) { 'use strict'; APP.colorModes = { init: function () { this.colorModes(); }, colorModes: function () { if (!document.documentElement.hasAttribute("data-bs-theme")) return; const e … -
error install mysqlclient command pip install mysqlclient
error: command 'C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.37.32822\bin\HostX86\x64\cl.exe' failed with exit code 2 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mysqlclient Failed to build mysqlclient ERROR: Could not build wheels for mysqlclient, which is required to install pyproject.toml-based projects I have this error when trying to install MySQLCorn, I already have the VS builds, the updated Microsoft C++ versions installed but I still can't fix the problem pls help -
Django MySQL retrieving data from multiple tables
I am trying to retrieve data from multiple tables in the same query to be rendered in an html page. Models and view below, ultimately I am trying to return a query set with following structure: filter SearchResults table by postcode queryset returns any listings from SearchResults matching the postcode, I would need to reference each field in SearchResults as well as including any related media records(one to many, i.e multiple media records for each listing) Not compulsory but nice to have the media returned in index order as I hope to render to html template in correct order Models.py class SearchResults(models.Model): listing_id = models.AutoField(primary_key=True) listing_date_added = models.DateField listing_last_updated = models.DateField(blank=True, null=True) price_from = models.PositiveIntegerField(blank=True, null=True) price_to = models.PositiveIntegerField(blank=True, null=True) suburb = models.CharField(max_length=100, blank=True, null=True) state = models.TextField(blank=True, null=True) postcode = models.PositiveIntegerField(blank=True, null=True) def __str__(self): return f"{self.suburb}, {self.display_price}" class Meta: managed = False db_table = "listing" class Media(models.Model): listing_id = models.ForeignKey(SearchResults, on_delete=models.DO_NOTHING) media_url = models.CharField(max_length=300, blank=True, null=True) media_index = models.PositiveIntegerField(blank=True, null=True) class Meta: managed = False db_table = 'media' def __str__(self): return f"Media url: {self.media_url}, Media index: {self.media_index}" Views.py # POST request coming from initial search field entry def search_results(request): if request.method == "POST": postcode_lookup = request.POST.get('search')[-4:] results = SearchResults.objects.filter(postcode=postcode_lookup).prefetch_related('media-set') … -
Django - deterministic=True requires SQLite 3.8.3 or higher
I'm using AWS App Runner to deploy a django web app, following this guide Deploy and scale Django applications on AWS App Runner. I have no problems deploying, but when I access a page, I'm getting the following error during template rendering. deterministic=True requires SQLite 3.8.3 or higher I searched for this error and found this solution, but I don't know how to apply it to AWS App Runner. Can anyone help me with this or have any other solutions to try? -
AttributeError / 'str' object has no attribute 'objects'
Hello, i'm newest in django and python and this error take a lot of my time and i don't now where is the problem views.py currentUser = request.user assert isinstance(category.objects, object) categoryData = category.objects.get(categoryName=category) newListing = Listing(` title=title, description=description, imageurl = imageurl, price=price, Category=categoryData, owner=currentUser ) newListing.save() return HttpResponseRedirect(reverse(index)) models.py class Listing(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=2560) imgUrl = models.CharField(max_length=100000) price = models.FloatField() isActive = models.BooleanField(default=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="user") category = models.ForeignKey(Category, on_delete=models.CASCADE , blank=True, null=True, related_name="categort") def __str__(self): return self.categoryName I try many solutions from here but it's fail -
GET parameters not retrievable in action view
GET parameters seem to always return empty when attempting to retrieve them from the action view. For example when I add the parameter 'form1' to the url that maps to my action http://localhost:8000/admin/form_builder/formdefinition/actions/export_form?form_name=form1 the parameter is removed when I access the request.GET object in the action view. Is it possible to access GET parameters somehow? @admin.register(FormDefinition) class FormDefinitionAdmin(DjangoObjectActions, BaseAdmin): changelist_actions = ('export_forms') def export_forms(self, request, queryset): # returns empty here form_name = request.GET.get('form_name') exporter = FormExporter() file_path = exporter.export_form(form_name) with open(file_path, 'r') as file: response = HttpResponse(file, content_type='application/pdf') response["Content-Disposition"] = "attachment; filename=forms.json" return response -
Cannot pass GET parameters to django admin custom action view
GET parameters seem to always return empty when attempting to retrieve them from the action view. For example when I add the parameter 'form1' to the form action url, it is missing when I access the request.GET object in the action view. Is it possible to access GET parameters in the action view method somehow? @admin.register(FormDefinition) class FormDefinitionAdmin(BaseAdmin): actions = ('export_forms') def export_forms(self, request, queryset): # returns empty here form_name = request.GET.get('form_name') exporter = FormExporter() file_path = exporter.export_form(form_name) with open(file_path, 'r') as file: response = HttpResponse(file, content_type='application/pdf') response["Content-Disposition"] = "attachment; filename=forms.json" return response -
Django not able to alter queryset in Class Based View with POST with get_queryset
Not really sure how I can't figure this out but I am trying to POST a form to alter the contents of get_queryset() but it isn't keeping the filtered items, it calls get_queeryset multiple times and loses the POST filtering. I must be doing something wrong, can someone help? class GeneralLedgerDatatableView(DatatableView): model = GeneralLedger datatable_class = GeneralLedgerDatatable template_name = 'accounting/general_ledger/general_ledger_list.html' def post(self, request, *args, **kwargs): self.object_list = self.get_queryset() context = self.get_context_data() return self.render_to_response(context) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) title = 'General Ledger: Transaction Detail' context['title'] = title properties = Property.objects.filter(active=True).order_by('name') accounts = GLAccount.objects.all().order_by('sortable_account_identifier') current_property = self.request.session.get('property') if current_property: current_property = current_property.pk form = SelectFilterOptionsForm(self.request.POST or None, properties=properties, accounts=accounts, initial={ 'from_date': timezone.now().replace(day=1, month=1).strftime('%m/%d%/%Y'), 'accounts': [x.pk for x in accounts], 'to_date': timezone.now().strftime('%m/%d%/%Y'), 'property': current_property }) context['form'] = form return context def get_queryset(self): queryset = super().get_queryset() if self.request.POST: # THIS IS CALLED BUT SO IS GET AND ALL ARE RETURNED? property = self.request.POST.get('property') accounts = [x for x in self.request.POST.getlist('accounts') if x] from_date = self.request.POST.get('from_date') to_date = self.request.POST.get('to_date') q_items = list() if property: # filter_dict['journal_line_item__property__pk__in'] = properties q_items.append(Q( property=property, )) q_items.append(Q( account__pk__in=accounts, )) q_items.append( Q( date_entered__date__gte=datetime.datetime.strptime(from_date, '%m/%d/%Y'), date_entered__date__lte=datetime.datetime.strptime(to_date, '%m/%d/%Y'), ) ) queryset = queryset.select_related( 'transaction_code', 'book', 'account', 'property' ).filter(*q_items) return queryset -
How do I use Django with phpMyAdmin? [closed]
So, bear with me as I am very new with this, I followed an guide to create an html site that can have a login system, it used WampServer, Phyton and Django to create it and it works fine, but now I want to do a ticket system on the site, and I am really confused on how do I get or save things that are in the database but are not declared on models.py, things that already got added by Django or tables that I created via phpMyAdmin. If any more context or code is needed I please just tell me, thanks in advance I tried looking for tutorials on the matter but I really suck at this and only get the reverse of what I want