Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I replace Email with Phone Number in Django Rest Framework's Forgot Password Module
I have developed an app using ReactJS and Django Rest Framework. Problem: For Forgot Password functionality, we're using the built in module which requires email. The link is propagated to the given email. I want to do this via phone number only. Is it possible? -
How to display data from parent model using foreign key django
I want to display the child model data with the parent model data as well in a queryset. This is my models in model.py class Shareholders(models.Model): sharehold_IC = models.CharField(primary_key=True, unique=True, validators=[RegexValidator(r'^\d{12,12}$'), only_int], max_length=12) sharehold_name = models.CharField(max_length=100, null=True) sharehold_email = models.CharField(max_length=50, null=True, unique=True) sharehold_address = models.TextField(null=True, blank=True) password = models.CharField(max_length=100) def __str__(self): return self.sharehold_name class Meeting(models.Model): MEETING_STATUS = ( ('Coming Soon', 'Coming Soon'), ('Live', 'Live'), ('Closed', 'Closed') ) meeting_ID = models.CharField(primary_key=True, max_length=6, validators=[RegexValidator(r'^\d{6,6}$')]) meeting_title = models.CharField(max_length=400, null=True) meeting_date = models.DateField() meeting_time = models.TimeField() meeting_desc = models.CharField(max_length=500, null=True) meeting_status = models.CharField(max_length=200, null=True, choices=MEETING_STATUS) date_created = models.DateTimeField(default=timezone.now, null=True) def __str__(self): return self.meeting_ID class Question(models.Model): question_ID = models.AutoField(primary_key=True) question = models.CharField(max_length=400, null=True) meeting_id = models.ForeignKey(Meeting, on_delete=CASCADE) shareholder_IC = models.ForeignKey(Shareholders_Meeting, on_delete=CASCADE, related_name='shareholder_ic') date_created = models.DateTimeField(default=timezone.now, null=True) def __str__(self): return str(self.meeting_id) I try to display all the data from the Question model with the shareholders details such as sharehold_name from the Shareholders model. This is how I try to do in Views.py. Views.py def getMessages(response, meeting_id): meeting = Meeting.objects.get(meeting_ID=meeting_id) questions = Question_Meeting.objects.filter(meeting_id=meeting.meeting_ID) # print(list(questions.values('shareholder_IC_id'))) for i in questions: print(i.shareholder_ic.all()) return JsonResponse({"questions":list(questions.values())}) But somehow I got this error AttributeError: 'Question' object has no attribute 'shareholder_ic'. I want to get the result like this: {'question_ID': 141, 'question': "I'm … -
Django perform Annotate , count and Compare
I have following Model. class Gallery(BaseModel): company = models.ForeignKey(to=Company, on_delete=models.CASCADE) image = models.ImageField( upload_to=upload_company_image_to, validators=[validate_image] ) def __str__(self): return f'{self.company.name}' I want to allow maximum upto 5 image to be uploaded by one company so I tried my query as def clean(self): print(Gallery.objects.values('company').annotate(Count('image')).count()) I don't know how to compare above query with Integer 5. How do I do that? -
Found array with 0 sample(s) (shape=(0, 5880)) while a minimum of 1 is required by MinMaxScaler
Hope you people are doing well I found this error==> "Found array with 0 sample(s) (shape=(0, 5880)) while a minimum of 1 is required by MinMaxScaler." Here I am Stuck that I did not know what to do: I am using Django Development and deploy my ML Model: here is the code of my model: CODE import numpy as np import pandas as pd def series_to_supervised(df, cols_in, cols_out, days_in=1, days_out=1): # input sequence (t-n, ... t-1) cols, names = list(), list() for i in range(days_in, 0, -1): cols.append(df.shift(i)) names += [('{}(t-{})'.format(j, i)) for j in cols_in] # concatenate input sequence partial_in = pd.concat(cols, axis=1) partial_in.columns = names # forecast sequence (t, t+1, ... t+n) df = df.filter(items=cols_out) cols, names = list(), list() for i in range(0, days_out): cols.append(df.shift(-i)) if i == 0: names += [('{}(t)'.format(j)) for j in cols_out] else: names += [('{}(t+{})'.format(j, i)) for j in cols_out] # concatenate forecast sequence partial_out = pd.concat(cols, axis=1) partial_out.columns = names return partial_in.join(partial_out).dropna() def transform_data(df, cols, scaler, n_days_past=120): n_cols = len(cols) # df to np array np_arr = np.array(df.values.flatten().tolist()) np_arr = scaler.transform([np_arr]) np_arr = np_arr.reshape((np_arr.shape[0], n_days_past, n_cols)) return np_arr def transform_predictions(pred_df, cols, scaler, n_days_future=30): n_cols = len(cols) # np array to df … -
Django slider widget default value
Using django I have implemented a slider for a form, that is presented as part of a formset so as to enable users to add additional rows using jquery. My issue is that although the model has the default value as ‘0’, and this is what the first row displays, when I add additional rows the slider is at the midpoint (’50’). Can anyone advise how to make additional rows also start at ‘0’. models.py class SideEffect(TimeStampedModel): concern = models.IntegerField(default=0) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) widgets.py from django.forms.widgets import NumberInput class RangeInput(NumberInput): input_type = 'range' forms.py SideeffectFormSet = inlineformset_factory( Patient, SideEffect, fields=("se_name", "timepoint", "concern"), widgets={'concern': RangeInput()}, extra=0, min_num=1, validate_min=True, ) -
WSGI ERROR :Target WSGI script cannot be loaded as Python module
I am trying to deploy a Django application using apache and i am getting the following error [Fri Oct 08 07:55:44.393237 2021] [wsgi:error] [pid 12424:tid 140450959271680] mod_wsgi (pid=12424): Target WSGI script '/home/preinstall/hx_preinstaller/hx_preinstaller/wsgi.py' cannot be loaded as Python module. [Fri Oct 08 07:55:44.393281 2021] [wsgi:error] [pid 12424:tid 140450959271680] mod_wsgi (pid=12424): Exception occurred processing WSGI script '/home/preinstall/hx_preinstaller/hx_preinstaller/wsgi.py'. [Fri Oct 08 07:55:44.393408 2021] [wsgi:error] [pid 12424:tid 140450959271680] Traceback (most recent call last): [Fri Oct 08 07:55:44.393430 2021] [wsgi:error] [pid 12424:tid 140450959271680] File "/home/preinstall/hx_preinstaller/hx_preinstaller/wsgi.py", line 12, in <module> [Fri Oct 08 07:55:44.393435 2021] [wsgi:error] [pid 12424:tid 140450959271680] from django.core.wsgi import get_wsgi_application [Fri Oct 08 07:55:44.393446 2021] [wsgi:error] [pid 12424:tid 140450959271680] ModuleNotFoundError: No module named 'django' My apache virtual host <VirtualHost *:80> DocumentRoot /home/preinstall/hx_preinstaller ErrorLog ${APACHE_LOG_DIR}/preinstall_error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /home/preinstall/hx_preinstaller/hx_preinstaller> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /home/preinstall/hx_preinstaller> Require all granted </Directory> WSGIDaemonProcess preinstall python-path=/home/preinstall/hx_preinstaller:/home/preinstall/.local/lib/python3.6/site-packages WSGIProcessGroup preinstall WSGIPassAuthorization On WSGIScriptAlias / /home/preinstall/hx_preinstaller/hx_preinstaller/wsgi.py </VirtualHost> What should i do?.. -
Django route giving 404
I've got a route registered in the urls.py file of my django main app as: router.register(r"visual/(?P<random_url>[\w]+)/$", views.LinkTest, basename="test") and the url patterns defineded as: urlpatterns = [ # Admin path("admin/", admin.site.urls), # Model API Routes path("rest/api/latest/", include(router.urls)) ] which means I should be able to hit the viewset via the following call http://localhost:8000/rest/api/latest/visual/random_string/ but I'm getting a 404 Can anyone tell me what I'm doing wrong? -
The one line if else elif not working in Django
After referring to this answer Tim Pietzcker, I implemented that code on my website. I'm not getting the proper solution for the same. Well, I try to implement if elif and else statement in one line Django. So I have tried this. views.py cart1 = CartTube.objects.values_list('tube__tubecode', flat = True) cart2 = CartDrum.objects.values_list('drum__drumcode', flat = True) machine = Machine.objects.filter(tubecode__in=cart1) if cart1 else Machine.objects.filter(drumcode__in=cart2) if cart2 else Machine.objects.filter(Q(tubecode__in=cart1) & Q(drumcode__in=cart2)) if cart1 else Machine.objects.all().order_by('id') Well, From the above code I'm trying to find a solution: If the user chooses Drum as a product then the same code should match with Machine and filter the exact matching product. and if, Drum product + Tube product is chosen then show the exact combination product from the Machine Since the individual code works perfectly. Down below are the code work perfectly. ✔️ machine = Machine.objects.filter(tubecode__in=cart1)if cart1 else Machine.objects.all().order_by('id') ✔️ machine = Machine.objects.filter(drumcode__in=cart2) if cart2 else Machine.objects.all().order_by('id') ✔️ machine = Machine.objects.filter(Q(tubecode__in=cart1) & Q(drumcode__in=cart2)) if cart1 else Machine.objects.all().order_by('id') Tell me where I'm going wrong -
import variables if file exists
I have two Python files on the same level in my Django app. settings.py SECRET.py I want to import the variables from SECRET.py in case the file exists. # This code checks if you have the SECRET.py file to connect to the live server if Path("SECRET.py").is_file(): print("Live Database") from .SECRET import * else: print("Local Database") NAME = 'blog_db' USER = 'postgres' PASSWORD = 'admin' HOST = 'localhost' PORT = '5432' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': NAME, 'USER': USER, 'PASSWORD': PASSWORD, 'HOST': HOST, 'PORT': PORT, } } The code keeps connecting to the local database; prints "Local Database", even though I have the SECRET.py file -
Deploy multi Django app on AWS with configuration per instance
I developed a Django+Vuejs app and time has come to try deploying it. The thing is that I want to have an instance of it running for each customer. So each customer would have : AWS RDS database (psql) Container running with the app (AWS ECS instance ?!) Customer 1 can be on v1.0 of my software while Customer 2 could be on v1.2. So they must have different containers (all my versions will be stored in AWS ECR). AWS S3 for their media files Its own subdomain (customer1.mydomain.com, customer2.mydomain.com, ...) While I've been able to build my container with the following Dockerfile : FROM node:lts-alpine as build-frontend-stage WORKDIR /frontend COPY ./frontend/package*.json /frontend/ RUN npm install COPY ./frontend . RUN npm run build FROM python:3.8.10-slim as build-backend-stage RUN apt-get update && apt-get install --yes --no-install-recommends \ g++ \ libpq-dev WORKDIR /backend RUN pip install --upgrade pip COPY ./backend/requirements.txt /backend RUN pip install -r requirements.txt COPY ./backend . COPY --from=build-frontend-stage /frontend/dist/static /backend/static COPY --from=build-frontend-stage /frontend/dist/index.html /backend/static I'm now wondering how can I run it with following questions : When starting the container, It should perform a manage.py migrate to apply migrations to the customer database (so that if I deploy a … -
How can I show help_text attribute through for loop in my template?
forms.py class UserRegistratiion(forms.Form): email = forms.EmailField() name = forms.CharField(help_text="80 Char Maximum") views.py def showFormData(request): fm = UserRegistratiion(auto_id="my_%s") return render(request, "blog/login.html", {"form":fm}) When i use this in my template it works fine and my help_text shows in span tag.. <form action=""> <div> {{form.as_p}} </div> But, whwn i use for loop {% for field in form.visible_fields %} <div> {{field.label_tag}} {{field}} </div> {% endfor %} help_text doesn't show how can i get this? -
form cannot redirect url after clicking on the button django
I have a web page as shown in the picture below, when I click on the add packing or picking button, it is supposed to redirect me to this url: http://127.0.0.1:8000/packing/13/ but it redirect me back to the home page url: http://127.0.0.1:8000/gallery/. How do i fix this issue? views.py @login_required() def packing(request, id): photo = get_object_or_404(Photo, id=id) if request.method == "POST": form = packingForm(request.POST, instance=photo) pickingform = pickingForm(request.POST, instance=photo) if form.is_valid(): if form != photo.packing: photo.status = 'Packing' photo.Datetime = datetime.now() form.save() if pickingform != photo.picking: photo.status = 'Picking' photo.Datetime = datetime.now() form.save() return redirect('gallery') else: form = packingForm(instance=photo) pickingform = pickingForm(instance=photo) context = { "form": form, "pickingform": pickingform } return render(request, 'packing.html', context) forms.py class packingForm(forms.ModelForm): packing = forms.CharField(label='', widget=forms.TextInput(attrs={"class": 'form-control', 'placeholder': 'Indicate packed if the item has been packed'})) class Meta: model = Photo fields = ("packing", ) def __init__(self, *args, **kwargs): super(packingForm, self).__init__(*args, **kwargs) self.fields['packing'].required = False #self.fields['picking'].required = False class pickingForm(forms.ModelForm): picking = forms.CharField(label='', widget=forms.TextInput(attrs={"class": 'form-control', 'placeholder': 'Indicate picked if the item has been picked'})) class Meta: model = Photo fields = ("picking",) def __init__(self, *args, **kwargs): super(pickingForm, self).__init__(*args, **kwargs) self.fields['picking'].required = False packing.html <!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <title>SCS Add Packing … -
I'm trying to add a new page in Django but getting 404 error yet I've added urls and views
I'm a newbie trying to add an a new page but the following error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/study Using the URLconf defined in student_management_system.urls, Django tried these URL patterns, in this order: I've added a function for the page in Views.py and also added the path in URLS.py StudentViews.py code-----> in student management app folder from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from django.contrib import messages from django.core.files.storage import FileSystemStorage # To upload Profile Picture from django.urls import reverse import datetime # To Parse input DateTime into Python Date Time Object from student_management_app.models import CustomUser, Staffs, Courses, Subjects, Students, Attendance, AttendanceReport, \ LeaveReportStudent, FeedBackStudent, StudentResult def study(request): return render(request, "student_template/study.html") Views.py ----->in student management app folder # from channels.auth import login, logout from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render, redirect from django.contrib import messages from student_management_app.EmailBackEnd import EmailBackEnd def home(request): return render(request, 'index.html') def loginPage(request): return render(request, 'login.html') def doLogin(request): if request.method != "POST": return HttpResponse("<h2>Method Not Allowed</h2>") else: user = EmailBackEnd.authenticate(request, username=request.POST.get('email'), password=request.POST.get('password')) if user != None: login(request, user) user_type = user.user_type #return HttpResponse("Email: "+request.POST.get('email')+ " Password: "+request.POST.get('password')) if user_type == '1': … -
how I can access class method variable in other class method in Python/Django
class Login_View(LoginView,FormView): template_name = 'app1/login.html' def form_valid(self, form): global login_user login_user = form.cleaned_data['username'] return super().form_valid(form) class DashboardView(ListView,Login_View): model = AllCompanies template_name = 'app1/dashboard.html' context_object_name = 'data' def get_queryset(self): return AllCompanies.objects.filter(user=login_user) -
django server 127.0.0.1:18000 doesn't work on browser for openedx project
I am using docker container(devstack) for openedx project on Mac. Since I exited all containers accidentally, I can't run the server. I started containers again and it's running fine. When I type command below in the docker container, python /edx/app/edxapp/edx-platform/manage.py lms runserver 18000 System check identified no issues (0 silenced). October 08, 2021 - 15:38:25 Django version 1.11.18, using settings 'lms.envs.devstack_docker' Starting development server at http://127.0.0.1:18000/ Quit the server with CONTROL-C. It seems like working on terminal but Chrome browser shows ERR_EMPTY_RESPONSE error sign. when I tried with 0.0.0.0:18000 or localhost:18000, it also connects to the server but gives me error like this but the difference is it's django debug mode. IOError at /dashboard [Errno 13] Permission denied: '/tmp/mako_lms/7fa50c86c772c2affd8b5a04d05a85da/dashboard.html.py' Strangely, When I run server on 0.0.0.0:18000, I am able to see django admin site with 127.0.0.1 or localhost or 0.0.0.0 :18000/admin but I get the error with the other urls. I am a complete novice on programming. Could someone give me ideas on what else to try? Thanks. -
Django Detecting delete or update method
mixins.py class ObjectViewMixin: def dispatch(self, request, *args, **kwargs): print(request.method, self.get_object()) return super().dispatch(request, *args, **kwargs) so if self.get_object() is None then I can detect its for Creating object if self.get_object() is found then it can be either update or delete method, because request.method always returns POST Now how can I distinguish them? -
(Django Rest Framework) got an error when I used RefreshToken class in rest_framework_simplejwt.tokens
I got an error which is related to RefreshToken class implemented in rest_framework_simplejst. I defined a function: def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token)} when I made a request to the server that is in the development environment, it ran perfectly: "POST /account/signup HTTP/1.1" 200 332 but when I made a request to the server that is in the production environment, it ran poorly: Forbidden: /account/signup I try to debug it and find the breaking point is "refresh = RefresgToken.for_user(user)", when I printed "refresh", it got the same result mentioned before and jumped to the exception block. Forbidden: /account/signup /account/signup is the endpoint that calls the function "get_tokens_for_user". Can anyone explain what is going on and why the production and development environment make the difference? Thanks so much. -
Covert list of lists in Python to json array [closed]
I've a list of lists in python [[0.3818, 0.028437499999999994, 0.09428, 0.08117894736842104, 0.15704, 0.1623230769230769, 0.21171470588235294, 0.23636], [nan, 0.0, 0.195925, 0.2216625, -0.04444, 0.05940769230769231, 0.016263333333333328, 0.201525]] I want to convert it into Json array When tried with just one list [[0.3818, 0.028437499999999994, 0.09428, 0.08117894736842104, 0.15704, 0.1623230769230769, 0.21171470588235294, 0.23636]] It works fine, when added second list it gives parseerror I've tried json.dumps and json.loads, doesn't seem to work data= json.dumps(data) data = json.loads(data) -
Django translation system
I have a small problem that I can't solve. With reference to Django's automated translation system, I wanted to do a teaching test: I went to django / contrib / auth / models.py in the AbstractUser class and in line 340 (Django version 3.2.7) I changed _ ('first name') to _ ('dog') then I went to the django.po file located in django / contrib / auth / locale / it / django.po and there I inserted a new reference, that is: msgid "dog" msgid "cane" i saved and restarted the server. I logged into the administration panel and in the users section the name field comes with "Dog", but I was expecting "Cane" ... What did I do wrong? Thanks so much for the support! -
Reverse for 'packing' with keyword arguments '{'id': '15'}' not found. 1 pattern(s) tried: ['packing/(?P<pk>[^/]+)$'] django
I got an issue here, so whenever the users click on the button, the url can show that it manage to get the ID from the link: http://127.0.0.1:8000/packing/15 but it show me this error when it is redirected to the link: Reverse for 'packing' with keyword arguments '{'id': '15'}' not found. 1 pattern(s) tried: ['packing/(?P[^/]+)$']. How do I fix this error? This is how after redirect it should looks like, but it just give me an error. views.py @login_required() def packing(request, pk): photo = get_object_or_404(Photo, id=pk) if request.method == "POST": form = packingForm(request.POST, instance=photo) pickingform = pickingForm(request.POST, instance=photo) if form.is_valid(): if form != photo.packing: photo.status = 'Packing' photo.Datetime = datetime.now() form.save() return redirect('packing', id=pk) if pickingform.is_valid(): if pickingform != photo.picking: photo.status = 'Picking' photo.Datetime = datetime.now() form.save() return redirect('packing', id=pk) else: pickingform = pickingForm(instance=photo) form = packingForm(instance=photo) context = { "pickingform": pickingform, "form": form, "photo": photo } return render(request, 'packing.html', context, ) forms.py class packingForm(forms.ModelForm): USER_TYPE_CHOICES = ( ('Yes', 'Yes'), ('No', 'No'),) packing = forms.ChoiceField(required=True, widget=forms.RadioSelect, choices=USER_TYPE_CHOICES) class Meta: model = Photo fields = ("packing", ) def __init__(self, *args, **kwargs): super(packingForm, self).__init__(*args, **kwargs) self.fields['packing'].required = False class pickingForm(forms.ModelForm): PICKING = ( ('Yes', 'Yes'), ('No', 'No'), ) picking = forms.ChoiceField(required=True, widget=forms.RadioSelect, … -
postman only showing "This field is required" to ManyToMany field in django
I have 2 models - Module and Room. A module can have zero or multiple rooms and a room can be added into multiple modules. So, there is a simple many-to-many relationship between them. When I use post request, raw-data works, but not form-data. module/models.py - class Module(models.Model): module_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() room_list = models.CharField(max_length = 100, blank=True) rooms = models.ManyToManyField(Rooms, blank=True) rooms/models.py - class Rooms(models.Model): room_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) level = models.CharField(max_length=100) desc = models.TextField() module/serializers.py - class ModuleSerializer(serializers.ModelSerializer): rooms = RoomSerializer(many=True) class Meta: model = Module fields = '__all__' def create(self, validated_data): rooms_data = validated_data.pop('rooms') module = Module.objects.create(**validated_data) for data in rooms_data: room = Rooms.objects.get(**data) module.rooms.add(room) return module def update(self, instance, validated_data): # Updating rooms rooms_data = validated_data.get('rooms') instance.rooms.clear() for room_data in rooms_data: room = Rooms.objects.get(**room_data) instance.rooms.add(room) # Updating other fields fields = [ 'title', 'desc', 'thumbnail', 'is_deleted', ] for field in fields: setattr(instance, field, validated_data[field]) instance.save() return instance rooms/serialier.py - class RoomSerialize(serializers.ModelSerializer): room_id = serializers.IntegerField() class Meta: model = Rooms fields = "__all__" module/views.py - class add_module(APIView): def post(self, request, format=None): # Adding the rooms to module from room_list new_request = request.data.copy() room_list=[] if 'room_list' in new_request: room_list_data = list(new_request['room_list'].split(" … -
Why are script tags auto converting & to &?
I'm experiencing a strange problem I haven't run into before. My html is generated via Django templates, and consist of some basic code that initializes a DataTable based on a query string with some GET variables (i.e. "/report1/?filter1=abc&filter2=def"). However, all of a sudden, whenever I write the Django template variable out within a <script></script> tag the & is converted to &amp;, like this: <script> var link = "/report1/?filter1=abc&amp;filter2=def" </script> However, when not inside a script tag, the string outputs as originally intended: "/report1/?filter1=abc&filter2=def" This is based off the exact same Django template variable with no changes. What about the script is causing the & to be encoded? This happens in current versions of Edge and Firefox. Django clearly doesn't know anything about the <script></script> tags so it must be a browser thing. Any ideas how to prevent this from happening? It is something that didn't seem to happen in the past. Thanks! For reference, my Django template looks something like this: {{ string }}<br> <script> var link = "{{ string }}" </script> -
Normalize CRLF line endings in Django form input
I have a ModelForm with a TextArea. If the user submits text with a newline, it gets converted into a \r\n by the browser. I would expect Django to normalize this text for me, but it doesn't. This is an issue because Django's maxlength validation doesn't line up with the maxlength in HTML, since in-browser lines endings are treated only as "\n". So if the textarea has a maxlength of 5, and the user enters "ab\ncd", they think that's fine, but when they submit the form, Django error because it sees "ab\r\ncd", which is 6 characters. I want to fix this by doing everything with \n, and not save \r\n into the database. -
Django Class Model choices from json file
When creating class in Django, why upload from json file instead of entering CHOICES directly? Is it not stored as a string in the Database, but as a 'pk' to relieve the burden on the DB? Or is it to facilitate when outputting values from a template? [models.py] class StudyFieldModel(models.Model): class Meta: abstract = True CHOICES = tuple() class Stage(StudyFieldModel): --> Method1 STAGE1 = 'stage1' STAGE2 = 'stage2' STAGE3 = 'stage3' NA = 'na' CHOICES = ( (NA, '해당없음'), (STAGE1, 'Stage 1'), (STAGE2, 'Stage 2'), (STAGE3, 'Stage 3'), ) class Stage(StudyFieldModel): --> Method2 CHOICES = ( ('na', '해당없음'), ('stage1', 'Stage 1'), ('stage2', 'Stage 2'), ('stage3', 'Stage 3'), ) [stage.json] [ { "model": "study.Stage", "pk": 1, "fields": { "value": "na" } }, { "model": "study.Stage", "pk": 2, "fields": { "value": "stage1" } }, { "model": "study.Stage", "pk": 3, "fields": { "value": "stage2" } }, { "model": "study.Stage", "pk": 4, "fields": { "value": "stage3" } } ] -
show selected checked boxes in update form that are saved in database while create form in django
In my create form i have saved certain values of soil_type as clay, chalk in my database these values should be shown ticked in update form let us consider my forms.py as SOIL_TYPE_CHOICES = ( ('Acidic','Acidic'), ('Alkaline','Alkaline'), ('Chalk','Chalk'), ('Clay','Clay'), ('Damp','Damp'), ) soil_type = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple(attrs={'checked' : 'checked'}), choices=SOIL_TYPE_CHOICES, ) When i am using widget=forms.CheckboxSelectMultiple(attrs={'checked' : 'checked'}) in updateform it is showing all the choices as ticked rather than the values that are saved in database(i.e clay, chalk only should be ticked in updateform display) Currently it is showing in this way in update form How i need the image to be is Please help me to display ticks only on the saved values in database