Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I setup Django to serve files on a file server?
I am working on a Django website where files are going to be sold. These files can be large in size, up to 5GB. So, I believe that in addition to a VPS for serving the website, I also need to set up a file server (download server). First of all, since I haven't used download servers before, I'm unsure about how to connect the download server to the VPS that hosts my website. In my research, I've come across the idea of setting up a subdomain. For instance, if my website is mywebsite.com, I would create a new DNS A record, like dl.mywebsite.com, and then use this link to serve the files to users on my website. Is this a correct approach? And also what protocol should be used for this connection when a user clicks a download button? Is it going to be a file protocol, HTTP, FTP, or something else? Another question is that I have no idea how to configure my Django project to provide download links to users who have purchased a file when the files are located on another server. For example, how do I configure the media root and URL so that the … -
how to pass queryset or kwarg to RangeFilter class in Django filters
I'm working on a Django-driven website which uses django-filters and, specifically, RangeFilter to show price diapason of the real estate properties and visualize it as a slider on search form. My queryset is initially formed in the PropertyListView as a list of objects with a certain status (sale or rent), and then it is being passed to the filter, PropertyFilter. The PropertyFilter uses several other classes to construct corresponding widgets, such as slider for the price: class PropertyFilter(FilterSet): price = PriceFilter() ... class PriceFilter(RangeFilter): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) values = [p.price for p in Property.objects.all()] min_value = min(values) max_value = max(values) self.extra['widget'] = CustomRangeWidget(attrs={'label':_('Price, €'),'data-range_min':min_value,'data-range_max':max_value}) The problem is that the PriceFilter does not "know", which objects are in the queryset, and takes the price diapason from the full list of objects. This results in awkward slider, whose diapason is too wide, from 600 to 300,000 euro, which is irrelevant. I want to make the PriceFilter to get prices from the queryset. How it is possible to do it? I've tried to use queryset directly inside this filter, to pass the queryset into it, or to pass the status as a kwarg parameter, but every time I got an … -
how to preserve data in form after a unsuccessful submit or after page reload after the error?
I have a Crud Project in which when i add any new member in the list the data i entered is vanished if i entered the same email which is already registered, i want that if i entered the mail id which is already registered so it will only give a message of that ID is already registered and data which i filled in the form it will not vanished , can we do this ? type here i want that if i entered the mail id which is already registered so it will only give a message of that ID is already registered and data which i filled in the form it will not vanished , can we do this ? Add_Member view.py @login_required def user_data_create(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] gender = request.POST['gender'] role = request.POST['role'] if Members.objects.filter(email=email).exists(): messages.error(request,"This Email Is already registred") else: user_data = Members.objects.create(user=request.user, name=name, email=email, phone=phone, gender=gender,role=role) user_data.save() messages.success(request,"New Member added Succesfully") return redirect('dashboard_page') return render(request, 'add.html') Update View.py @login_required def user_data_update(request, id): try: user_data = Members.objects.get(id=id) if user_data.user == request.user: if request.method == 'POST': user_data.name = request.POST['name'] user_data.email = request.POST['email'] user_data.phone = request.POST['phone'] user_data.gender = … -
Running a django project on windows server 2016 - IIS
I’m trying to run a django site on windows server 2016. I am using IIS and FastCGI to do this. After trying to open the site in the browser, I get this error message: Error occurred while reading WSGI handler: traceback (most recent call last).:File "C:\Python\Lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response. physical_path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python\Lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python\Lib\site-packages\wfastcgi. py", line 605, in get_wsgi_handler handler = handler() ^^^^^^^^^ File "C:\Python\Lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "C:\Python\Lib\site-packages\django\__init__. py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python\Lib\site-packages\django\apps\registry.py", line 83, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant StdOut: I tried adding enviromental variables which didn't help but maybe I didn't set them correctly. I would be very grateful for advice and guidance on how to fix this error. Have a nice day Lukas -
change dropdown data - django
How can i change the values in the department fields based on the selection made in school. I have the below models school_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) name = models.CharField(max_length=50) abbr = models.CharField(max_length=5) class Department(models.Model): dept_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) school = models.ForeignKey(School, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=30) forms.py school = forms.ModelChoiceField(required=True, queryset=School.objects.all(), empty_label="Select School", widget=forms.Select( attrs={ 'class': 'form-control select form-select', 'onchange': 'this.form.submit()' } )) department = forms.ModelChoiceField(required=True, queryset=Department.objects.all(), empty_label="Select Department", widget=forms.Select( attrs={ 'class': 'form-control select form-select' } )) how can i tweak my views? -
Syncing issue within Socket IO
I've implemented a website chat with python-socketio and socket.io-client. At times, when we simultaneously open multiple tabs in different browsers or incognito sessions with the same logged-in user, the newly opened tabs can successfully send and receive messages. However, the older tabs do not send or receive messages, even though they remain connected to Python Socket.IO and socket.io-client. Additionally, I've already used a room session for managing the connections. This Problem happens on a live server where, at any point about 50-100 users are connected to the socket, not on localhost. The versions I'm using are as follows: python-socketio==5.9.0 uvicorn==0.16.0 eventlet==0.33.3 socket.io-client = 4.7.2 Backend: import socketio sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins='*', logger=True, engineio_logger=True) connected_users = {} room_user_count = {} @sio.on("connect") async def connect(sid, environ): try: query_string = environ.get("QUERY_STRING") or "Anonymous" if query_string: username = query_string.split("username=")[1].split("&")[0] await sio.save_session(sid, {'username': username}) room_name = await change_group_name(username) sio.enter_room(sid, room_name) print(f"[Connected] {sid}") except Exception as e: print("Connected error", str(e)) @sio.on("login") async def handle_login(sid, data): username = data.get("username") session_id = await sio.get_session(sid) connected_users[sid] = {"username": username, "session_id": session_id['username']} print(f"{username} logged in.") @sio.on("disconnect") async def disconnect(sid): try: username = connected_users.get(sid, {}).get("username", "Anonymous") connected_users.pop(sid, None) leave_room = await change_group_name(username) sio.leave_room(sid, leave_room) print(f"Disconnected: {sid}, Username: {username}") except Exception as … -
Using Django ORM to query a Model with two FKs that are related through an unique_together constraint on a third Model
I am currently facing a challenge in creating a QuerySet that accurately represents the relationships within my Django models. I have a model equipped with two foreign keys, FK1 and FK2. These two foreign keys, when combined, create a tuple representing a classification (FK1, FK2 -> CLS.pk). This relationship is managed and represented through another model, where I store the records corresponding to these foreign keys and the resulting classification (FK1, FK2, CLS.pk). Defining my question has been a challenge in itself, so I've tried to simplify the relationship to illustrate the core idea of what I'm attempting to achieve here. class Event(models.Model): value = models.DecimalField(decimal_places=2, max_digits=11, default=0.0) event_date = models.DateField() local = models.ForeignKey(Local, on_delete=models.CASCADE, related_name='event_set') origin = models.ForeignKey(Origin, on_delete=models.CASCADE, related_name='event_set') class Meta: db_table = 'db_event' class Local(models.Model): name = models.CharField(max_length=100, unique=True) class Meta: db_table = 'db_local' class Origin(models.Model): name = models.CharField(max_length=100, unique=True) class Meta: db_table = 'db_origin' class Classification(models.Model): name = models.CharField(max_length=100, unique=True) class Meta: db_table = 'db_classification' class ClassificationPerOriginAndLocal(models.Model): local = models.ForeignKey(Local, on_delete=models.CASCADE, related_name='classification_related_set') origin = models.ForeignKey(Origin, on_delete=models.CASCADE, related_name='classification_related_set') classification = models.ForeignKey(Classification, on_delete=models.CASCADE, related_name='classification_related_set') class Meta: db_table = 'db_classification_per_origin_and_local' unique_together = ('local', 'origin',) Consider an 'Event' Model designed to store records for events occurring at a specific origin … -
I am trying to host my Django project in heroku, but i am getting an error when i am collecting static files with python manage.py collectstatic
I am trying to host my Django project in heroku, but i am getting an error when i am collecting static files with python manage.py collectstatic. I have looked for this file 'plugins/flot/jquery.flot.js.map' in my plugin folder, but i can't find it anywhere. whitenoise.storage.MissingFileError: The file 'plugins/flot/jquery.flot.js.map' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x000001BE271A1810> I tried running python manage.py collectstatic, reconfigure the manifestfile in the settings.py, but no solution. -
Can I run python 3.11 django application on centOS 7? Failing to execute wsgi script
I am trying to run my django application based on python version 3.11.5 on centOS 7 with openssl version 3.0.11. My application is not able to find math module which comes in-built with python installation. But I am able to import math module in the python script. I am getting the below error, when I try to run my application on server: [Tue Oct 24 20:44:17.092551 2023] [wsgi:error] [pid 30479] [client 129.214.105.163:35318] mod_wsgi (pid=30479): Failed to exec Python script file '/var/www/html/hmi.hmt/HMT/HMT/wsgi.py'. [Tue Oct 24 20:44:17.092643 2023] [wsgi:error] [pid 30479] [client 129.214.105.163:35318] mod_wsgi (pid=30479): Exception occurred processing WSGI script '/var/www/html/hmi.hmt/HMT/HMT/wsgi.py'. [Tue Oct 24 20:44:17.116764 2023] [wsgi:error] [pid 30479] Traceback (most recent call last): [Tue Oct 24 20:44:17.116826 2023] [wsgi:error] [pid 30479] File "/var/www/html/hmi.hmt/HMT/HMT/wsgi.py", line 17, in <module> [Tue Oct 24 20:44:17.116976 2023] [wsgi:error] [pid 30479] from django.core.wsgi import get_wsgi_application [Tue Oct 24 20:44:17.117017 2023] [wsgi:error] [pid 30479] File "/var/www/html/new_env/lib/python3.11/site-packages/django/__init__.py", line 1, in <module> [Tue Oct 24 20:44:17.117097 2023] [wsgi:error] [pid 30479] from django.utils.version import get_version [Tue Oct 24 20:44:17.117130 2023] [wsgi:error] [pid 30479] File "/var/www/html/new_env/lib/python3.11/site-packages/django/utils/version.py", line 1, in <module> [Tue Oct 24 20:44:17.117200 2023] [wsgi:error] [pid 30479] import datetime [Tue Oct 24 20:44:17.117225 2023] [wsgi:error] [pid 30479] File "/var/www/html/Python-3.11.6/Lib/datetime.py", line 12, … -
Supervisor (superuser) approval of root superuser login in Django
In my Django project with two superusers called root and supervisor, I'm trying to implement the following flow: When root logs into the application, he is directed to a 'waiting for authorisation' page In the meantime, an email is sent to the supervisor containing the OTP in plain text as well as a parameterised link (containing the OTP and session token) When the supervisor clicks this link, approval via OTP verification for root occurs If authentication is successful, the supervisor sees a message saying OTP authentication successful, and in the meantime, the root user is redirected from the waiting page to the landing page If authentication fails, root and the supervisor are shown a message on the page saying that the OTP authorisation failed The only user who needs OTP authentication is root and approval can only be granted by supervisor. My first approach had been to trigger OTP generation when root logs in, root gets redirected to a waiting page. Once the supervisor clicks the link, root is redirected to the landing page All my code was working except for the part where root gets redirected from the waiting area to the landing page. My current approach is to … -
Geographic point created in admin Django panel is not displayed correctly located in the html
I've created a model with postgis and rendered the templates with Folium. But when rendering the html. Geographic points appear in a geographic area that does not correspond. I've checked the srid and from what I've read they come by default at 4326 or WGS84. Can anyone help me fix this? models.py from django.contrib.gis.db import models class Location(models.Model):name=models.CharField(max_length=250,verbose_name='nombre arbol') punto=models.PointField() def str(self): return f"{self.punto}"` views.py from django.shortcuts import renderimport foliumfrom .models import * def home(request): locations=Location.objects.all()initialMap=folium.Map(location=[-33.56919516402464, -70.81542789027874], zoom_start=18) for location in locations: folium.Marker(location.punto ,popup='Arbol'+ location.punto ).add_to(initialMap) context={'map':initialMap._repr_html_(),'locations':locations} return render(request, 'survey/home.html',context) admin.py from django.contrib import adminfrom .models import * admin.site.register(Location) error points This is where the dots should appear I need to know what I need to set so that the points appear where they correspond geographically where I created them (I created them from the Django admin panel) Point Creation from admnin panel here is the libs installed on my venv asgiref==3.7.2 branca==0.6.0 certifi==2023.7.22 charset-normalizer==3.3.1 Django==4.2.6 folium==0.14.0 GDAL @ file:///-/Downloads/GDAL-3.4.3-cp311-cp311-win_amd64.whl#sha256=f78861fb5115d5c2f8cf3c52a492ff548da9e1256dc84088947379f90e77e5b6 idna==3.4 Jinja2==3.1.2 MarkupSafe==2.1.3 numpy==1.26.1 psycopg2==2.9.9 requests==2.31.0 sqlparse==0.4.4 tzdata==2023.3 urllib3==2.0.7 I would appreciate your help, thank you very much for your time. -
How to fix in django "Page not found (404)" error ("Django tried these URL patterns... The empty path didn't match any of these.")
As a newbie to Django, I encountered the same problem as many before me. I would appreciate if you didn't mark my question as a double immediately because I checked the fixes those old posts suggested but to no avail, unfofrtunately. When I start server I get: Page not found (404). Using the URLconf defined in shops_online.urls, Django tried these URL patterns, in this order: admin/ api/organizations/ [name='organizations-list'] api/organizations/<int:id>/shops_file/ [name='get-shops-file'] api/shops/<int:id>/ [name='shop-view'] api/v1/token/ [name='token_obtain_pair'] api/v1/token/refresh/ [name='token_refresh'] api/v1/token/verify/ [name='token_verify'] docs/ [name='schema-swagger-ui'] The empty path didn’t match any of these. Here`s my views.py: from django.shortcuts import render from rest_framework.views import APIView from .models import Shop, Organization from shop.serializers import OrganizationSerializer, ShopSerializer from rest_framework.response import Response from rest_framework import status import pandas as pd import logging from django.http import HttpResponse from django.core.mail import send_mail from background_task import background from background_task.models import Task from background_task.models import Task from .tasks import send_email_task from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response @api_view(['GET']) @permission_classes([IsAuthenticated]) class OrganizationListView(APIView): def get (self, request): try: organizations = Organization.objects.filter(is_deleted=False) serializer = OrganizationSerializer(organizations, many=True) # logging logging.info('GET request was successful') return Response(serializer.data, status=status.HTTP_200_OK) except Exception as e: logging.error(f'An error occurred while executing the request: {e}') return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(['PUT']) … -
Automatically refresh Django admin panel
I'm wanting to automatically refresh/update a model in the admin page to show updated data. How can I modify the admin panel to do that? -
CommandError: Unable to serialize database: 'utf-8' after command makemigrations
I use Windows 11 Pro and Visual Studio Code. I created a new almost empty database in pgadmin 4 (PostgreSQL 16). I set the default settings in the project settings in django (settings.py): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5433', }, } After the python manage.py makemigrations command I get the following error in the terminal: Traceback (most recent call last): File "C:\Users\twitchtest\Myproject\project\manage.py", line 22, in <module> main() File "C:\Users\twitchtest\Myproject\project\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\core\management\base.py", line 106, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\core\management\commands\makemigrations.py", line 156, in handle loader.check_consistent_history(connection) File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\db\migrations\loader.py", line 313, in check_consistent_history applied = recorder.applied_migrations() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\db\migrations\recorder.py", line 81, in applied_migrations if self.has_table(): ^^^^^^^^^^^^^^^^ File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\db\migrations\recorder.py", line 57, in has_table with self.connection.cursor() as cursor: ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\db\backends\base\base.py", line 330, in cursor return self._cursor() ^^^^^^^^^^^^^^ File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\db\backends\base\base.py", line 306, in _cursor self.ensure_connection() File "C:\Users\twitchtest\Myproject\project\venv\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, … -
get_form_kwargs being omitted
I have a simple admin form: class SomeForm(forms.ModelForm): class Meta: model = Process fields = ["start", "end", "result", "description", "user"] def __init__(self, user=None, *args, **kwargs): user = kwargs.pop("user", None) super().__init__(*args, **kwargs) self.fields["user"].initial = user The form is being instanciated by a normal ModelAdmin: class SomeAdmin(admin.ModelAdmin): form = SomeForm def get_form_kwargs(self, request): return {"user": request.user} def get_form(self, request, obj=None, change=False, **kwargs): form = super().get_form(request, obj, change, **kwargs, **self.get_form_kwargs(request)) return form The output of the print statement is never visible in the terminal. Why? I want to be able to access the "user" as an initial value in the form: Edit: Code updated according to @Willem Van Onsem's input (still not working: Error: TypeError saying modelform_factory() got an unexpected keyword argument 'user'.) -
Add extra field to serializer
I need to add an extra field to serializer. I have below django serialzer { "count": 2, "next": null, "previous": null, "results": [ { "id": 8363, "name": "test10", "description": "" }, { "id": 8360, "name": "check", "description": "edew" } ] } I need to add a field, for example, let us call it as new_field. How can we make this possible? The structure I am expecting is below. { "count": 2, "next": null, "previous": null, "results": [ { "id": 8363, "name": "test10", "description": "" }, { "id": 8360, "name": "check", "description": "edew" } ], "new_field": "New Field Value" } -
GeoDjango: Building route of MultiLineStrings between 2 railway stations
I'm using GeoDjango (django.contrib.gis). I have 2 models: class RailwayStation(models.Model): point = models.PointField('Point') class RailwayLine(models.Model): mls = models.MultiLineStringField('MultiLineString') In my DB I have railway stations and a lot of railway lines (note: in most cases those lines do not directly connect stations between each other, they can be very short up to 50 meters). My goal is to be able to find the train's route between 2 RailwayStations (in other words the shortest route) that must consist of chained RailwayLines from my database, that would represent train's route, basically MultiLineString of concatenated MultiLineStrings from my database. ChatGPT suggested "networkx" package, not really sure if it is the suitable approach, as I have geo-data. Attaching 2 examples of RailwayLine's model MultiLineString - as I said they can be very short, as well as that long so one can be directly connecting 2 stations (very rarely). -
Syntax Django Website Error in URL name defining
I'm building a Django website and have a Syntax Error in a weird place. In urlpatterns, defining a name to my url. I've tried this from django.urls import path, include from . import views urlpatterns = [ ("", views.home, name="home") ] And get this return File "C:\VsCodeProjects\my_project\home\urls.py", line 5 ("", views.home, name='home') ^^^^^^^^^^^ SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? -
No Watchlist matches the given query
Trying to add an item to my watchlist returns an suddenly started returning an error. Here is what my code looks like. models.py class Listing(models.Model): product_name = models.CharField(max_length=64, verbose_name="product_name") product_description = models.TextField(max_length=200, verbose_name="product description") product_image = models.ImageField(upload_to="images/", verbose_name="image", blank=True) is_active = models.BooleanField(blank=False, default=True) initial_price = models.DecimalField(decimal_places=2, max_digits=6, default=False) owner = models.ForeignKey(User, related_name="auction_owner", on_delete=models.CASCADE, default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category") def __str__(self): return self.product_name class Watchlist(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING) items = models.ManyToManyField(Listing, null=True, related_name="watchlist_item") views.py def add_to_watchlist(request, item_id): item = get_object_or_404(Listing, pk=item_id) user_watchlist = get_object_or_404(Watchlist, user=request.user) user_watchlist.items.add(item) return redirect("watchlist") urls.py path("add_to_watchlist/<int:item_id>", views.add_to_watchlist, name="add_to_watchlist"), template <div class="btn-groups"> {% if listing in watchlist_items %} <a href="{% url 'remove_from_watchlist' item_id=listing.id %}" class="fas fa-shopping-cart"><button type = "button" class = "add-cart-btn">remove from watchlist</button></a> {% else %} <a href="{% url 'add_to_watchlist' item_id=listing.id %}" class="fas fa-shopping-cart"><button type = "button" class = "add-cart-btn">add to watchlist</button></a> {% endif %} </div> -
Python django error occurs when trying to use daphne for realtime channels server and corsheaders middleware together
Im am trying to make an application supporting both http and websockets i used djangorestframework for making http api and also i used channels to incorporate websockets and, with this setup when i try to serve the http server with the development server i dont get any error or application break but when I use daphne to try and serve both http and websockets server the application breaks with an error that await expression cannot be used in httpresponse,and note that after debugging I came to realise this only occurs because of the corsheaders middleware removing the middleware handles the error but i still need the corsheaders for my react frontend to work with django without any errors -
Using Django, updating a model using REGEXP_REPLACE with multiple patterns to match
I've searched and found similar posts but not this specific. I am currently trying to update a models JSON field using REGEXP_REPLACE. I want to do it in one query so I want to match multiple patterns and replace them in one call. With my current setup, if I have just one pattern I want to match the code works fine eg. name1, but as soon as I try to match multiple using (name1|name2) it doesn't work. A small example: We have a JSON field information on a model Person. The information field is populated with the following: {"name": "first_name last_name", "description": "Test description", "address": "123 example street"} The code I currently am using to do REGEXP_REPLACE is: find_pattern = r'(name|description)": "(.*?)",' repl_pattern = r'\1": "filler",' Cast( Case( When( **{f'information__isnull': False}, then=Func( Cast(information, output_field=CharField()), Value(find_pattern), Value(repl_pattern), Value('g'), function='REGEXP_REPLACE', output_field=CharField(), ), ), default=None, ), output_field=JSONField(), ) However this does not work and I can't figure out why. I get the following error: django.db.utils.DataError: invalid input syntax for type json DETAIL: The input string ended unexpectedly. Any help/ideas would be greatly appreciated, thanks. -
Image does not load on my webpage in django template
i want to put an image in my webpage but it is not loading the settings.py is STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] and homepage.py is <html> <head><title>project</title> </head> <body> <div class="top"> {% load static %} <img src="{% static 'project1.jpg' %}"> <h1> FLIGHT</h1> </div> </body> </html> the virtual env is sem1 final and app is project and folder named static is in project which contains project1.jpeg i tried the django documentations but it did not work. -
How can I serialize multiple unrelated tables to get combined JSON output via django rest framework?
I am working on an order management. Here's the scenario: User can create multiple types of orders and these order types are unrelated, but user can view all types of order. I have created an individual table for each of order type in models.py class OrderType1(models.Model): create_time = models.DateTimeField(auto_now_add=True, verbose_name="create_time") ordertype1_info = models.CharField(max_length=32, verbose_name="Exclusive info for OrderType1") class OrderType2(models.Model): create_time = models.DateTimeField(auto_now_add=True, verbose_name="create_time") ordertype2_info = models.CharField(max_length=32, verbose_name="Exclusive info for OrderType2") class OrderType3(models.Model): create_time = models.DateTimeField(auto_now_add=True, verbose_name="create_time") ordertype3_info = models.CharField(max_length=32, verbose_name="Exclusive info for OrderType3") In serializers.py, I have created serializers accordingly class OrderType1Serializer(serializers.ModelSerializer): class Meta: model = OrderType1 fields="__all__" class OrderType2Serializer(serializers.ModelSerializer): class Meta: model = OrderType2 fields="__all__" class OrderType3Serializer(serializers.ModelSerializer): class Meta: model = OrderType3 fields="__all__" Then here's the key problem: I want to create a serializer of order to return all orders of mutilple types like class OrderSerializer(serializers.ModelSerializer): class Meta: model = [OrderType1, OrderType2, OrderType3] fields = "common info of all types of order" If the serializer accepts GET request, I want to return JSON output like this: { "OrderType1":[ { "id": 1, "create_time": "2018-01-01 12:00:00", "ordertype1_info": "Exclusive info for OrderType1" }, { "id": 2, "create_time": "2019-12-01 12:00:00", "ordertype1_info": "Exclusive info for OrderType1" } ], "OrderType2":[ { "id": 1, "create_time": "2020-01-01 … -
The message tag is being sent to html document but it's not visible
index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="stylesheet" href="{% static "css/signup.css" %}" type="text/css"/> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/boxicons@latest/css/boxicons.min.css" /> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} <div id="container" class="container"> <!-- FORM SECTION --> <div class="row"> <!-- SIGN UP --> <div class="col align-items-center flex-col sign-up"> <div class="form-wrapper align-items-center"> <form class="form sign-up" id="signup-form"> {% csrf_token %} <input type="hidden" name="form_type" value="signup"> <div class="input-group"> <i class="bx bx-user"></i> <select name="role" class="form-control" required> {% for value, label in form.role.field.choices %} <option value="{{ value }}" {% if value == '' %}disabled="disabled" selected="selected"{% endif %}>{{ label }}</option> {% endfor %} </select> </div> <div class="input-group"> <i class="bx bxs-user"></i> {{ form.username }} </div> <div class="input-group"> <i class="bx bx-mail-send"></i> {{ form.email }} </div> <div class="input-group"> <i class="bx bxs-lock-alt"></i> {{ form.password }} </div> <div class="input-group"> <i class="bx bxs-lock-alt"></i> {{ form.confirm_password }} </div> <button type="submit">Sign up</button> <p> <span> Already have an account? </span> <b onclick="toggle()" class="pointer"> Sign in here </b> </p> </form> </div> </div> <!-- END SIGN UP --> <!-- SIGN IN --> <div class="col … -
Problem loading JS files in django project
I am currently working on a project which uses templet inheritance. and from other tamplet when i am trying to load two different javascript files having 2 windows.onload function it load only one which is on the top. i am attaching a image which show both the directory structure and code image with code and dir structure I am expecting that my all windows.onload fun run from diff JS files at once when document is loaded.