Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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': … -
Choosing the Right Architecture for Django Application: Monolith vs. Microservices [closed]
Project Idea: All-in-One School Portal Hi there! I need to build project for a school system which idea is collecting different existing sites (different sizes and technologies). Here's what it will offer: Student Dashboard: Students can log in to view their personal information, subject details, exam scores, and class schedules (including location, teacher, and room). Assignments: Both teachers and students can access the assignment section. Teachers can upload assignments, while students can submit their answers. Teachers can also grade submissions and leave comments. Additional Features: The portal will include other functionalities like teacher ratings and exam applications. Choosing the Right Architecture (Microservice vs Monolith) 1. Microservice vs Monolith I'm deciding between two architecture options: Microservices and Monolith. I've never used microservices before, but I have some ideas on how to implement it. Can you help me choose the best approach? 2. Deep Dive into Microservices If microservices are the better choice, can you explain how it would work for user information? If the first one (Microservice), could you elaborate on that in detail? For instance, should the user information be stored solely in the user table in the database, and if so, how do other services need to access it … -
Django caching causing blank screen on Brave browser
I have a new Django website and have just implemented the filesystem cache (django.core.cache.backends.filebased.FileBasedCache). This seems to work fine when I use a chrome browser to view the site, but when I use the Brave browser, it initially shows the site on the first GET of a url, but upon subsequent refreshes it draws a blank (white) screen. I am new to Django and, after reading the docs I think the following setting are all I need to implement it. And I can see the cache files being created on the server. So I assume I don't need to add the various decorators in the views (just want it to cache all pages). What is also interesting, is that the response time isn't that much quicker (from 550ms > 450ms).. maybe because its a filesystem cache?? Here are my settings CACHES = { "default": { "BACKEND": "django.core.cache.backends.filebased.FileBasedCache", "LOCATION": "/var/tmp/django_cache", "TIMEOUT": 600, } } MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'strip_whitespace.middlewares.HtmlStripWhiteSpaceMiddleware.html_strip_whitespace', 'django.middleware.cache.FetchFromCacheMiddleware', ] -
Django django.contrib.messages add new constant messages.NOTICE
How can I add new constant to Django messages? I want to add a new constant messages.NOTICE in addition to the existing six constants. That I can use to display notices using Bootstrap CSS. # settings.py from django.contrib.messages import constants as messages MESSAGE_TAGS = { messages.DEBUG: 'alert-secondary', messages.INFO: 'alert-info', messages.SUCCESS: 'alert-success', messages.WARNING: 'alert-warning', messages.ERROR: 'alert-danger', messages.NOTICE: 'alert-primary', } -
How to run an exe file of a server through your website and get its Window on browser?
Is it possible to run an exe file on your server through your website to start to use it through your browser? If so, how? I saw some people run pc games in browsers. So I want to do something similar. For back end I use Django, but I can consider any other frameworks. The main question is what technology should I search for? -
Microservice vs Monolith architecture in Django
Project Idea: All-in-One School Portal Hi there! I need to build project for a school system which idea is collecting different existing sites (different sizes and technologies). Here's what it will offer: Student Dashboard: Students can log in to view their personal information, subject details, exam scores, and class schedules (including location, teacher, and room). Assignments: Both teachers and students can access the assignment section. Teachers can upload assignments, while students can submit their answers. Teachers can also grade submissions and leave comments. Additional Features: The portal will include other functionalities like teacher ratings and exam applications. Choosing the Right Architecture (Microservice vs Monolith) 1. Microservice vs Monolith I'm deciding between two architecture options: Microservices and Monolith. I've never used microservices before, but I have some ideas on how to implement it. Can you help me choose the best approach? Microservices: This breaks down the application into smaller, independent services (e.g., User Service, Schedule Service, Assignment Service). Each service has its own database and can be developed, deployed, and scaled independently. Monolith: This is a single, unified application where everything is bundled together. It's simpler to set up initially but can become cumbersome and slow as the application grows. 2. … -
Apps without migrations must not have relations to apps with migrations. Why?
There is a vague paragraph in django docs: Apps without migrations must not have relations (ForeignKey, ManyToManyField, etc.) to apps with migrations. Sometimes it may work, but it’s not supported. I have 5 years of experience and never encountered problems in these cases. In what case it's dangerous to have relation to "apps with migrations" ?