Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF mixin uses the model manager's create method but not the update method
# models.py class HelloManager(models.Manager): ''' On create, set date_created and last_modified to the same values On update, set last_modified to current time ''' def create(self, *args, **kwargs): current_time = datetime.now() kwargs.setdefault('date_created', current_time) kwargs.setdefault('last_modified', current_time) return super().create(*args, **kwargs) def update(self, *args, **kwargs): kwargs['last_modified'] = datetime.now() return super().update(*args, **kwargs) The CreateModelMixin works just fine, but the UpdateModelMixin does not call my manager's update method. I went through DRF's implementation and found that the UpdateModelMixin calls serializer.save() wich calls either update or create but this is where I got lost. I tried just directly overriding perform_create like so: # views.py class HelloDetailView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, generics.GenericAPIView): queryset = HelloModel.objects.all() lookup_field = 'id' def get_serializer_class(self): if self.request.method == 'POST': return HelloWriteSerializer return HelloReadSerializer def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def perform_update(self, serializer): HelloModel.objects.update(**serializer.validated_data) But the problem now is the UpdateModelMixin now returns old data. What's the best approach for this? -
Related fields aren't filtering in the formset (using library 'django-formset' )
I'm trying to use the library 'django-formset' to filter drop-down list (ForeignKey objects) when selecting an item in a linked drop-down list (related ForeignKey objects). I think, I did everything according to the instructions, but still the data in the second drop-down list is not filtered. Maybe someone has experience using this library with formset? What I did: Model class TypeCar(models.Model): title = models.CharField(max_length=20) class Car(models.Model): reg_mark = models.CharField(max_length=10) type_car = models.ForeignKey( 'TypeCar', ... ) class Order(models.Model): car = models.ForeignKey( Car, ... ) type_car = models.ForeignKey( TypeCar, ... ) Form (FormSet): from formset.widgets import Selectize class OrderCloseForm(forms.ModelForm): type_car = forms.ModelChoiceField( label="Type_car", queryset=TypeCar.objects.all(), widget=Selectize( search_lookup='name__icontains', placeholder="First, select Type car" ), required=False, ) car = forms.ModelChoiceField( label="Car", queryset=Car.objects.all(), widget=Selectize( search_lookup=['title__icontains'], filter_by={'type_car': 'type_car__id'}, placeholder="Then, select a Car" ), required=False, ) class Meta: model = Order fields = ( 'type_car', 'car', ) Formset displays already existing objects in which need to make a selection of the above fields OrderCloseFormSet = modelformset_factory( Order, form=OrderCloseForm, extra=0, can_delete=False, ) Template <head> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link href="{% static 'formset/css/bootstrap5-extra.css' %}" rel="stylesheet"> <link href="{% static 'formset/css/collections.css' %}" rel="stylesheet"> <script type="module" src="{% static 'formset/js/django-formset.js' %}"></script> </head> <django-formset endpoint="{{ request.path }}" csrf-token="{{ csrf_token }}"> {{ formset.management_form }} {{ … -
Python Django does not see the CSS file
I just started using Django, which I initially had a lot of problems with, but that's not the point. I launched a new project about 4 times, it turned out that through the console it did not create a complete list of folders and files and I had to create them manually. I created and added an init file everywhere so that Python sees this folder, however, when I need to insert a Banner photo for my profile, when I start the server through the console and the python manage.py runserver command, although it launches my entire HTML structure, it does not display the photo , which I inserted there initially. I tried to change the location of the folders, I tried to change the location of the photos and it didn’t bring much results. Also, I changed settings.py and urls several times, but this also did not change anything, perhaps I made a mistake in the code or missed something? {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="{% static 'css' %}" /> <title>Your Profile</title> </head> <body> <div class="container"> <div class="sidebar"> <div class="logo"><span class="tf-logo">{{ title … -
Using an object attribute when accessing element in array in Django Template Python
So basically in my Django template I'm passing in two things from my view. a Django model object Plan which is defined like: class Plan(models.Model): class Sport(models.IntegerChoices): RUN = 1, "RUNNING" CYC = 2, "CYCLING" SWM = 3, "SWIMMING" sport = models.PositiveSmallIntegerField( choices=Sport.choices, default=Sport.RUN ) start_date = models.DateField("Starting Date") end_date = models.DateField("End Date") weeks = models.PositiveSmallIntegerField(default=0) title = models.CharField(max_length=20) description = models.TextField(max_length=100, blank=True, null=True) completed = models.BooleanField(default=False) def __str__(self): return self.title and 2. an array of arrays of strava activities pulled from an API, activity_list which is formatted so activity_list[i][j] would return week i's activity on day j. In my template, I need to access activity_list dynamically whilst looping through the week numbers in the plan. My first attempt was to do something like ativity_list.week.number.0 to access the Monday of the week we're on, but as expected Django treats week.number as a literal instead of replacing it with the number "0" or "3" or whatever. I'm really stuck on this so any help would be much appreciated, either with an ad-hoc fix or a way to refactor my models to make this feasible. Thanks -
CPU to 90% for gunicorn process on debian 11 - Django Nginx Gunicorn Supervisor
Since 3 days, I have some issues with the CPU usage which is up to 90%. When I run "top" on command line, I see that CPU usage for gunicorn is very high ! I do not have a lot of trafic on the website. I have checked the access log et error log, but I do not find anything... What Could I check to solve this performance issue ? Thanks I have checked the logs but I did not find anything. I work with Django, Nginx, Gunicorn and Supervisor. -
How to pass data to injected django template?
In django admin interface I have a custom tab for displaying a table. How to display the table as django admin model list table instead of field, but get the context for table from admin.py by calling the method from the model. I used django-baton's baton_form_includes to insert a template below the field, but then I could not pass data to that template. models.py class MyModel(TimeStampedModel): . . . def get_custom_tab_data(self): return OtherModel.objects.filter( active=False ) admin.py @admin.register(models.MyModel) class MyModelAdmin(): . . . readonly_fields = ( "get_custom_tab_data", ) fieldsets = ( _("Custom Tab"), { "fields": ("get_custom_tab_data"), "classes": ("tab-fs-custom") } ) . . # django-baton baton_form_includes = [("admin/custom_tab_template.html", "get_custom_tab_data", "below")] # This was the better solution but template table should display as model admin list with custom data, so had to use baton_form_includes to inject template above field. # def custom_tab_data(self, myModel: models.MyModel): # if myModel.active: # return "N/A" # if custom_data := myModel.get_custom_tab_data()[:15]: # get 15 latest # html_content = render_to_string( # "admin/custom_tab_template.html", # {"custom_data": custom_data} # ) # return mark_safe(html_content) @admin.display(description="Custom Tab") def get_custom_tab_data(self, myModel: models.MyModel): return self.custom_tab_data(account) custom_tab_template.html {% load i18n l10n %} <table class="table table-stripped"> <thead> <tr> <th>ID</th> <th>Name</th> <th>State</th> <th>Created</th> </tr> </thead> <tbody> {% comment %} {% … -
How to get parent model id in child serializer?
How to get parent id in child serializer? class Parent(models.Model): name = models.CharField('') date = models.DateField('') class Material(models.Model): name = models.CharField('') description = models.TextField('') parent = models.ForeignKey(Parent, on_delete=models.CASCADE) serializer = ParentSerializer(data=item) if serializer.is_valid(raise_exception=True): serializer.save() class MaterialSerializer(serializers.ModelSerializer): parent = ? class Meta: model = Material fields = ['id', 'name', 'description', 'parent'] class ParentSerializer(serializers.ModelSerializer): material = MaterialSerializer(many=True) class Meta: model = Parent fields = ['name', 'date', 'material'] I dont understand how get parent id in child serializer -
django-filter ModelMultipleChoiceFilter for product color with Preview
I'm honing my django skills by writing my own e-commerce web application from scratch and I want to let users see a preview for the product colors in the color filters. Here is what I currently have, which works perfectly: What I'm trying to achieve is this: My filters.py file: import django_filters from .models import Product,ProductColor class ProductFilter(django_filters.FilterSet): title = django_filters.CharFilter(lookup_expr='iexact') price_sale = django_filters.NumberFilter() price_regular= django_filters.NumberFilter() release_year = django_filters.NumberFilter(field_name='date_added', lookup_expr='year') release_year__gt = django_filters.NumberFilter(field_name='date_added', lookup_expr='year__gt') release_year__lt = django_filters.NumberFilter(field_name='date_added', lookup_expr='year__lt') chogoyo = ProductColor.objects.all() def colors(request): return ProductColor.objects.all() product_color = django_filters.filters.ModelMultipleChoiceFilter(queryset=colors) class Meta: model = Product fields = ['price_sale','price_regular', 'date_added','product_color'] What would be the best approach to accomplish this? Thank you in advance. -
"kombu.exceptions.OperationalError" occurs When running a server consisting of django, rabbitMQ, celery worker, and celery beat with docker-compose
Im currently trying to deploy a server consisting of django, rabbitMQ, celery worker, and beat. While celery beat executes the created periodic task well, the celery worker that executes the SMS sending task generates the above error message and does not work. version: "3.9" services: was_container: build: context: ./was dockerfile: Dockerfile.was container_name: was_container ports: - "8000:8000" env_file: - ./was/.env restart: always entrypoint: /entrypoint.sh networks: - miti_network rabbitmq: image: rabbitmq:3-management container_name: rabbitmq environment: - RABBITMQ_DEFAULT_USER=admin - RABBITMQ_DEFAULT_PASS=admin - RABBITMQ_DEFAULT_VHOST=/ ports: - "5672:5672" - "15672:15672" expose: - "15672" networks: - miti_network celery_worker: container_name: celery_worker build: context: ./was dockerfile: Dockerfile.celery-worker environment: - CELERY_BROKER_URL=amqp://admin:admin@rabbitmq:5672// depends_on: - was_container - rabbitmq networks: - miti_network command: celery -A config worker --loglevel=info --concurrency=1 celery_beat: container_name: celery_beat build: context: ./was dockerfile: Dockerfile.celery-worker environment: - CELERY_BROKER_URL=amqp://admin:admin@rabbitmq:5672// depends_on: - was_container - rabbitmq - celery_worker networks: - miti_network command: celery -A config beat --loglevel=info networks: miti_network: driver: bridge import os import dotenv from datetime import timedelta from celery import Celery dotenv.load_dotenv() os.environ.setdefault('DJANGO_SETTINGS_MODULE', f'config.settings.{os.getenv("ENVIRONMENT")}') app = Celery('MITI') app.config_from_object('django.conf:settings', namespace='CELERY') CELERYBEAT_SCHEDULE = { 'game_status_auto_update': { 'task': 'config.tasks.update_game_status', 'schedule': timedelta(minutes=1), }, } app.conf.update( CELERYBEAT_SCHEDULE = CELERYBEAT_SCHEDULE ) app.autodiscover_tasks() from .celery import app as celery_app __all__ = ['celery_app'] Please tell me the cause and how can … -
How to make a field unique across two models in Django without inheritance?
I have following 2 models, Admin and Employee: class Admin(models.Model): name = models.CharField(max_length=30) email = models.EmailField() city = models.CharField(max_length=30) def __str__(self): return str(self.name) class Employee(models.Model): name = models.CharField(max_length=30) email = models.EmailField() city = models.CharField(max_length=30) department = models.ForeignKey(Department, on_delete=models.CASCADE) def __str__(self): return str(self.name) What I want is to ensure that the field email is unique across both the models i.e. no two admins can have the same email AND no two employees can have the same email AND no admin and employee have the same email. I created a base class CustomUser and inherited it to both Employee and Admin class: class CustomUser(AbstractUser): email = models.EmailField(unique=True) class Employee(models.Model): name = models.CharField(max_lengt=30) email = models.OneToOneField(CustomUser, on_delete=models.CASCADE) city = models.CharField(max_length=30) department = models.ForeignKey(Department, on_delete=models.CASCADE) def __str__(self): return str(self.name) class Admin(models.Model): name = models.CharField(max_lengt=30) email = models.OneToOneField(CustomUser, on_delete=models.CASCADE) city = models.CharField(max_length=30) def __str__(self): return str(self.name) What I want to know is, is there any other way of ensuring this kind of cross-model uniqueness that wouldn't require me to create a separate Abstract class? -
Unable to display the webpage using reactjs and having problems to integrate it with Django
I have created project where in I am using reactjs as the frontend and Django as the beackend. I have set up both Django and react but I am having trouble to get the app.js in my react project to load on the server, and not sure how to connect it to the Django api endpoint I have created models on the Django server, and when testing on the Django server, I am able to use get and post requests and it is working as expected Below is the my GitHub repo link as I am not sure where I am going wrong and it wouldn't be easy to read if I post all my files on here https://github.com/revanthperla/platform_test.git Appreciate any help I can get -
Django Elastic Search configuration for modeltranslation fields
I'm using ElasticSearch with Django. I've a model "Product", that has title field. I'm also using django-modeltranslation for my Product model to translate title field in several languages. How can I return title field matches with language that coming from request in Elastic Search. I've ElasticSearch currently working, but it's returning default title field -
Django channels and asynchoronise system
How does Django Channels facilitate real-time communication in chat systems, and what are the key components involved in its operation? Additionally, could you elaborate on how Django Channels enables asynchronous communication between two devices in a chat system, highlighting its mechanisms for handling WebSocket connections, message routing, and consumer processing? -
Python: Auto-update a field in database
I want the database to automatically update the status field when the date already passed. For example the date for the event was yesterday, and I don't want to update the status myself. Is it possible for database to automatically change the status? models.py class Events(models.Model): id = models.AutoField(db_column='id', primary_key=True) title = models.CharField(max_length=45, blank=True, null=True) venue = models.CharField(max_length=45, blank=True, null=True) date = models.DateTimeField(max_length=45, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) image = models.ImageField(upload_to=eventpath, blank=True, null=True) date_posted = models.CharField(max_length=45, blank=True, null=True) status = models.CharField(max_length=45, blank=True, null=True) -
How I can run django cronjob function on windows?
I'm developing a Django application which fetches an external API and stores information from that API to a local Django model so I have set a cronjob to automatically fetch and store data within some period of time. but the problem is this that cronjobs don't work on windows. So is there any way I can test my function that it will work on production on linux server. (I'm not using windows task scheduler because I'll have to host it on linux based server.) Any help will be appreciated! -
Django : ValueError at / The 'avatar' attribute has no file associated with it
Django sends me the following error: ValueError at / The 'avatar' attribute has no file associated with it. enter image description here The message appears just after I log in, even though I uploaded an avatar when I registered a dummy profile. I can't even find the avatar in the configured path: media/avatars. Could you help find where I got this wrong please? Bellow is my code. **models.py: ** from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): (some code) avatar = models.ImageField(upload_to='avatars/',blank=True, null=True) **forms.py: ** class RegisterForm(UserCreationForm): (some code) avatar = forms.ImageField( required=False, widget=forms.ClearableFileInput( attrs={ "class": "form-control" } ) ) class Meta: model = User fields = ['username','first_name','last_name','email','avatar','password1','password2','user_type'] **settings.py: ** STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_DIR = BASE_DIR / 'media' STATIC_ROOT = BASE_DIR / 'staticfiles' MEDIA_ROOT = BASE_DIR / 'media' I added this in urls.py of the main project directory: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And finally, the path of where I want the avatars to be uploaded: mainProject ├── media │ ├── avatars Thank you very much for any help I tried to make all the uploaded avatars go to media/avatars. I even made conditions where there is a placeholder image in case the user … -
Could not find module 'C:\OSGeo4W\bin\gdal308.dll' (or one of its dependencies)
I'm trying to use GeoDjango + gdal + PostGis in order to create a map application. OSGeo4W is completelly installed, and all the dll files are there When I run this command: python3 manage.py check I get the following result: ^^^^^^^^^^^^^^^^^^^^^^^^^ FileNotFoundError: Could not find module 'C:\OSGeo4W\bin\gdal308.dll' (or one of its dependencies). Try using the full path with constructor syntax. However the files are correctly existing in the location. Here is how my settings file looks like, for the gdal part: if os.name == 'nt': OSGEO4W = r"C:\\OSGeo4W" # if '64' in platform.architecture()[0]: # OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\\share\\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\\share\\proj" os.environ['PATH'] = OSGEO4W + r"\\bin;" + os.environ['PATH'] GDAL_LIBRARY_PATH = OSGEO4W + r"\\bin\\gdal308.dll" Could someone who has gone through this please help me shed some light over it? -
View in django not running
I have a Django project where I'm trying to activate a user's account when they reset their password. I've created a custom view ActivateUserPasswordResetConfirmView that inherits from PasswordResetConfirmView and overrides the form_valid method to set user.is_active = True. However, the form_valid method in my custom view does not seem to be called when a user resets their password. I've checked my URL configurations and they seem to be correct. Here are the relevant parts of my code: views.py: from django.contrib.auth.views import PasswordResetConfirmView class ActivateUserPasswordResetConfirmView(PasswordResetConfirmView): def form_valid(self, form): user = form.save() user.is_active = True user.save() return super().form_valid(form) myapp/urls.py: from django.urls import path from .views import ActivateUserPasswordResetConfirmView urlpatterns = [ path('reset/<uidb64>/<token>/', ActivateUserPasswordResetConfirmView.as_view(), name='password_reset_confirm'), # other urls... ] project/urls.py: from django.urls import include, path urlpatterns = [ path('', include('myapp.urls')), path('accounts/', include('django.contrib.auth.urls')), # other urls... ] I have also added logging in the form_valid method, but I don't see any log messages when testing the password reset flow, which suggests that the method is not being executed. Any ideas on why the form_valid method is not being called or how I can debug this issue further? -
Technical question: Building API using python in real time connection + authentication
I need to build an API that will be called from Android, iOS and desktop clients using framework like flutter The problem i am facing is that i need to build an APIs that relies on HTTPS request/response that uses JSON format using python and offer some features like authentication, authorization, database storing, static files storing like.png and .pdf and some parts should work in real time connection for chat system but i don't know what should i use. Because i am stacked in multiple options like Django, RESTful and channels frameworks So my questions are Is there a way to combine all those technologies or should i choose one of them and work with them? Is there a better way to do the listed features up? -
SMTPSenderRefused Error Django: (501, b'<settings.EMAIL_HOST_USER>: sender address must contain a domain', 'settings.EMAIL_HOST_USER')
I am working on a Django project. I have a contact form. What I want when someone fills up the form my info@mydomain.com should send my gmail a notification like "Someone filled up your form". When i go to contact form and submit it, there is an error page that says: SMTPSenderRefused at /contact/ (501, b'<settings.EMAIL_HOST_USER>: sender address must contain a domain', 'settings.EMAIL_HOST_USER') Django Version: 5.0.2 Exception Type: SMTPSenderRefused Exception Value: (501, b'<settings.EMAIL_HOST_USER>: sender address must contain a domain', 'settings.EMAIL_HOST_USER') Exception Location: C:\Users\Bedirhandd\AppData\Local\Programs\Python\Python311\Lib\smtplib.py, line 887, in sendmail And here is my codes: Settings.py # EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_BACKEND = 'backend.email.EmailBackend' EMAIL_HOST = 'mail.info@mydomain.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'info@mydomain.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'Mydomain <info@mydomain.com>' backend.email file: (I created the email_backend.py file to avoid "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain" error. I found the code here import ssl from django.core.mail.backends.smtp import EmailBackend as SMTPBackend from django.utils.functional import cached_property class EmailBackend(SMTPBackend): @cached_property def ssl_context(self): if self.ssl_certfile or self.ssl_keyfile: ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT) ssl_context.load_cert_chain(self.ssl_certfile, self.ssl_keyfile) return ssl_context else: ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE return ssl_context And lastly here is my views.py: from django.shortcuts import render from portfolio.models import Portfolio from … -
Can anybody help me find a work remotely? [closed]
Hi hope you all doing well and you don't meet bugs indeed Im quite good at django i can say that im a full-stack with a solid python & JavaScript background. Please get in touch if you have any collaborative opportunities. Peace ✌️. Post. On LinkedIn and other platforms that offers remotes jobs ? -
Dynamic routing not working as expected in Nextjs
I am trying to create a dynamic route in nextjs but I am getting page not found error The page loads only when I give the url with the exact pathname of the page I have a Django Backend server set up I just call The RestApis Here is the error Error Screen here is the page when I pass the exact url enter image description here This is how I created the route in the app directory app/something/[id] And this is the screen I want to render page.tsx I am expecting to a dynamic url from where i can extract the id through params -
Need some advice on Phusion/Passenger setup
Okay, so.. I've never used this set of programs, so please be nice. I help a guy out with his hosted application on dreamhost. I mostly edit some HTML and python. However, it's pretty legacy and it's running phusion/passenger. It's a django site, but I don't think it's "deployed correctly" with django. Typically, I copy everything locally, make edits and run the application manually with something like: python manage.py runserver 0.0.0.0:8000 --verbosity 3 I then just copy over the changes.. However, some of the python modules are REALLY old. I wanted to try and update them. When I update django in my dev environment the application works fine. However, when I update django on the dreamhost environment the application bombs. (I do not have the exception handy) So, I want to more accurately reproduce this environment. I've built a docker container with apache, passenger, etc. I'd like to figure out how to put this application into the passanger environment so I can reproduce the environment. But I simple don't know how - and the amount of Googling i've done has not helped. -
Django: Set initial value of dropdown in form based on value in model
I am working on a ticketing web application using Django as a university. In there, assignees (tutors) need to be able to asign another tutor and change the status of the ticket ("Open", "In progress", ...). The current tutor and the current status is saved in the Ticket model: class Ticket(models.Model): creator = models.ForeignKey( Student, null=True, on_delete=models.SET_NULL ) assignee = models.ForeignKey( Tutor, on_delete=models.SET_NULL, blank=True, null=True ) current_status = models.CharField( max_length=2, choices=KorrekturstatusEnum.choices, default=KorrekturstatusEnum.OFFEN, ) description = models.TextField( default="Please provide as much detail as possibile." ) The life cycle of a ticket is saved in the Messages model: class Messages(models.Model): class ChangeTypeENUM(models.TextChoices): OPEN = "01", "Open" ASIGNMENT = "02", "Asignment" STATUS_CHANGE = "03", "Status change" MESSAGE = "04", "Message" class SenderENUM(models.TextChoices): TUTOR = "01", "Tutor" STUDENT = "02", "Student" student = models.ForeignKey( Student, on_delete=models.SET_NULL, null=True, related_name="student_messages", ) tutor = models.ForeignKey( Tutor, on_delete=models.SET_NULL, related_name="tutor_messages", null=True, blank=True, ) ticket = models.ForeignKey( ticket, on_delete=models.CASCADE, related_name="korrektur_messages" ) text = models.TextField(null=True, blank=True) created_at = models.DateTimeField(default=timezone.now) sender = models.CharField( max_length=2, choices=SenderENUM.choices, default=SenderENUM.STUDENT ) status = models.CharField( max_length=2, choices=KorrekturstatusEnum.choices, default=KorrekturstatusEnum.OFFEN, ) change_type = models.CharField( max_length=2, choices=ChangeTypeENUM.choices, default=ChangeTypeENUM.EROEFFNUNG, ) Changes to a ticket, including messages/comments are done by a from, I'm using a model form here. I am trying to … -
Add dynamic fields through django admin
I've looked around the stack but I cant find any answers. So I have a model like this: class DynamicModel(models.Model): config = models.JSONField() def __str__(self): return self.config what I want to do here now is to show the json field key-value pairs as standalone fields and also be able to edit them in the same way, like if they were each one a different field. This was the best way I could come up to create dynamic fields. So if I have a jsonfield like this: { "age": 23, "name": "John Doe", "gender": "Male" } I would have an `Age` field where I can edit the value or even remove the field alotgether. The changes would then reflect to the `JSONField`. My approach is like this: # forms.py from django import forms from .models import DynamicModel class DynamicModelForm(forms.ModelForm): class Meta: model = DynamicModel fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Check if 'config' is in the fields if 'config' in self.fields: # Extract JSON data from the instance or initialize an empty dictionary json_data = self.instance.config if self.instance and 'config' in self.instance else {} # Loop through the JSON data and add individual fields for key, value …