Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
gunicorn.service: Failed at step CHDIR spawning */fresh_env/bin/gunicorn: No such file or directory
gunicorn.service cannot open WorkingDirectory and the gunicorn executable. I think it's about permissions but I don't know how I can solve it. ** sudo systemctl status gunicorn:`** `Apr 12 23:57:08 2818479-qd78506.twc1.net systemd[1]: gunicorn.service: Main process exited, code=exited, status=200/CHDIR` `Apr 12 23:57:08 2818479-qd78506.twc1.net systemd[1]: gunicorn.service: Failed with result 'exit-code'.` `Apr 12 23:57:53 2818479-qd78506.twc1.net systemd[78132]: gunicorn.service: Changing to the requested working directory failed: No such file or directory` `Apr 12 23:57:53 2818479-qd78506.twc1.net systemd[78132]: gunicorn.service: Failed at step CHDIR spawning /var/www/web_app/fresh_env/bin/gunicorn: No such file or dir>` `Apr 12 23:57:53 2818479-qd78506.twc1.net systemd[1]: Started gunicorn.service.` ** /etc/systemd/system/gunicorn.service: ** [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target` `[Service]` `User=root` `WorkingDirectory=/var/www/web_app/webapp ` `ExecStart=/var/www/web_app/webapp/fresh_env/bin/gunicorn --access-logfile = --workers 5 --bind unix:/run/gunicorn.sock webapp.wsgi:application` `[Install]` `WantedBy=multi-user.target` I've tried a lot of methods but no one could help me How to solve it? -
How to print out data into a certain html DOM element in Django templates?
I am printing out a list of deeds in template in a todo-list app. It works fine, but I would like block <p>No deeds here yet</p> to be outside of the ul list since it doesn't need to be in a list because it's a logically separate block. Also it gets a margin that I don't want there. How to place that paragraph element outside of the ul list? {% extends "todo_lists/base.html" %} {% block content %} <h2>Deeds of a {{list_title}} list</h2> <ul> {% for deed in deeds %} <li>{{deed.title}}</li> {% empty %} <p>No deeds here yet</p> {% endfor %} </ul> {% endblock content %} -
images from media file wont get displayed in React Native
I want to display the image on my React Native Post.js component but it just showing a white it consume the space of the style I made to the image settings.py STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / 'static' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' models.py from django.db import models from django.conf import settings class Item(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='items') name = models.CharField(max_length=100) description = models.TextField() category = models.CharField(max_length=50, choices=[ ('electronics', 'Electronics'), ('furniture', 'Furniture'), ('clothing', 'Clothing'), ('appliances', 'Appliances'), ('books', 'Books'), ('other', 'Other'), ]) condition = models.CharField(max_length=50, choices=[ ('new', 'New'), ('like_new', 'Like New'), ('used', 'Used'), ]) image = models.ImageField(upload_to='item_images', blank=True, null=True) available = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) reserved = models.BooleanField(default=False) reserved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='reserved_items', null=True, blank=True) Post.js import React, { useState, useEffect } from "react"; import { View, Text, Image, StyleSheet } from "react-native"; import fetchUserData from "../Reusable Component/FetchUserData"; import { COLORS } from "../constants"; import DynamicPostTime from "../Reusable Component/DynamicPostTime"; export default function Post({ listing }) { const [userData, setuserData] = useState({ firstName: "Loading...", lastName: "Loading...", email: "loading...", }); useEffect(() => { const loadUserData = async () => { setuserData(await fetchUserData()); }; loadUserData(); // console.log(listing.user); }, []); return ( <View style={styles.post}> <View style={styles.header}> <Image source={{ uri: userData.email … -
Can't use selenium with multithread in python - Digital Ocean server
i'm trying to scrap using a multiple threads to optimize. When I run the project on my pc it works nice, but when I deploy it on my Digital Ocean server it doesn't work throwing Timed out receiving message from renderer: 60.000. The server is a classic django server and the scraper runs in django views module after a POST request. My PC: macOS Sonoma 14.2.1 MacBook Air M2 8 gb RAM Digital Ocean Droplet: Ubuntu 23.10 x64 1 AMD vCPU 1 GB RAM 25 GB Disk + 10 GB Relevant code: from pathlib import Path from multiprocessing import Manager from multiprocessing.pool import ThreadPool from .scrapers.scraper_onu_odc import scrap_from_onu_odc from .scrapers.scraper_peps import scrap_from_senaclaft_peps from .scrapers.scraper_bcu import scrap_from_bcu_infractores_cheques from .scrapers.scraper_onu_scs import scrap_from_onu_scs from .scrapers.scraper_ofac import scrap_from_ofac from .scrapers.scraper_google import scrap_from_google from .scrapers.scraper_yahoo import scrap_from_yahoo from .scrapers.scraper_bing import scrap_from_bing from .scrapers.scraper_wikipedia import scrap_from_wikipedia from .scrapers.scraper_fincen import scrap_from_fincen BASE_DIR = Path(__file__).resolve().parent.parent.parent def scrapping_pool(scraper): scraper[0](*scraper[1]) def get_search_results(info, uuid): paths = { 'screenshots_path' : BASE_DIR / f'searcher/screenshots/{uuid}/', 'certificate_path' : str(BASE_DIR / 'searcher/ssl_certificates/bcu.pem') } manager = Manager() results = manager.dict() person_to_search = info['person_to_search_name'] + ' ' + info['person_to_search_surname'] params = (person_to_search, results, paths) scrapers = [ (scrap_from_onu_odc, params), (scrap_from_senaclaft_peps, params), (scrap_from_bcu_infractores_cheques, params), (scrap_from_onu_scs, params), (scrap_from_ofac, params), (scrap_from_fincen, … -
Django upload_to from ImageField not working
I have a model where i want to store a cover image for a publication, this is the code for the field in models.py: cover = models.ImageField(upload_to="covers/") I have in my settings.py: MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(BASE_DIR,'media') and in the root of the project I have media/covers/: folder structure the way I'm saving the model is the following: views.py title = request.POST["title"] description = request.POST["description"] initial_bid = int(request.POST["initial_bid"]) category = request.POST["category"] cover = request.POST["cover"] save_auction(title, description, initial_bid, category, cover, User(request.user.id)) def save_auction(title, description, initial_bid, category, cover, author): auction = Auction( title=title, description=description, initial_bid=initial_bid, category=category, status=0, cover=cover, author= author, winner = None ) auction.save() The model gets saved in the database but I don't get the image saved in the desired folder. I tried defining a function like this def user_cover_path(instance, filename): return 'user_{0}/covers/{1}'.format(instance.user.id, filename) cover = models.ImageField(upload_to=user_cover_path) but didn't work -
Django and Sanity
Can Sanity be used as a database backend to Django when used in a dynamic ERP system? How would this work in practive, API calls with JSON data transfer? Would this be a good solution, or is it better to use a relational database like MySql/ Postgres/ SQLite? I am planning on making an ERP system, and have started coding in Django, and would like to know more about the dastabase connection before moving on. -
Error when trying to install wagtail from source
11:36 I'm new to Wagtail and want to learn to contribute. But after many manipulations, when I do setup.py, there appears an error stack with at the end : string or bytes expected. Here is the full message : Traceback (most recent call last): File "/mnt/d_drive/var_docs_complements/open-source-contribs/wagtail/./mysetup.py", line 81, in <module> setup( File "/home/ainaf/.local/lib/python3.10/site-packages/setuptools/__init__.py", line 102, in setup _install_setup_requires(attrs) File "/home/ainaf/.local/lib/python3.10/site-packages/setuptools/__init__.py", line 70, in _install_setup_requires dist = MinimalDistribution(attrs) File "/home/ainaf/.local/lib/python3.10/site-packages/setuptools/__init__.py", line 52, in __init__ super().__init__(filtered) File "/home/ainaf/.local/lib/python3.10/site-packages/setuptools/dist.py", line 297, in __init__ for ep in metadata.entry_points(group='distutils.setup_keywords'): File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 1021, in entry_points return SelectableGroups.load(eps).select(**params) File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 459, in load ordered = sorted(eps, key=by_group) File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 1018, in <genexpr> eps = itertools.chain.from_iterable( File "/usr/lib/python3.10/importlib/metadata/_itertools.py", line 16, in unique_everseen k = key(element) File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 943, in _normalized_name or super()._normalized_name File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 622, in _normalized_name return Prepared.normalize(self.name) File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 871, in normalize return re.sub(r"[-_.]+", "-", name).lower().replace('-', '_') File "/usr/lib/python3.10/re.py", line 209, in sub return _compile(pattern, flags).sub(repl, string, count) TypeError: expected string or bytes-like object Thanks. I did some searchs. Also, I tried using github codespace and got very different results. I expect to be able to build and run it from source in my local computer. Thanks. -
Django queryset not filtering correctly in ListView with complex lookup
I'm trying to build a Django application where I have a ListView that displays a list of objects based on complex filtering criteria, but I'm encountering issues with the queryset not filtering correctly. Here's a simplified version of my code: models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) category = models.CharField(max_length=100) stock_quantity = models.IntegerField() class Sale(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity_sold = models.IntegerField() sale_date = models.CharField() views.py from django.views.generic import ListView from .models import Product, Sale class ProductListView(ListView): model = Product template_name = 'product_list.html' def get_queryset(self): queryset = super().get_queryset() return queryset.filter(category='Electronics', stock_quantity__gte=10, sale__sale_date__month=4) product_list.html {% extends 'base.html' %} {% block content %} <h1>Products</h1> <ul> {% for product in object_list %} <li>{{ product.name }}</li> {% endfor %} </ul> {% endblock %} I expect this ProductListView to display a list of products that belong to the 'Electronics' category, have a stock quantity of at least 10, and have had sales in the current month (April). However, when I visit the page, it displays an empty list, even though I know there are products that meet these criteria. I've tried debugging by printing the queryset in the get_queryset method, and it seems to be filtering correctly. I'm … -
create a Q variable in django orm
I want to actuate this query as one Q variable In [55]: Practitioner.objects.filter(query).filter(query10).distinct() Out[55]: <QuerySet [<Practitioner: Mohsenibod, Hadi>]> I used this methods but they do not correct: In [53]: Practitioner.objects.filter(query & query10).distinct() Out[53]: <QuerySet []> In [54]: Practitioner.objects.filter(query , query10).distinct() Out[54]: <QuerySet []> -
Django, htmx delete record and update
So I have a list in a partial Django template. <div class="col"> <div class="row pb-2" id="rowcolor"> <div class="col border-bottom"> pk:{{ color.pk }} / name:{{ color.description|title }} </div> <div class="col-auto"> <button hx-delete="{% url 'delete-color' pk=color.pk %}" hx-target="#rowcolor" hx-swap="outerHTML" class="btn btn-outline-secondary btn-sm float-end" type="button">Delete</button> </div> </div> </div> When deleting the pk149/name3: the pk147 / name1 disappears. When refreshing it is correct. pk:149 is gone. The view looks like this: @require_http_methods(["DELETE"]) def delete_color(request, pk): if request.htmx: Color.objects.get(pk=pk).delete() return HttpResponse("") I have been trying to read the htmx documentation. But I do not understand. Can anyone please point me in the right direction here? -
ModuleNotFoundError: No module named 'apps' - How to make Django find my app?
I'm a Django beginner, also a new SO user, and want to register my app in settings.py. Software version: Python 3.11.9 Django 4.2.11 I created my app (named: Portal) following this guide: startapp with manage.py to create app in another directory Here's the project tree: C:. ├───media │ ├───book-covers │ └───users ├───static │ └───admin │ ├───css │ ├───fonts │ └───js └───project ├───apps │ ├───auth │ ├───portal │ │ ├───media │ │ ├───migrations │ │ │ └───__pycache__ │ │ ├───static │ │ │ └───portal │ │ │ ├───css │ │ │ ├───icons │ │ │ ├───images │ │ │ └───js │ │ ├───templates │ │ │ └───catalog │ │ └───__pycache__ │ └───users ├───plugins │ └───tinymce ├───static └───__pycache__ However, when I register my Portal app, Django raised an error: ModuleNotFoundError: No module named 'apps' apps.py from django.apps import AppConfig class PortalConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'apps.portal' settings.py INSTALLED_APPS = [ '', 'apps.portal', '', ] I know this might be a duplicate question, but still I can't manage to solve this issue. What should I do to make Django find my app? Please be as specific as possible because I'm totally new. Thanks for your time. I've tried steps here: Proper way … -
Problem with getting model instances in specific order
I have a list of passport data of users. I need to get users queryset in the same sequence as their passport data ordered in the list. Here is the list with passport data: lst = ['AA1111111', 'AD2222222', 'AA3333333', 'AA4444444', 'АВ5555555'] I tried to do something like this: empty_queryset = Users.objects.none() for passport_number in lst: user = Users.objects.filter(passport_number__exact=passport_number) empty_queryset |= user I was expecting this: <QuerySet [<Users: AA1111111>, <Users: AD2222222>, <Users: AA3333333>, <Users: AA4444444>, <Users: АВ5555555>]> But it came in chaotic order: <QuerySet [<Users: АВ5555555>, <Users: AA1111111>, <Users: AD2222222>, <Users: AA3333333>, <Users: AA4444444>]> Then I tried this: Users.objects.filter(passport_number__in=[i for i in lst]) But still did not work -
Python Django OSError: [Errno 99] Address not available
I am creating an app with Django Rest Framework and struggling with a weird problem which occures when sending email with Djoser. When I try to reproduce this error on my host machine inside Docker container in production environment I do not have any errors, all email messages are sent succesfully, however when I try to do it on production server under Docker I get OsError, here is the full traceback: Traceback (most recent call last): File "/usr/local/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/contextlib.py", line 81, in inner return func(*args, **kwds) ^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc ^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/rest_framework/mixins.py", line 19, in create self.perform_create(serializer) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/djoser/views.py", line 140, in perform_create settings.EMAIL.activation(self.request, context).send(to) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/templated_mail/mail.py", line 78, in send super(BaseEmailMessage, self).send(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/core/mail/message.py", line 298, in … -
How do I effectively filter locations in my database without having to loop through it manually?
In my DRF project, I have a model structured like this class ServiceLocation(models.Model): ''' Represents a location where an internet service is offered ''' SERVICE_TYPES = [ ("wifi", 'wifi'), ("fibre", "fibre"), ("p2p/ptmp", "p2p/ptmp") ] id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, null=False, blank=False) description = models.TextField() # Location address = models.CharField(max_length=150, null=False, blank=False) latitude = models.DecimalField(max_digits=18, decimal_places=15) longitude = models.DecimalField(max_digits=18, decimal_places=15) # Service service = models.CharField( max_length=10, choices=SERVICE_TYPES, null=False, blank=False) speed = models.IntegerField() def __str__(self): return f"{self.service} by {self.operator}" and I'm trying to filter this instances of this model with their relative proximity to given coordinate. My view is structured like this class CloseServiceLocations(View): def get(self, request): lat = request.GET.get('lat', 6.748134) lng = request.GET.get('lng', 3.633301) distance = request.GET.get('distance', 10) # Default distance to 10 if not provided # if lat is None or lng is None: # # return JsonResponse({'error': 'Latitude and Longitude are required parameters.'}, status=400) try: lat = float(lat) lng = float(lng) distance = float(distance) except ValueError: return JsonResponse({'error': 'Invalid latitude, longitude, or distance provided.'}, status=400) # Create a Point object representing the provided latitude and longitude user_location = Point(lng, lat, srid=4326) # Calculate the distance in meters (Django's Distance function uses meters) distance_in_meters = distance * 1000 close_service_locations = … -
Filter deep nested related_set in Django
There are two models: class Subject(Model): categories = ManyToManyField(Category, related_name='subjects') class Category(Model): parent = ForeignKey('self', related_name='subcategories') This supposed to be translated into the following rest output: [ { ..., "categories": [ {"subcategories": [{}, {} ... {}]}, {"subcategories": [{}, {} ... {}]} ], }, { ..., "categories": [ {"subcategories": [{}, {} ... {}]}, {"subcategories": [{}, {} ... {}]} ], } ] The problem is to have set of subcategories for each category, subcategories that are in many to many relation with ancestor subject. So far I think that queryset should be something like: Subject.objects.prefetch_related( Prefetch( lookup="categories", queryset=Category.objects.filter(parent__isnull=True) .prefetch_related( Prefetch( lookup="subcategories", queryset=Subquery( Category.objects.filter( parent__pk=OuterRef("pk"), subjects__id__in=OuterRef(OuterRef("pk")), ) ) ) ) .distinct(), ), ) But this gives the error: AttributeError: 'Subquery' object has no attribute '_chain' What is wrong with the queryset. What would be the correct way of doing that? -
How to test external fetch API function with connectionerror exception Django
My code snippet fetches data from an external API. It works fine and I tested the results when I don't have any issues with the connection. However, I'm interested on testing my try except block that handles any connection problem during the function execution. I'm using python 'requests' library and I don't have any complain about it but I feel testing a connection issue will reassure my code does throw the exception. This is the closest StackOverflow answer for python only, I couldn't implement it in my code though. Also, I found another answer that suggested using Httpretty but I don't that's the approach to this question. Does anyone know how to simulate failures for external API data fetching? views.py def fetch_question(request): handler = APIHandler() match request.POST["difficulty"]: case "easy": url = ( "https://opentdb.com/api.php?amount=1&category=9&difficulty=easy&type=multiple&token=" + handler.token ) case "medium": url = ( "https://opentdb.com/api.php?amount=1&category=9&difficulty=medium&type=multiple&token=" + handler.token ) case "hard": url = ( "https://opentdb.com/api.php?amount=1&category=9&difficulty=hard&type=multiple&token=" + handler.token ) try: response = requests.get(url) except ConnectionError: # Want to test this exception response.raise_for_status() else: return render_question(request, response.json()) test_views.py from django.test import TestCase, Client client = Client() class QuestionTest(TestCase): def test_page_load(self): response = self.client.get("/log/question") self.assertEqual(response["content-type"], "text/html; charset=utf-8") self.assertTemplateUsed(response, "log/question.html") self.assertContains(response, "Choose your question level", status_code=200) def test_fetch_question(self): … -
How to have different settings in local settings.py and settings.py in a docker container
I finally sorted this issue by using the answer in the link below. I'm posting this here in the hope others might find this and click on the link below. I was stuck on this for a long time and couldn't get an answer anywhere. This link should be way more popular but I don't have the credits to give it an upvote. How to make different database settings for local development and using a docker I tried re-configuring my wsl-config hosts, multiple re-configurations of my docker-compose.yml. I tried 'host.docker.internal', extra-hosts, links -
type object 'my model' has no attribute 'CHOICES' after running 'migrate'
so here in my migration file i have this function : def populate_categories(apps, schema_editor): CategoryModel = apps.get_model('app_l3', 'CategoryModel') for name, desc in CategoryModel.CATEGORY_CHOICES: CategoryModel.objects.create(category_name=name, description=desc) this is for auto populating my database, and the model is this CATEGORY_CHOICES = ( ('hardware', 'Hardware'), ('software', 'Software'), ('network', 'Network'), ('printer', 'Printer'), ('phone', 'Phone'), ('laptop', 'Laptop'), ) category_name = models.CharField(max_length = 150,unique=True,primary_key=True,choices=CATEGORY_CHOICES) description = models.TextField() category_creation_date = models.DateTimeField(auto_now_add=True,null=True,blank=True) so after i tried to run py manage.py migrate i got this error : for name, desc in CategoryModel.CATEGORY_CHOICES: AttributeError: type object 'CategoryModel' has no attribute 'CATEGORY_CHOICES' so how i could fix it .. and is there other ways to auto populate with predefined choices -
VSCode on Linux freezes when opening existing folder, but works fine after Git cloning the same folder
On Linux when I try to open a folder in vscode the program crashes. If I git clone this folder after opening vscode, everything works fine (I can run the code and everything). But otherwise I get an error if the folder has already been cloned and I try to open it "Visual Studio Code" Not responding On Windows everything works without problems. The code is python-django code -
Django User not inheriting Group permissions
I have a TestCase that i'm testing permissions on. I don't understand how this test is failing where it's failing: # Make sure group has permission group_permissions = self.my_group.permissions.filter(codename="view_mymodel") self.assertEqual(len(group_permissions), 1) print("Group Permissions:") for permission in group_permissions: print(permission) # Make sure user is in group user_groups = self.user.groups.filter(name="My User Group") self.assertEqual(len(user_groups), 1) user_permissions = self.user.get_all_permissions() print("User Permissions:") for permission in user_permissions: print(permission) # Make sure user has permission self.assertTrue(self.user.has_perm("myapp.view_mymodel")) This is failing at the last assertion. I can see the permission is set for the group but when i call get_all_permissions(), nothing shows up. That makes no sense because get_all_permissions() is suppose to return all permissions on both the User and the group. -
In django crispy form, forms.ImageField value always is None
I have a form with an image field but its value is always None. I found this. it says that I should put enctype="multipart/form-data" as an attribute of the form tag in my HTML template but I am using crispy so I do not have access to the form tag directly. As here says there is no need to put this attribute for crispy forms and it sets whenever it needed. So what is the problem with my image field? -
Django and htmx messages with refresh dataTables after submit form
I am a beginner in the django programming language who please need some assistance. I have a data which after validation of my form displays a success message: "Operation completed successfully" from the return httpReponse but does not refresh the page. However, by adding this script in the form <form hx-post="{{ request.path }}" class="modal-content" hx-on="htmx:afterRequest:location.reload()"> tag, the dataTable is refreshed but success message is not displayed views.py def index(request): all_person = Personne.objects.all() context = {'all_person': all_person} return render(request, 'index.html', context) def add_personne(request): if request.method == "POST": form = PersonneForm(request.POST) if form.is_valid(): form.save() return HttpResponse(status=204, headers={'HX-Trigger': json.dumps({ "personList": None, "showMessage": "Opération effectuée avec succès", }) }) else: form = PersonneForm() return render(request, 'form_personne.html', {'form':form}) <---------------------------- Début index.html -------------------------------------------> index.html {% extends "base.html" %} {% block title %}Tableau-Dynamique{% endblock title %} {% block content %} <div class="col md-12"> <button type="button" class="btn btn-primary" hx-get="{% url 'add_personne' %}" hx-target="#dialog" style="width:300px;"> Add New </button> </div> <br> <h3 class="mt-3">Option de recherche</h3> <!--HTML table with student data--> <table id="tableID" class="display"> <thead> <tr> <th class="px-2 py-2 text-center">N°</th> <th class="px-2 py-2 text-center">Nom</th> <th class="px-2 py-2 text-center">Age</th> </tr> </thead> <tbody> {% for personne in all_person %} <tr> <td>{{ forloop.counter }}</td> <td>{{personne.nom}}</td> <td>{{personne.age}}</td> </tr> {% endfor %} </tbody> </table> {% endblock … -
ValueError at /accounts/signup/ Cannot query "echiye@gmail.com": Must be "User" instance
Am using django-allauth for aunthentication and below is my custom user models. The password are not safe to the database because it will report incorrect password but the user will be created along with other necceasiry informations on the database entered during registrations are correctly saved rightly. password created using the createsuperuser is stored correctly too. Kindly help me out with the ValueError at /accounts/signup/ Cannot query "echiye@gmail.com": Must be "User" instance. class MyUserManager(UserManager): """ Custom User Model manager. It overrides default User Model manager's create_user() and create_superuser, which requires username field. """ def _create_user(self, email, password, username, first_name, phone_number, country, last_name, is_staff, is_superuser, wallet_address=None, private_key=None, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, first_name=first_name, last_name=last_name, username=username, is_staff=is_staff, is_active=True, last_login=now, date_joined=now, phone_number=phone_number, country=country, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) ''' def create_superuser(self, email, password, **kwargs): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) return self._create_user(email, password, True, True, **kwargs) def create_superuser(self, email, password, **kwargs): user = self.model(email=email, is_staff=True, is_superuser=True, **kwargs) user.set_password(password) user.save(using=self._db) return user ''' def create_superuser(self, email, password, **kwargs): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) user = self._create_user(email, password, True, True, … -
Dark Mode doesn't sync properly?
I'm having an issue syncing the Django admin panel theme with the application's side of the theme...Whenever I switch to Light mode from Dark mode on the app side, it changes to Auto and it should rather switch to Dark mode and vice versa. The issue persists on the admin side as well for some reason. If I switch from Light mode to Dark mode whilst in the admin panel and refresh the application's side, it changes it to Light mode? It's quite odd. I tried troubleshooting it and what I could find was an error pointing at theme.js which is a file part of the admin panel. It seems the problems stems from this file... theme.js 'use strict'; { window.addEventListener('load', function(e) { function setTheme(mode) { if (mode !== "light" && mode !== "dark" && mode !== "auto") { console.error(`Got invalid theme mode: ${mode}. Resetting to auto.`); mode = "auto"; } document.documentElement.dataset.theme = mode; localStorage.setItem("theme", mode); } function cycleTheme() { const currentTheme = localStorage.getItem("theme") || "auto"; const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches; if (prefersDark) { // Auto (dark) -> Light -> Dark if (currentTheme === "auto") { setTheme("light"); } else if (currentTheme === "light") { setTheme("dark"); } else { setTheme("auto"); } … -
Django: how to pass javascript code from python to form field attributes?
I'm using django-bootstrap-daterangepicker plugin that allows to create the following Django form: from django import forms from bootstrap_daterangepicker import fields class DateRangeForm(forms.Form): date_range = fields.DateRangeField() Everything works as expected until I want to add some dynamic daterangepicker-specific options like predefined ranges, that should be evaluated on every page refresh: $('#demo').daterangepicker({ ranges: { 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], }, }) If I use: from datetime import datetime, timedelta from django import forms from bootstrap_daterangepicker import fields, widgets class DateRangeForm(forms.Form): date_range = fields.DateRangeField( widget = widgets.DateRangeWidget( picker_options = { 'ranges': { 'Last week': [ (datetime.now() - timedelta(days=7)).isoformat(), datetime.now().isoformat(), ], }, }, ), ) then dates are evaluated on server start and not re-evaluated at page refresh. Is there a way to tell Django to treat string as javascript code to pass it to rendered page as code, not as string? Or are there other ways to solve this problem?