Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python function w/ same method as index doesn't work
views.py def index(request): print("passed through index method") return render(request, "title/index.html", {}) def q(request): print("passed through q method") return render(request, "title/index.html", {}) def testss(request): print("passed through testss method") return render(request, "title/index.html", {}) urls.py urlpatterns = [ path("", views.index, name="index"), path("test", views.q, name="q"), path("testss", views.testss, name="testss"), ] I am a beginner in python and I was coding different functions. But for some reason methods that aren't named after "index" returns "NONE". What I've done is to replace the methods with the same method as the original index function. I did this to check if maybe it was solely a method problem. As it turned out only the function "index" worked. So I juggled the function names and only functions with the name index worked. I've been on this for a while and I can't seem to figure out what's wrong with this yet. Your insight would immensely help! -
web socket not working on postman or websocket king
I have a backend project using Django and its for QMS, I want to make two real time notifications : 1-for the client if there is only a ticket ahead 2- is for all clients to see the number of tickets that are in counters here is the asgi file: import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from apps.ticket.routing import websocket_urlpatterns from django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "qms_api.settings") application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter(websocket_urlpatterns) ), } ) #and here is the consumers file: import json from channels.generic.websocket import AsyncWebsocketConsumer class TicketConsumer(AsyncWebsocketConsumer): async def connect(self): self.group_name = "global_notifications" # Join the global group await self.channel_layer.group_add(self.group_name, self.channel_name) await self.accept() async def disconnect(self, close_code): # Leave the global group await self.channel_layer.group_discard(self.group_name, self.channel_name) async def ticket_ahead_notification(self, event): # Send the ticket ahead notification to the WebSocket await self.send(text_data=json.dumps(event["data"])) class TicketInProgressConsumer(AsyncWebsocketConsumer): async def connect(self): self.group_name = "tickets_in_progress" # Join the group await self.channel_layer.group_add(self.group_name, self.channel_name) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.group_name, self.channel_name) async def send_ticket_update(self, event): await self.send(text_data=json.dumps(event["message"])) #routing file: from django.urls import re_path from apps.ticket.consumers import TicketConsumer,TicketInProgressConsumer websocket_urlpatterns = [ re_path(r"^tickets/ahead/$", TicketConsumer.as_asgi()), re_path(r"^tickets/in_progress/$", TicketInProgressConsumer.as_asgi()), ] #the settings : INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", … -
Generic Foreign Key on unsaved model in Django
I have stumbled into a bit of inconsistency with Foreign Keys and Generic Foreign Keys in Django. Suppose we have three models class Model_One(models.Model): name= models.CharField(max_length=255) class Model_with_FK(models.Model): name=models.CharField(max_length=255) one=models.ForeignKey(Model_One, on_delete=models.CASCADE) class Model_With_GFK(models.Model): name=models.CharField(max_length=255) content_type= models.ForeignKey( ContentType, on_delete=models.CASCADE, ) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") class Meta: indexes=[models.Index(fields=["content_type", "object_id"]), ] When we do one = Model_One() two = Model_Two(model_one=one) one.save() two.save() Everything works okay. Model one recieves an ID, and when model two is saved, that ID is used to reference model one. However, the same does not work with GFK one = Model_One() two = Model_With_GFK(content_object=one) one.save() two.save() When there is an attempt to save two, integrity error is raised that "object_id" column is null. When inspected with debugger, as soon as model one is saved, field "content_object"on the model two is turn from model "one" to None. This is quite unexpected, as with Foreign Key there is no such problem. Of course you can save model one before using it in GFK relation, but why is this necessary? With Foreign keys, i could instantiate all the models and then create them with bulk_create. With GFK in the picture, this no longer seems possible -
Login doesn't set sessionid at Cookies on Safari browser with onrender.com [Django]
I deployed Django as backend at [render.com][1], I set up csrf and session rules at settings.py like this. SECURE_HSTS_SECONDS = 31536000 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SESSION_ENGINE = "django.contrib.sessions.backends.db" SESSION_COOKIE_AGE = 1209600 # 2 weeks SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = "None" SESSION_COOKIE_HTTPONLY = True CSRF_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = "None" CSRF_TRUSTED_ORIGINS = [ "http://localhost:5173", config("LOCAL_SERVER"), config("FRONTEND_URL"), config("BACKEND_URL"), ] The server even replied with 200 status, but the user is not stored at cookies so the user is not actually logged in. I tried to log in at Brave browser and it worked. But the problem exists at Safari and mobile browsers. What could be the problem? This is the login method at Django. @csrf_protect @api_view(["POST"]) @permission_classes([AllowAny]) def login_view(request): username = request.data.get("username") password = request.data.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) csrf_token = get_token(request) if request.data.get("favorites") or request.data.get("cart"): request.user = user # Call sync function with the cookie data sync_user_data(request) response = JsonResponse({"message": "Login success"}, status=status.HTTP_200_OK) response.set_cookie( "sessionid", request.session.session_key, httponly=True, secure=True, samesite="None", domain=config("ALLOWED_HOST_BACKEND"), max_age=1209600, ) response.set_cookie("csrftoken", csrf_token, httponly=True) return response else: return JsonResponse( {"message": "Invalid credentials"}, status=status.HTTP_400_BAD_REQUEST ) ``` [1]: https://render.com -
Wagtail_Modeltranslation for MultiFieldPanel
i had problem related to translating fields inside MultiFieldPanel...when i tried to translate fields i can not show it on admin.But outside MultiFieldPanel it works fine like FieldPanel("body") and also i tried to understand the docs but not working also link:https://wagtail-modeltranslation.readthedocs.io/en/latest/advanced%20settings.html MultiFieldPanel( [ FieldPanel("header_title"), FieldPanel("header_subtitle"), FieldPanel("header_image"), FieldPanel("intro", classname="full"), FieldPanel("body"), FieldPanel("wide_content"), ], heading="Article", classname="collapsible collapsed", ), ] translations.py: class ProjectPageTR(TranslationOptions): fields = ( "hero_title", "hero_subtitle", "header_title", "header_subtitle", "intro", "body", "wide_content", ) -
How to have multiple submit buttons in one line even if they are different form submissions, using Python Django?
I'm making a sort of checklist/todo app in Python Django and have an update form where I can save updates, mark it as complete or incomplete or delete the item. The current code displays the save button on one line as it's in a form with other data to update the item. the complete and delete buttons are in a separate line. How do I update the code so that all the buttons appear in one line? and function? I've tried to use Chatgpt to get an answer and if I get all the buttons in one line, the functions/buttons or the mark as important stop working. {% extends 'BJJApp/base.html' %} {% block content %} <div class="row justify-content-center mt-5"> <div class="col-md-5"> <h2>New Item</h2> </div> </div> <div class="row justify-content-center mt-5"> <div class="col-md-5"> {% if error %} <div class="alert alert-danger" role="alert"> {{ error }} </div> {% endif %} <div class="container"> <!-- Main Form for saving item --> <form method="POST"> {% csrf_token %} <div class="form-group"> <label for="title">Title</label> <input type="text" name="title" class="form-control" id="title" value="{{ item.title }}" required> </div> <div class="form-group"> <label for="memo">Memo</label> <textarea name="memo" rows="5" class="form-control" id="memo">{{ item.memo }}</textarea> </div> <div class="form-group form-check"> <input type="checkbox" name="important" class="form-check-input" id="important" {% if item.important %}checked{% endif %}> … -
Django and Firebird
Has anybody a running system using Django and Firebird? If yes, could you provide information about the Python version, Django version, Firebird version, used Firebird driver and Firebird Django driver, libfbclient version and finally which additional moduls (e.g. six) you have installed? -
problem with django migration / django.db.utils.ProgrammingError: invalid dsn: invalid connection option "players"
i am facing a problem when trying to migrate my project to docker postgres db! Error is: File "D:\TeamsProject.venv\Lib\site-packages\psycopg2_init_.py", line 121, in connect dsn = _ext.make_dsn(dsn, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\TeamsProject.venv\Lib\site-packages\psycopg2\extensions.py", line 167, in make_dsn parse_dsn(dsn) django.db.utils.ProgrammingError: invalid dsn: invalid connection option "players" More context: I have an app named players with a model Player in it. DB configuration in settings.py was checked 100 times. Also tried manually to connect with DB through Docker commands, and it works fine. I cannot understand where this problem is coming from... Checked all the code for some typos, checked db settings, reinstalled decouple and psycopg2 and 100 more things. -
UniqueConstraints not running?
class DataStatus(DjangoChoices): draft = ChoiceItem("draft", _("Draft")) active = ChoiceItem("active", _("Active")) class BaseDataModel(models.Model): class Meta: abstract = True class DataModel(BaseDataModel, models.Model): """Model class for Purchase Request.""" class Meta: constraints = [ models.UniqueConstraint(fields=["user"], condition=Q(status="draft"), name="unique_draft_user"), ] user = models.ForeignKey( User, related_name="+", on_delete=models.CASCADE, blank=True, null=True, ) status = models.CharField( max_length=255, null=True, default=DataStatus.draft, choices=DataStatus.choices, ) However I seem to easily create multiple data models for the same user, even when explicitly setting the status to "draft": DraftModel.objects.create(user=some_user, status="draft") I also notice that after I added the constraints and I ran: manage.py makemigrations Django said no migrations to apply. What causes the unique constraint to not work? -
How to Deselect an Already Selected ForeignKey Object in Django FormWizard?
I have a Django project where I use FormWizard for managing multi-step forms. In one of my forms, I have a ModelChoiceField linked to a ForeignKey field in the model. Here's a simplified version of the form: class JobDetailsForm2(BaseHXForm): employee_id = forms.CharField( label='Employee ID', max_length=50, widget=forms.TextInput(attrs={ 'class': 'form-control', 'hx-trigger': 'change', 'readonly': 'readonly', }) ) department = forms.ModelChoiceField( queryset=Department.objects.all(), label='Department', required=False, widget=forms.Select(attrs={ 'class': 'form-control department', 'hx-trigger': 'change', }) ) I want to allow users to deselect the already selected ForeignKey object (i.e., set department to None). However: I use FormWizard, so I don't want to make changes in the views. I don’t have access to the HTML templates to customize the dropdown directly. How can I handle this within the form itself to allow users to deselect the ForeignKey? Is there a way to ensure the form allows this functionality without modifying the views or templates? I’ve ensured the ModelChoiceField is optional by setting required=False, which should allow a None value. However, I’m not sure how to handle this in the form logic without requiring changes in the views or templates. I expected the dropdown in the form to allow an empty selection (---), and upon submitting the form, the ForeignKey … -
Module django_push_notifications does not work
I've previously used Django Push Notifications with FCM, and it worked well. However, after Firebase changed its authentication process, it stopped functioning. What I've Tried Migrated to HTTP v1 API: I updated to the HTTP protocol as described in the django-push-notifications documentation. Updated the Module: Upgraded django-push-notifications to version 3.1.0. Unfortunately, it still doesn't work. Debugging Steps Suspecting an issue with authentication, I implemented a plain Firebase example (using firebase-admin) and confirmed that it worked correctly. Through further experiments, I found that supplying my own messaging.Message object resolves the issue. Here's the code that works: ` message = messaging.Message( notification=messaging.Notification( title=title, body=body, ), data=data, ) ` The problem arises when I use the examples provided in the module's documentation, such as: fcm_device.send_message("This is a enriched message", title="Notification title", badge=6) This does not work. Upon inspecting the source code of the module, I noticed: When creating the Message object, the Notification argument is not used internally. It seems the module doesn't construct the messaging.Notification correctly, leading to the failure. Question I'd prefer not to manually construct the Message object and rely on the module as intended. Does this module currently work for you? Or do you know of any workarounds or … -
Autoflake prints unused imports/variables but doesn't remove them
I'm using the autoflake tool to remove unused imports and variables in a Python file, but while it prints that unused imports/variables are detected, it doesn't actually remove them from the file. Here's the command I'm running: autoflake --in-place --remove-unused-variables portal/reports.py Printed Output: portal/reports.py: Unused imports/variables detected Despite the message indicating unused imports and variables, the file remains unchanged. I've confirmed that the file has unused imports and variables that should be removed. Versions: Django==5.0.7 autoflake==2.3.1 Python==3.11 I also noticed this issue: when I try to install autoflake after turning off .venv in my Django app folder, I get the following error. error: externally-managed-environment × This environment is externally managed ╰─> To install Python packages system-wide, try apt install python3-xyz, where xyz is the package you are trying to install. If you wish to install a non-Debian-packaged Python package, create a virtual environment using python3 -m venv path/to/venv. Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make sure you have python3-full installed. If you wish to install a non-Debian packaged Python application, it may be easiest to use pipx install xyz, which will manage a virtual environment for you. Make sure you have pipx installed. See /usr/share/doc/python3.12/README.venv for more information. note: If you … -
NoReverseMatch at /cms-admin/ Reverse for 'wagtailadmin_sprite' not found. 'wagtailadmin_sprite' is not a valid view function or pattern name
Trying to integrate Wagtail CMS into my website and have been successful as far as when I go to change the path name from '/admin' -> '/cms-admin' because it was causing conflict with the Django database admin page and I started getting the NoReverseMatch error for 'wagtailadmin_sprite' whenever I go to '8000/cms-admin'. Here's the urls.py file: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from wagtail.admin import urls as wagtailadmin_urls from wagtail import urls as wagtail_urls urlpatterns = [ path('db-admin/', admin.site.urls), # Django admin interface path('', include('apps.home.urls')), # Home app URLs path('', include('apps.users.urls')), # Users app URLs # Wagtail path('cms-admin/', include(('wagtail.admin.urls', 'wagtailadmin'), namespace='wagtailadmin')), # Wagtail admin with a unique namespace path('documents/', include(('wagtail.documents.urls', 'wagtaildocs'), namespace='wagtaildocs')), # Wagtail documents with a unique namespace path('', include('wagtail.urls')), # Wagtail page serving ] 'wagtailadmin_sprite' is shown when I search for the URL list in the terminal and all INSTALLED_APPS have been correctly included in settings.py. Using up-to-date Django and Wagtail versions also. Is there something I'm missing? Any ideas are appreciated. -
how i fix this Error occurred during initialization of VM PyReportJasper?
i have problem with pyreportjasper when i click print i git this error Error occurred during initialization of VM Could not find agent library instrument on the library path, with error: La procÚdure spÚcifiÚe est introuvable Module java.instrument may be missing from runtime image. i install jdk 23 and i work with django 4.1 and pyreportjasper 2.1.4 this is my print function in views.py def Demande_Intervention(request): REPORTS_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)),) input_file = os.path.join(REPORTS_DIR, 'Demande_Intervention.jasper') output_file = os.path.join(REPORTS_DIR, 'Demande_Intervention') print(input_file) print(output_file) jasper = PyReportJasper() con = { 'driver': 'postgres', 'username': settings.DATABASES['default']['USER'], 'password': settings.DATABASES['default']['PASSWORD'], 'host': settings.DATABASES['default']['HOST'], 'database': settings.DATABASES['default']['NAME'], 'port': settings.DATABASES['default']['PORT'], 'jdbc_driver': 'org.postgresql.Driver' } pyreportjasper = PyReportJasper() pyreportjasper.config( input_file, output_file, output_formats=["pdf", "rtf"] ) pyreportjasper.process_report() return FileResponse(open(output_file +'.pdf', 'rb'), as_attachment=True) so please help me to solve this problem -
Getting False value even on creating a new User instace in Django signal receiver function, Why don't know?
This is my Signal Definition from django.dispatch import receiver from django.contrib.auth.models import User from django.db.models.signals import post_save, pre_save @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): user = instance if created: print('A new user is created') else: print('A new user is not created') print(sender, user, created) I am using django-allauth package to authenticate user Currently i'm using the very simple account authenticating only Here is the how i have registered signal in my a_users.apps.py def ready(self): print('Ready method is executing') import a_users.signals I should get True ideally in the create_profile function whenever i create a new user But unfortunately i am not getting True rather every time i am getting False Value I can not understand why it is happening Thanks in Advance!! -
Why image upload is not working for Django when using docker
I have an ImageField in my Django blog application that uploads images to a specific folder. The setup works perfectly when I run the application using python manage.py runserver; the image is uploaded to the intended folder without any issues. However, when I run the application in Docker using docker-compose, the image is not being uploaded. The Docker logs (docker logs <container-name>) do not show any errors. Here’s the relevant part of my setup: I use /Works/app-media as the target folder for uploaded images. I also tested this folder is mounted properly. I verified this by creating a file inside the container at /app/media, and it correctly reflects in the local folder. Here’s my docker-compose.yml configuration for reference: services: admin-backend-service: build: context: . container_name: admin-backend ports: - "8000:8000" volumes: - ./static:/app/static - /Works/app-media:/app/media environment: DEBUG: "0" ALLOWED_HOSTS: "admin.dypzen.com" restart: always I use .env file to load the MEDIA_URL and MEDIA_ROOT to my settings.py and I have tested if these variables are loading properly MEDIA_ROOT = os.getenv('MEDIA_ROOT', os.path.join(BASE_DIR, 'media')) MEDIA_URL = os.getenv('MEDIA_URL', '/media/') For clarity I'm sharing a part of my models.py file to see how I defined the ImageField for my blog post app class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) … -
What is the best way to use `ModelChoiceField` in `NestedTabularInline`
Recently, I've noticed that the detail screen in my web has been performing very slowly. After analyzing the issue, I found that it's caused by an inline containing a ModelChoiceField. This field repeatedly executes SELECT * queries to the database, significantly slowing down the screen's loading time. I tried various solutions, including setting the queryset to objects.none() However, this approach led to a new problem: when editing, the data doesn't auto-select as expected. I attempted to address this by setting the initial value dynamically in the __init__ method, but it didn't work due to the lack of a queryset. class ProductOptionForm(CustomDuplicateItemInlineForm): class Meta: model = ProductOption fields = '__all__' # override option để hiển thị autocomplete với size option option = forms.ModelChoiceField( queryset=PodOption.objects.none(), required=True, widget=CustomOptionSelect2( url='product-size-options-auto-complete', ), label='Size Option' ) def __init__(self, *args, **kwargs): super(ProductOptionForm, self).__init__(*args, **kwargs) # Use the preloaded data to set the initial dynamically if self.instance and self.instance.pk and hasattr(self, 'product_size_options'): self.fields['option'].initial = self.product_size_options[self.instance.option_id] # Manually set the result cache It's all empty as you can see If anyone knows the solution, please let me know. Thanks in advance! -
Hot Reloading in Docker Container not working Django
I'm having problems with my VS-Code Dev Container. It is running, but unfortunately, the StatReloader does not work. If I run uv run python manage.py runserver 0.0.0.0:6000 inside the Dev Container (an start a new Django server) it is working perfectly fine. Actually, I'm not sure if the problem is related to Dev Containers because the StatReloader does not work in the Docker container in general. I've tried to... change the volume in .devcontainer/docker-compose.yml to .:/workspace:delegated change the workspaceFolder to workspace run Django with gunicorn # backend/Dockerfile FROM python:3.12 EXPOSE 8000 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get install -y inotify-tools RUN pip install uv watchdog WORKDIR /app COPY pyproject.toml uv.lock ./ COPY . ./ RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app USER appuser RUN uv sync && uv lock CMD [ "uv", "run", "python", "manage.py", "runserver", "0.0.0.0:8000" ] # docker-compose.yml name: experiments-graphql services: django: image: backend build: context: ./backend dockerfile: ./Dockerfile ports: - 8000:8000 restart: "unless-stopped" # .devcontainer/docker-compose.yml services: django: volumes: - .:/workspace:rw,consistent // .devcontainer.json/devcontainer.json { "name": "Existing Docker Compose (Extend)", "dockerComposeFile": [ "../docker-compose.yml", "docker-compose.yml" ], "service": "django", "workspaceFolder": "/workspace", "customizations": { "vscode": { "settings": {}, "extensions": [ "ms-python.python", "eamodio.gitlens", "editorconfig.editorconfig" … -
Django Custom Database Backend
I am trying to use a third party database backend and to understand the topic I followed the approach described under this link: https://python.plainenglish.io/how-to-create-custom-django-database-backends-a-comprehensive-guide-for-developers-c8fb7e6a49ed So I used a docker instance of python:latest (3.13.0) and installed django (5.1.13). I followed the article Complete Real-World Demo: Creating and Using a Custom Django Database Backend in the article above. When I reached the migration part, I received the error message: ModuleNotFoundError: No module named 'custom_backend.base.base'; 'custom_backend.base' is not a package So I changed the settings to: DATABASES = { 'default': { 'ENGINE': 'custom_backend', # .base removed 'NAME': 'my_custom_db', 'USER': 'custom_user', 'PASSWORD': 'custom_password', 'HOST': 'localhost', 'PORT': '5432', } } I still get an error: File "/project/custom_backend_project/manage.py", line 22, in <module> main() ~~~~^^ File "/project/custom_backend_project/manage.py", line 18, in main execute_from_command_line(sys.argv) ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^ File "/usr/local/lib/python3.13/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() ~~~~~~~~~~~~~~~^^ File "/usr/local/lib/python3.13/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() ~~~~~~~~~~~~^^ File "/usr/local/lib/python3.13/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.13/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() ~~~~~~~~~~~~~~~~~~~~~~~~^^ File "/usr/local/lib/python3.13/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.13/importlib/__init__.py", line 88, in import_module return _bootstrap._gcd_import(name[level:], package, level) ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked … -
In Django + REST Framework, what is the right way to get prefetched data in complex serializers?
my first question on stack overflow ! We are making a web app quite similar to a forum (in the concept). Users can post message in threads wich are organized in nested categories wich belongs to a project. A project is a group of users and their content / activity inside it. We are using django + DRF for the backend and Vuejs for the frontend. Quite new to Django, I takeover on the backend and I installed debug toolbar. I realize that our backend is a mess that make ton of queries... So I'm trying to manage that. I found lot of tutorials for prefetch_related and select_related on easy examples but in my case I'm struggling to get this to work. What I would do for now : Get the current project and its last 12 most recently active threads with their last message in one request. Here are my models : # projects/models.py class Project(models.Model): name = models.CharField(max_length=500, verbose_name=_('Name')) slug = models.SlugField(unique=True) image = models.ImageField( blank=True, null=True, upload_to=project_directory_path, max_length=500, verbose_name=_("Project image"), validators=[validate_file_extension]) # not working. Bug ? image_token = models.CharField(blank=True, max_length=50, verbose_name=_('image token')) preferences = models.TextField(blank=True,verbose_name=_('Preferences')) # ... some other methods .... # messaging/models.py class Category(models.Model): STATUS = … -
Grades and Attendance form POST data didn't save to the database
I'm currently working on a project where I have to input Grades and Attendance of students using Django. I have the forms for both Grades and Attendance but when I tried submitting it, it didn't show in their specific tables (Grade) and (Attendance). Can anyone help me? This is my views.py for both: @login_required def mark_attendance(request): students = Student.objects.all() if request.method == 'POST': form = AttendanceForm(request.POST) if form.is_valid(): form.save() return redirect('attendance') else: form = AttendanceForm() return render(request, 'mark_attendance.html', {'form': form, 'students': students}) @login_required def input_grades(request): students = Student.objects.all() subjects = Subject.objects.all() form = GradesForm() if request.method == 'POST': form = GradesForm(request.POST) if form.is_valid(): form.save() return redirect('grades') else: print(form.errors) # This will print errors in the console return render(request, 'input_grades.html', {'form': form, 'students': students, 'subjects': subjects}) Here's my forms.py for both: # Attendance Form class AttendanceForm(forms.ModelForm): class Meta: model = Attendance fields = ['student', 'date', 'is_present'] widgets = { 'date': forms.DateInput(attrs={'type': 'date'}), } # Grades Form class GradesForm(forms.ModelForm): class Meta: model = Grades fields = ['student', 'subject', 'quarter', 'grade'] widgets = { 'grade': forms.TextInput(attrs={'class': 'form-control'}), 'student': forms.Select(attrs={'class': 'form-control'}), 'subject': forms.Select(attrs={'class': 'form-control'}), 'quarter': forms.TextInput(attrs={'class': 'form-control'}), } Forms in their html files: mark_attendance.html <div class="content"> <h2>Mark Attendance</h2> <form method="post"> {% csrf_token %} <div … -
Multi tenancy for consumer facing application
I'm building a consumer-facing application using Django and DRF that will have user accounts. I'd like to integrate some multi-tenancy into it so that all data is separated by tenant(user). I know that I could simply filter by user in queryset but I feel that this approach is a bit more secure. I am also aware of the django-tenant and django-tenant-schema pkgs but I'd like to try and avoid outside pkgs if possible. Basically where there is a main tenants-table all other tables have a foreign-key pointing to that table. Does that sound right? So basically something like this: class Tenant(models.Model): tenant_id = f'{...}' .... from tenant.models import Tenant class User(AbstractBaseUser, PermissionsMixin): user_id = f'{....}' tenant_id = models.ForeignKey(Tenant, ...) ... from tenant.models import Tenant class Profile(models.Model): profile_id = f'{...}' user_id = f'{...}' tenant_id = models.ForeignKey(Tenant, ...) ... -
How do I and my friend build a webapp in sync with live preview and control very feature deployed over time
So my friend and I are starting a startup and we are building a web app that is similar to "sproutgigs". We have written a plan down with the help of AI and we will start with an MVP with limited features after about 6 months depending on the outcome, we will roll out the final features. We have no company experience of how collaboration and things are done but we want to learn and gain experience as we grow. I will take care of the frontend with angular and he does the backend with django. And we would want to use azure with web services and azure storage for static file storage, then for security and monitoring too and finally azure devops for CI/CD. We have never used these before but are eager to get our hands dirty, we just need some guidance as we accomplish this project. So here's me problem! How do we start ? Since we are in different areas, how do we code and get live preview but stilll remain in sync ? We intended to connect git to azure but still researching how all this works. Sorry if i sound like i don't know … -
when deploying DJANGO app in CPANEL, but only the home page works
this is my urls: path('', views.test, name='home'), path('TEST/', views.test, name='test') home has button that redirect to test. iam not using any login, database or anything, just 2 html pages. but only when the path is '' that is working. i tryed on localhost and pythanywhere and it's working prefectly. the probleme only occur on Cpanel. -
Django doesn't detected my files and displays a blank HTML page
I'm new to React (TypeScript) and Django, my Vite-created React project runs flawlessly but when I tried to deploy it using Django, my files don't seem to get detected by it. I've literally tried every possible solution out there and spent 10+ hours on this and yet couldn't fix it because everything seems correct yet all I'm getting is a blank page. Here is the error: Here is my project structure: Here is the HTML file generated by the React build command: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <!-- <link rel="icon" type="image/svg+xml" href="/vite.svg" /> --> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>AI - Chatbot</title> <script type="module" crossorigin src="/assets/index-B5FpUC4l.js"></script> <link rel="stylesheet" crossorigin href="/assets/index-C7NLutAK.css"> </head> <body> <div id="root"></div> </body> </html> This is proof that the requested files do exist in mentioned path: And finally, here is the relevant parts of code from my settings.py: 'DIRS': [ os.path.join(BASE_DIR, 'ai', 'dist'), os.path.join(BASE_DIR, 'ai', 'dist', 'assets'), ], STATIC_URL = '/static/' VITE_APP_DIR = os.path.join(BASE_DIR, "ai") STATICFILES_DIRS = [ os.path.join(VITE_APP_DIR, "dist"), os.path.join(VITE_APP_DIR, "dist", "assets"), ] STATIC_ROOT = os.path.join(BASE_DIR, "static") And DEBUG = True. Thanks