Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django LDAP authentication CONNECT_ERROR
I've been trying to connect my app with LDAP server and have been struggling for around a week. These are my settings.py configs: AUTH_LDAP_SERVER_URI = 'ldap://10.xx.xx.1:389' AUTH_LDAP_BIND_DN = 'cn=djangouser,ou=django,ou=groups,dc=xx,dc=xx' AUTH_LDAP_BIND_PASSWORD = 'xx' AUTH_LDAP_USER_SEARCH = LDAPSearch( "dc=xx,dc=xx", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" ) AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'dc=xx,dc=xx', ldap.SCOPE_SUBTREE, '(objectClass=groupOfNames)' ) AUTH_LDAP_GROUP_TYPE = PosixGroupType(name_attr="cn") AUTH_LDAP_MIRROR_GROUPS = True AUTH_LDAP_USER_ATTR_MAP = { 'first_name': 'givenName', 'last_name': 'sn', 'email': 'mail', 'username': 'sAMAccountName', 'password': 'userPassword', } AUTH_LDAP_PROFILE_ATTR_MAP = { 'home_directory': 'homeDirectory' } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_TIMEOUT = 3600 AUTH_LDAP_START_TLS = True AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) import logging logger = logging.getLogger('django_auth_ldap') logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.DEBUG) Worth to mention i've tried: AUTH_LDAP_USER_DN_TEMPLATE = "sAMAccountName=%(user)s,dc=xx,dc=xx" And I've also tried mentioning the OU like: AUTH_LDAP_USER_SEARCH = LDAPSearch( "ou=store,dc=redesejus,dc=local", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)" ) AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'ou=store,dc=redesejus,dc=local', ldap.SCOPE_SUBTREE, '(objectClass=groupOfNames)' ) In all occasions I get the error below when trying to connect through django's admin Panel: Caught LDAPError while authenticating xx: CONNECT_ERROR({'result': -11, 'desc': 'Connect error', 'ctrls': [], 'info': '(unknown error code)'}) "POST /admin/login/?next=/admin/ HTTP/1.1" My AD is Windows server and this is the Structure: GROUPS -> DJANGO -> DJANGOUSER STORE -> GVIX -> USERS NORTH -> USERS SOUTH -> USERS Also worth mentioning I've tested the binding and the connection and everything … -
How to put apache superset as an application in a django project
How to put apache superset as an application in a django project I tried to install the tool using docker, but I want to use the superset tool with the django project so that it becomes an application among the applications in the django project.. -
Initializing tables with fixtures in Django
I have some tables that contain static data. So I want to be able to initialize them. I created a fixture to do this, but it seems that if I run the fixture more than once, it tries to insert the same data. Is there a way I can clear the table first? Similar to the flask drop_all, command, is there a way to drop and re-create all the tables from scratch? Or at least delete all the records. Also, how can I initialize the join table in a many-to-many relationship? -
Show/Hide the menu on another page while clicking radio button on another html page. I want to do this in Django framework
<ul class="navigation" role="navigation"> <li><a href="#"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li> <li><a href="{% url 'asset_list' %}"><i class="fas fa-box"></i> Assets</a></li> <li><a href="#"><i class="fas fa-chart-bar"></i> Reports</a></li> </ul> In the above html code i want to hide asset_list menu. <thead> <tr> <th></th> <th>Privilege Update</th> <th>Report Download</th> <th>Assign Asset</th> <th>Asset History</th> <th>View</th> <th>Edit</th> <th>Delete</th> <th>Add</th> </tr> </thead> <tbody> <tr> <td>Assets</td> <td> </td> <td> </td> <td> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </td> hide the asset menu when clicking a radio button in another page . Here both dashboard and switch are in two separate html pages.hide the asset menu when clicking a radio button in another page. -
How to express the reverse of a Many-to-One in Django
I realized that Django has Many-to-One and not One-to-Many, but how to you express the opposite relationship? I have a table which has 2 foreign keys to another table. The table Validation_Run has 2 foreign keys to Calibration_Run Django complains that that the reverse relationship has a conflict calibration.ValidationRun.calibration_run_pk: (fields.E304) Reverse accessor 'CalibrationRun.validationrun_set' for 'calibration.ValidationRun.calibration_run_pk' clashes with reverse accessor for 'calibration.ValidationRun.calibration_run_pk_tune_parameters'. HINT: Add or change a related_name argument to the definition for 'calibration.ValidationRun.calibration_run_pk' or 'calibration.ValidationRun.calibration_run_pk_tune_parameters'. How do I define the reverse relationship (from Calibration_Run to Validation_Run), so there is no conflict? -
How to pass the selected value of select2 element as parameter in htmx?
I want to do GET request with query parameter. However, the query parameter need to be taken from select2 elements. How do I pass the selected value of select2 to htmx? Below is the simplified overview of my code. <select id="filter">...</select> <select id="filter2">...</select> ... <button hx-get="{% url 'filter-data'}" hx-trigger="click" hx-include="#filter, #filter2" hx-target="targetDiv" >Filter</button> <script> $(document).ready(function () { $('#filter').select2() $('#filter2').select2() } </script> I've tried to search for similar problem but none were found. Any pointer is appreciated. -
Django subquery with static VALUES expression
Is it possible using the Django ORM to write a subquery which SELECTs from a set of fixed values? SELECT id, name, ( SELECT new_ages.age FROM (VALUES ('homer', 35), ('marge', 34)) AS new_ages(name, age) WHERE new_ages.name = ages.name ) AS new_age FROM ages ; The output from such a query might be something like: person_id name age 1 homer 35 42 marge 34 99 bart null I know that the Django code would look something like this: from django.db.models import OuterRef, Subquery from my_app.models import Person Person.objects.annotate(age=Subquery(...(name=OuterRef("name"))) But what goes in the ...? -
How to connect a dockerized django application to a non dockerized postgres database?
I have a dockerized django application and It works fine to connect it to a dockerized postgres database. I would like to modify the settings.py to connect to a local database in my machine or in the network but I just do not know how to map it. shall I use a network. there is not documentation for this. In fact the policy of my company is not to dockerize databases, but we are encouraged to dockerize applications. please help. I used the following dockerfile. # Start with the official Python image FROM python:3.11 # Set work directory WORKDIR /home/app # Preventing python from writing # pyc to docker container ENV PYTHONDONTWRITEBYTECODE 1 # Flushing out python buffer ENV PYTHONUNBUFFERED 1 # Install dependencies RUN pip install --upgrade pip COPY requirements.txt . #RUN ..\bin\activate. RUN pip install gunicorn RUN pip install --no-cache-dir -r requirements.txt # Copy project files COPY . . # Expose the localhost port on docker image on the port below. This is not used for mapping it but to expose it for comunication. EXPOSE 8000 # Run the Django server . we will run django on port 8000 CMD ["python", "manage.py", "runserver", "127.0.0.1:8000"] ###############settings.py######################## DATABASES = { … -
Django - Uploaded images are not found in production
I have a problem uploading images in production in my Django project. In development it works as expected, but in production, I get 404 images not found. Folder Structure website/ | |- core/ | |- settings.py | |- urls.py | ... | |- management/ | |- models.py | ... | |- static/ | |- images/ | |- uploads/ | |- sketch/ | ... | ... | |- manage.py |- media/ | |- uploads/ | |- sketch/ | ... settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [ BASE_DIR / 'static', ] MEDIA_ROOT = BASE_DIR / 'media' STATIC_ROOT = BASE_DIR / 'staticfiles' models.py class OrderSketch(models.Model): img = models.ImageField(upload_to='uploads/sketch/') def __str__(self): return f'Sketch - {self.order.id}' index.html <div class="sketch-gallery"> {% for sketch in order.ordersketch_set.all %} <img class="gallery-image {% if forloop.first %}active{% endif %}" src="{{ sketch.img.url }}" alt="Order Sketch {{ forloop.counter }}"> {% endfor %} </div> urls.py from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('base.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Note: my website is hosted in Microsoft Azure -
How do we separate django project into multiple docker containers
I have a django project right now that allows users to login and register an account. Sort of like a blog. All the views are separated and have their own static html file. The project works running locally and all. Users data is currently running with the default sqlite3 database currently i am able to put the whole project into a single docker container and it works when I run it. I use commands: docker compose up --build I am trying to separate my docker project into multiple docker containers. I want separate containers for the frontend and backend. a lot of tutorials online show how to have multiple containers using only postgressql, but I couldn't find much on sqlite3(django default database). I want to be able to do this with a sqlite3. Is this a way to do this. I have a requirements file, .dockerignore, Dockerfile, and a docker-compose.yml file. Any help would be appreciated. docker-compose.yml: eversion: "3" services: django: image: django-docker:0.0.1 build: . ports: - "8000:8000"``` Dockerfile: FROM python:3.12.3 ENV PYTHONUNBUFFER=1 WORKDIR /code COPY requirements.txt . RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD ["python", "manage.py","runserver"] -
Prefill modelform based on url
I'm struggling around Django form. I'm not really comfortable with this part of the framework. Here is the case. I have a ModelForm containing a OneToOneField. I would like to prepopulated the ModelChoice Field with the object referenced in the URL. Ex: catalogue/location/add/7 to add a location to the product with pk=7 NB: if the PK is not included, the form is just not prefilled models.py class Product(models.Model): pass class ProductLocation(geo_models.Model): product = geo_models.OneToOneField(Product, verbose_name=_('Product'), on_delete=geo_models.CASCADE, null=True,) geo_point = geo_models.PointField(verbose_name=_('Location'), blank=True) address = geo_models.CharField(verbose_name=_('Address'), max_length=255) urls.py urls += [ re_path(r"^location/add/(?P<product_pk>\d+)/$", self.add_update_location.as_view(), name='catalogue-product-location-add'), # Prepopulate product ModelChoiceField path("location/add", self.add_update_location.as_view(), name='catalogue-location-create' # Empty product ModelChoiceField ), path("location/<int:pk>", self.add_update_location.as_view(), name='catalogue-location-update') # Edit an existing Location ] views.py class LocationCreateUpdateView(generic.UpdateView): form_class = ProductLocationForm creating = True product = None def get_object(self, queryset=None): """ Extend the role of get_object to retrieve the product specified in the url """ self.creating = "pk" not in self.kwargs if self.creating: if self.kwargs.get("product_pk"): self.product = get_object_or_404(Product, pk=self.kwargs["product_pk"]) return None else: return super().get_object(queryset) # Try this way def get_form_kwargs(self): kwargs = super().get_form_kwargs() if self.product and not self.request.POST.get('product'): kwargs["product"] = self.product return kwargs # Or this way def get_initial(self): initial = super().get_initial() if self.product: initial["product"] = self.product return initial forms.py class ProductLocationForm(forms.ModelForm): … -
Celery Task Not Executing for Scheduled Reminder Emails in Django Project
I'm working on a Django project where I need to send confirmation emails upon registering for an event. The immediate confirmation emails are being sent correctly, but the scheduled reminder emails which I am using Celery for are not working. Below is my setup and the relevant parts of my project. event_management/celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'event_management.settings') app = Celery('event_management') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') event_management/init.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) Task Definition: emails/tasks.py import logging from celery import shared_task from django.core.mail import send_mail from django.template.loader import render_to_string from main.models import ReminderEmailNotification logger = logging.getLogger(__name__) @shared_task def send_reminder_email(email_notification_id, recipient_email): try: logger.info(f"Task started: send_reminder_email for email_notification_id {email_notification_id} to {recipient_email}") email_notification = ReminderEmailNotification.objects.get(id=email_notification_id) masthead_url = email_notification.masthead.url if email_notification.masthead else None print(f'recipient_email: {recipient_email}') context = { 'masthead_url': masthead_url, 'email_subject': email_notification.subject, 'email_message': email_notification.message, 'email_footer': email_notification.footer, } logger.info(f"Email context prepared: {context}") html_message = render_to_string('emails/email_template.html', context) logger.info(f"HTML Message: {html_message}") send_mail( email_notification.subject, '', 'example@example.com', [recipient_email], fail_silently=False, html_message=html_message ) logger.info(f"Email sent to {recipient_email}") except Exception as e: logger.error(f"Error in send_reminder_email: {str(e)}", exc_info=True) Settings: event_management/settings.py # Celery settings CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE … -
Custom class via {% element %} template django allauth
I'm trying to use the following scheme below: example of my template elements/h1.html {% comment %} djlint:off {% endcomment %} {% load allauth %} <h1> {% default slot %}{% endslot %} </h1> It is possible to declare the h1 in another template, via {% element h1 %} {% trans "Sign In" %} {% endelement %} for example, do I pass the name of a class? This way I can customize forms and other elements via .css. <h1 class="login-title"> Sign-in </h1> -
CesiumJS Container shutting down on Windows
I'm building an application, that consists of three different docker containers. The first is a CesiumJS (frontend container), the second a Django App, the third a PostgreSQL (3DCityDB, citydb container) database. The idea is to load data from Cesium in a standardized manner. The apps built just fine, but as soon as I open the page in a local setting on Windows I get the following error. The same network builds just fine on PopOS. And the application is running as requested. Why is the application not running on Windows? I'm using Windows 11 Pro and docker verson 26.1.4 frontend | /usr/src/app/node_modules/finalhandler/index.js:279 frontend | res.statusMessage = statuses.message[status] frontend | ^ frontend exited with code 1 frontend | frontend | TypeError: Cannot read properties of undefined (reading '404') frontend | at Array.write (/usr/src/app/node_modules/finalhandler/index.js:279:41) frontend | at listener (/usr/src/app/node_modules/finalhandler/node_modules/on-finished/index.js:169:15) frontend | at onFinish (/usr/src/app/node_modules/finalhandler/node_modules/on-finished/index.js:100:5) frontend | at callback (/usr/src/app/node_modules/ee-first/index.js:55:10) frontend | at IncomingMessage.onevent (/usr/src/app/node_modules/ee-first/index.js:93:5) frontend | at IncomingMessage.emit (node:events:519:28) frontend | at endReadableNT (node:internal/streams/readable:1696:12) frontend | at process.processTicksAndRejections (node:internal/process/task_queues:82:21) frontend | at process.processTicksAndRejections (node:internal/process/task_queues:82:21) frontend | frontend | Node.js v21.7.0 Full docker log: 2024-07-01 13:43:52 citydb | 2024-07-01 13:43:52 citydb | PostgreSQL Database directory appears to contain a database; Skipping initialization 2024-07-01 … -
Gunicorn cant find working directory on a remote Ubuntu machine (Django+nginx+gunicorn)
I have django application deployed on ubuntu machine, but it doesn't work because of error in gunicorn.service (it can't find work dir I wrote). My working directory is in /home/ubunut/project. gunicorn.service: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/ubuntu/project ExecStart=/home/ubuntu/project/env/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock project.wsgi:application [Install] WantedBy=multi-user.target I went into nginx logs: 2024/07/01 11:04:08 [error] 1906#1906: *23 connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: myipaddress, server: ipaddress, request: "GET /en/ HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/en/", host: "ipaddress" So i typed the sudo journalctl -u gunicorn.service -f to see logs in real time: Jul 01 11:29:17 landingpage (gunicorn)[2472]: gunicorn.service: Changing to the requested working directory failed: No such file or directory Jul 01 11:29:17 landingpage systemd[1]: gunicorn.service: Main process exited, code=exited, status=200/CHDIR Jul 01 11:29:17 landingpage systemd[1]: gunicorn.service: Failed with result 'exit-code'. Jul 01 11:29:17 landingpage systemd[1]: gunicorn.service: Start request repeated too quickly. Jul 01 11:29:17 landingpage systemd[1]: gunicorn.service: Failed with result 'exit-code'. Jul 01 11:29:17 landingpage systemd[1]: Failed to start gunicorn.service - gunicorn daemon. I've tried to go to my project root and copy path with pwd command, checked all the permissions. Still doesn't work. How do i fix gunicorn? -
User Logout on Django without logging into admin
I have recently deployed a REST API for a user authentication and authorization system using Django and Django REST Framework. The system should support user registration, authentication, token refresh, logout, and allow users to retrieve and update their personal information. I have done everything, but one thing remains: the user logout: `Endpoint: /api/logout/ Method: POST Body: {"refresh_token": "eb0464c2-ed6e-4346-a709-042c33946154"} Response: {"success": "User logged out."} curl -X POST http://localhost:8000/api/logout/ -d '{"refresh_token": "eb0464c2-ed6e-4346-a709-042c33946154"}' -H "Content-Type: application/json" I have written the code for logout, it's on github: https://github.com/AnakinSolo1983/RESTful-API-for-User-Authentication.git.` So, after I have deployed the app, I have made the following discovery: no matter which browser you're using, a user cannot access logout page unless he's registered on admin. The logout page shows the message "Authentication Credentials Not Provided" as shown in the caption below: enter image description here But if I login on to admin and try to logout a user that I have created, it works: enter image description here The code on GitHub is public, so be free to take a look at it. If there is somehow to fix this problem, and you know the solution, please let me know, thank you. I tried to add AllowAny to the permission classes, … -
ajax jquery request disappearing the data on the web page of the website created using django
this is my views.py file this is my ajax jquery code in html file in my properies.html file's web page there is some data about properties. I applied some filters which will work through ajax request. when clicking the objects on the page, the ajax request is working and the data on the page is getting disappeared. -
django-angular Access to XMLHttpRequest has been blocked by CORS policy
When trying to commit a POST request to the django server I get the following error: Obj:1 Access to XMLHttpRequest at 'http://localhost:8000/api/' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response. This is the code where I make the request: return this.http.post(url, data, {headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json', 'Access-Control-Allow-Headers': 'Content-Type', })} ) And this is my django settup for corsheaders: CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_HEADERS = ["access-control-allow-origin"] Any insight on the problem and how to improve the question will be thanked -
how to impelement notifications-hq ?: relation "notifications_notification" already exists
i try to implement notification-hq in django and when i send notify i got same error relation "notifications_notification" already exists sender=User.objects.using("default").get(username=request.user.username) receiver = User.objects.using("default").all() notify.send(sender=sender, recipient=receiver, verb='Message', description='message') and i got this traceback Traceback (most recent call last): File "/home/azizi/Documents/Ufmeeg_Projects/Gmao/Gmao-env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/azizi/Documents/Ufmeeg_Projects/Gmao/Gmao-env/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/azizi/Documents/Ufmeeg_Projects/Gmao/Gmao/Gmao/views.py", line 41, in home notify.send(sender=sender, recipient=receiver, verb='Message', description='message') . . . . return self.cursor.execute(sql, params) File "/home/azizi/Documents/Ufmeeg_Projects/Gmao/Gmao-env/lib/python3.9/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/azizi/Documents/Ufmeeg_Projects/Gmao/Gmao-env/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/azizi/Documents/Ufmeeg_Projects/Gmao/Gmao-env/lib/python3.9/site-packages/psycopg/cursor.py", line 737, in execute raise ex.with_traceback(None) django.db.utils.ProgrammingError: relation "notifications_notification" does not exist LINE 1: INSERT INTO "notifications_notification" ("level", "recipien... ^ [01/Jul/2024 09:14:04] "POST / HTTP/1.1" 500 184506 please help me -
best book to learn python
Seeking Recommendations for the Best Python Book with Latest Updates I'm eager to learn Python from scratch and stay up-to-date with the latest developments in the language. With the rapid evolution of Python, I want to ensure that I'm learning the most recent features, best practices, and industry standards. Could you please recommend a comprehensive and beginner-friendly book that covers Python 3.x (preferably the latest version, Python 3.10 or 3.11) and includes topics such as: Core Python concepts: variables, data types, control structures, functions, object-oriented programming, and more Data analysis and visualization: NumPy, Pandas, Matplotlib, and Seaborn Web development: Flask or Django, HTML, CSS, and JavaScript basics Machine learning and AI: scikit-learn, TensorFlow, and Keras Best practices and coding standards: code organization, debugging, and testing -
functionality in which same height of all the tr of the table based on the tallest tr of the table using html and css only
i am using playwright package of django for template, i want the same height of the tr should be applied for all the tr of table based on tallest tr. not expecting the tr should reposive its own content, all the tr should be same based on tallest tr Html - <tr> <td> <table class="line-item-table"> <thead> <tr> <th class="border-right border-bottom text-center sr-no"> Sr No. </th> <th class="border-right border-bottom text-center des-of-goods" > Description of Goods </th> <th class="border-right border-bottom text-center qty"> Qty </th> <th class="border-right border-bottom text-center unit"> Unit </th> <th class="border-right border-bottom text-center rate"> Rate </th> <th class="border-right border-bottom text-center discount"> Disc. % </th> <th class="border-right border-bottom discount-amt"> Discount Amount </th> <th class="border-bottom text-center tax-amt"> Taxable Amount </th> </tr> </thead> <!-- <tbody> {% for inv in invoiceData.dispatch_details %} <tr> <td class="border-right border-bottom sr-no"> <p class="font-lg">{{forloop.counter}}</p> </td> <td class="border-right border-bottom table-padding des-of-goods" > <p> <strong >{{inv.description|add_interval_in_string}} </strong> </p> <div class="lower-content"> <div class="flex-space-between italic"> <p>HSN : {{inv.hsn_code}}</p> <p>Width: -</p> <p>Buyer Ref: {{inv.buyer_ref_no|add_interval_in_string}}</p> </div> <div class="flex-space-between italic"> <p>Order no: {{inv.order_number|add_interval_in_string}}</p> <p>Challan/Packing no: {{inv.challan_slip_number|add_interval_in_string}}</p> </div> </div> </td> <td class="border-right border-bottom qty"> <p class="font-lg">{{inv.quantity}}</p> </td> <td class="border-right border-bottom unit"> <p class="font-lg">{{inv.unit_short_name}}</p> </td> <td class="border-right border-bottom rate"> <p class="font-lg">{{inv.rate_per_unit|add_interval_in_string:7}}</p> </td> <td class="border-right border-bottom discount"> <p class="font-lg">{{inv.discount_per}}</p> … -
Delete Tasks using Django framework
Im currently creating a todo list project using the Django web framework and i currently have an issue with deleting tasks of the webpage. My issue is that i don't know and can't find suitable code to perform the action of deleting a task from the webpage. This is what the webpage looks like: todo list. I believe my issue is contained in the views.py file: from django.shortcuts import render, redirect from django.contrib import messages as django_messages from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from .forms import RegisterForm, CreateTask from .models import Task # Import Task model def home(request): if request.method == 'POST': form = CreateTask(request.POST) if form.is_valid(): form.save() return redirect('home') else: form = CreateTask() tasks = Task.objects.all().order_by('-created_at')[:10] # Query Task model correctly context = { 'form': form, 'tasks': tasks, } return render(request, "home.html", context) def delete_task(request, id): task = Task.objects.get(id=id) task.delete() return redirect('home') @login_required def user_logout(request): auth_logout(request) django_messages.success(request, 'Logged out successfully') return redirect("introduction") # Redirect to a valid URL name def user_login(request): if request.method == "POST": username = request.POST.get("username") password = request.POST.get("password") user = authenticate(request, username=username, password=password) if user is not None: auth_login(request, user) django_messages.success(request, 'Login successful') return … -
Integrity Error raised because of constraint cannot override In Django Admin Panel
I have 4 classes like below: from django.db import models class A(models.Model): title = models.CharField(max_length=100) class B(models.Model): title_b = models.CharField(max_length=100) a = models.ForeignKey(A, on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint(fields=['title_b'], name='unique_title_b') ] class C(models.Model): title_c = models.CharField(max_length=100) a = models.ForeignKey(A, on_delete=models.CASCADE) class D(models.Model): title_d = models.CharField(max_length=100) a = models.ForeignKey(A, on_delete=models.CASCADE) All related classes are used as Inline model which described below: from django.contrib import admin class BInline(admin.TabularInline): model = B class CInline(admin.TabularInline): model = C class DInline(admin.TabularInline): model = D And Model Admin of class A is defined as class AAdmin(admin.ModelAdmin): inlines = [BInline, CInline, DInline] As you can see class B has a constraint on title uniqueness. If I enter duplicate data for class B in admin panel, an Integrity Error is raised and error page with title IntegrityError at /app/A/81ac3366-4cdb-4cbb-a861-340ff188c760/change/ duplicate key value violates unique constraint "unique_title_b" DETAIL: Key (title)=(TestDuplicate) already exists. is shown. In order to show user a friendly message rather than this error page, I override save_related method in class AAdmin like below: def save_related(self, request, form, formsets, change): try: with transaction.atomic(): super().save_related(request, form, formsets, change) except IntegrityError as e: self.message_user(request, 'A related model constraint was violated: {}'.format(e), level=messages.ERROR) I expect that after overriding save_related … -
'EnrollHash' object is not subscriptable : Query on AWS Django
This is my part of the code: @require_http_methods(["POST"]) @csrf_exempt @validate_api_request def processCommand(request): jsonResponse = dict() jsonResponse["status_code"] = 200 jsonResponse["message"] = "Command Sent Successfully" jsonResponse["data"] = dict() if 'childhash' in request.POST and request.POST['childhash'] \ and 'command' in request.POST and request.POST['command']: usrcommand = request.POST['command'].lower() childhash = request.POST['childhash'] enrollhash = EnrollHash.objects.filter(hash=childhash).filter( status='enrolled').first() # apply simple and condition if not enrollhash: jsonResponse["status_code"] = 404 jsonResponse["message"] = "Invalid Child Hash" try: failedCommand = FailedCommand(childHash=childhash, status_code=404, commandData=jsonResponse) failedCommand.save() except IntegrityError: pass requests.post("http://mesh.stg.familytime.io//mdm/checkout", data={"child_mdm_hash": childhash}) return JResponse(jsonResponse) try: child = Child.objects.get(enrollHashId=enrollhash.id) except Child.DoesNotExist: child = None except Child.MultipleObjectsReturned: child = Child.objects.filter(enrollHashId=enrollhash.id).first() if usrcommand.lower() == 'applyrestrictions': if 'data' not in request.POST or not request.POST['data']: jsonResponse["status_code"] = 400 jsonResponse["message"] = "This command requires 'data' variable with json object" try: failedCommand = FailedCommand(childHash=childhash, status_code=400, commandData=jsonResponse) failedCommand.save() except IntegrityError: pass return JResponse(jsonResponse) try: resdict = json.loads(request.POST['data']) except Exception: jsonResponse["status_code"] = 400 jsonResponse["message"] = "Invalid json object for current command" try: failedCommand = FailedCommand(childHash=childhash, status_code=400, commandData=jsonResponse) failedCommand.save() except IntegrityError: pass return JResponse(jsonResponse) allowedRestrictions = Restrictions.restrictionsMapping() if not all(item in allowedRestrictions.keys() for item in resdict.keys()): jsonResponse["status_code"] = 400 jsonResponse["message"] = "Invalid keys in json object" try: failedCommand = FailedCommand(childHash=childhash, status_code=400, commandData=jsonResponse) failedCommand.save() except IntegrityError: pass return JResponse(jsonResponse) try: currentRestrictionsObj = Restrictions.objects.get(childId=child) except Restrictions.DoesNotExist: … -
How to prevent Gmail from altering image URLs in email HTML?
I'm working on an event management portal using Django, and I send a confirmation email upon user registration. The email includes a masthead image. However, when the email is received in Gmail, the URL for the image is being altered, causing rendering issues. Here's the relevant part of my code: def view_registration_form(request, event_id, event_name): event = get_object_or_404(Event, id=event_id, name=event_name) form_template = get_object_or_404(FormTemplate, event=event) view_only = 'view' in request.path if request.method == 'POST' and not view_only: response_data = {field.label: request.POST.get(f'field-{field.id}', '') for field in form_template.fields.all()} email = next((value for key, value in response_data.items() if '@' in value), None) # Save the form response print(email) FormResponse.objects.create(form=form_template, email=email, response_data=response_data) # Send confirmation email using the event's email configuration email_config = EmailNotification.objects.filter(event=event, email_type='confirmation').first() if email_config and email: ngrok_url = 'https://######.ngrok-free.app' # Replace with your ngrok URL masthead_url = f"{ngrok_url}{email_config.masthead.url}" html_message = f""" <html> <head> <style> .email-masthead img {{ width: 100%; height: auto; }} .email-footer {{ margin-top: 20px; font-size: 0.9em; color: #555; }} </style> </head> <body> <div class="email-masthead"> <img src="{masthead_url}" alt="Email Masthead"> </div> <div class="email-body"> {email_config.message} </div> <div class="email-footer"> {email_config.footer} </div> </body> </html> """ print(html_message) send_mail( email_config.subject, email_config.message, 'from@example.com', [email], fail_silently=False, html_message=html_message ) return JsonResponse({'status': 'success', 'message': 'Thank you for registering!'}) fields = [{ 'id': …