Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django migrations: SeparateDatabaseAndState vs --fake
Let's say I have a model: class MyModel(models.Model): ... field_no_need_anymore = Charfield(...) I want to remove field_no_need_anymore, but I don't want to apply changes to the database immediately - I will drop this column manually later (next day or day after). In Django for this case I have two options: python manage.py migrate --fake or add this to the migration: operations = [ migrations.SeparateDatabaseAndState( state_operations=[ migrations.RemoveField( model_name='mymodel', name='field_no_need_anymore', ) ], database_operations=[] ) ] In both cases there will be a new record in django_migrations table, while no changes to the target table will be applied. So, when you use --fake and when SeparateDatabaseAndState? -
Django add numbers from database and displaying on screen
I have a model that takes values from each day. I would like to add the sum of those numbers and display them below the columns every time they are added to. For instance: Some days we have a lift_frame in service and some days we don't. At the end of the month I want to display the total number of days we had a lift_frame in service. Can someone help me sort this out, or point me to the documentation that explains adding and displaying sums in Django? This is my current code: model.py class Day(models.Model): day = models.DateField(auto_now=False) well_name = models.ForeignKey("Well", on_delete=models.SET_NULL, null=True) lift_frame = models.IntegerField(default=0) mpd_manifold_building = models.IntegerField(default=0) rcd_housing = models.IntegerField(default=0) pipework = models.IntegerField(default=0) mpd_supervisor = models.IntegerField(default=2) mpd_operator = models.IntegerField(default=2) def __str__(self): return self.day.strftime("%d %B") views.py class Dayboard(LoginRequiredMixin, View): def get(self, request): days = Day.objects.all().order_by('day') return render(request, 'days/dayboard.html', {'days': days}) dayboard.html {% extends 'base/base.html' %} {% block content %} <div class="container"> <div class="d-flex justify-content-end m-4"> {% if user.is_superuser %} <a href="{% url 'add-day' %}" class="btn btn-outline-info rounded">+</a> {% endif %} </div> <table class="table table-hover"> <thead> <tr> <th scope="col">Date</th> <th scope="col">Well</th> <th scope="col">MPD</th> <th scope="col">RCD</th> <th scope="col">Pipe</th> <th scope="col">LF</th> <th scope="col">Sup</th> <th scope="col">Op</th> <th scope="col"></th> </tr> </thead> <tbody> … -
Django: how to reset page URL in a post response?
Context Page displays a list of records (from a DB) where some columns are editable. One "cell" is supposed to contain a sum. Layout is something like this: +----+-------+--------+--------+--------+---------------+ | id | name | Price |Packing |Shipping| Total fees | +----+-------+--------+--------+--------+---------------+ | 32 | Name1 | 150.25 | (0.00) | (1.00) | <Update> 0.00 | <Save> | 47 | Name2 | 57.16 | (0.50) | (1.00) | <Update> 0.00 | <Save> +----+-------+--------+--------+--------+---------------+ <Cancel> <Approve> where (…) denotes an input field and <…> a button. The goal is to be able to manually override what comes from the DB and, in case the row is not "approved" for the next step in the workflow, to save the overrides in the DB for later check. <Update> button computes the sum of the fees. This should probably be handled by JavaScript, locally in the client. <Save> requires a POST transaction. The button has a formaction= to return the row id for identification of which order to process. This means the URL is http://host/app/save/<rowid> while the page is initially queried by http://host/app. It is "easy" to handle it in urls.py: urlpatterns=[ path('app', MyView.as_view(), name='current_list'), path('app/save/<id>', MyView.as_view(), name='patch_entry'), ] When <Save> is pressed, post() receives … -
How to make django automatically fill in a form field with information from another model that is in the database
`Good morning, I am building a system to manage the company I work for, however, I am facing a problem, as I need a certain field in the contract form to be already filled in with the process number to which it belongs, in this case, when I am going to register this contract, this registration is done by the process, by a button that sends to the contract template, which is more precise than the process number (it would be something like the name of the process, different from the primary key) at this moment I need the form is already loaded with the process number, and the user just enters the rest of the information, and saves. Below are my models, views, forms and templates. models i am using cbv to make this sistem -
Django Models - Table and Table status - how to model?
I need some advice... In my django app, I've got models: Order and Order status: class OrderStatus(models.Model): status = models.CharField(max_length=20, verbose_name="Status") class Order(models.Model): orderNo = models.CharField(max_length=20, verbose_name="Order", unique=True) orderStatus = models.ForeignKey(OrderStatus, on_delete=models.PROTECT, verbose_name="Status" ) There are 3 statuses..: New, In progress, Finished... In my views, I frequently use a code like: (for example to create Order) orderx = Order() orderStatus1 = OrderStatus.objects.get(pk=1) # <- the problem is here... orderx.orderStatus=orderStatus1 orderx.orderNo=i orderx.save() The problem, I've got is the one: I should't get Status object by char content (eg. "New" - because it can change, be in different language etc, so I should't filter it like: orderStatus1 = OrderStatus.objects.get(status="New") I also shouldn't get it by id like now: orderStatus1 = OrderStatus.objects.get(pk=1) because there is no warranty, that it will be the same ID while placing in other database, etc.. So how should it be modelled, so I can take STATUS_NEW somehow? -
Django mssql-django is error in MacOS but it is working on Windows
I have already installed pip install mssql-django on MacOS. It was working fine for a while after that stop executing the program ( python3 manage.py runserver) and display message error below: django.db.utils.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)") DB setting: 'default':{ 'ENGINE': 'mssql', 'NAME': 'dbname', 'HOST': 'x.x.x.x', 'PORT': '1433', 'USER': 'sa', 'PASSWORD': 'xxxx', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', } It is working fine on Windows but not working on MacOS why ? -
Duplicate rows in aggregation over values() with many-to-many relation
I'm trying to calculate a lookup for items sharing a common related object + a common value. It seems like it should be pretty straightforward, but I keep getting incorrect results no matter what I try. I can't get the grouping to be what I want it. Here's a simple example: I have Persons assigned to Teams; I have ExpenseReports signed by (multiple) Persons on particular dates. I want a query that finds, for each pair of Team and date, the total expense signed for by that team on that date. Here's my models: class MyTeam(models.Model): name = models.CharField() class MyPerson(models.Model): name = models.CharField() team = models.ForeignKey(MyTeam, on_delete=models.CASCADE) class ExpenseReport(models.Model): expense_paid = models.FloatField() expense_date = models.DateField() persons = models.ManyToManyField(MyPerson) And here's some simple data -- expense reports on two dates. Appa and Alex on Team A ; Barbara and Bob are on Team B: [2024-11-01] 1.0 paid by [<MyPerson: Person <Alex>>, <MyPerson: Person <Appa>>] <-- Team A [2024-11-01] 10.0 paid by [<MyPerson: Person <Barbara>>, <MyPerson: Person <Bob>>] <-- Team B [2024-11-05] 100.0 paid by [<MyPerson: Person <Barbara>>] <-- Team B [2024-11-05] 1000.0 paid by [<MyPerson: Person <Alex>>, <MyPerson: Person <Bob>>] <-- Teams A and B What I've Tried There's the …