Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement several widgets to one field (Django)?
I was wondering is there any way i can use several widgets in one form field? I wanna use forms.TextInput(attrs={'class': 'form-control'} and forms.PasswordInput in one field. I've been reading about multiwidgets but I am quite new to django and I am not sure I can comprehend it yet. So are there maybe easier ways to implement 2 widgets at once? Thank you in advance! -
Displaying data from database vs displaying json data from end point in django
I'm familiar with django, now I'm learning django rest framework. Django framework converts database object to Json object. So the json datas can we easily used by the trusted website(CORS).Now my doubt is, I have viewed some tutorial about django rest framework, in that tutorials they are using their own serialized json data and displaying it in browser using react framework...so what is the difference between display data from end point vs displaying directly it from database and rendering it in html in own project -
Elasticsearch Mapping for array
I have the following document for which I need to do mapping for elasticsearch "table_1": { "title": "Spine Imaging Guidelines", "rows": [ "Procedure Codes Associated with Spine Imaging \n3", "SP-1: General Guidelines \n5", "SP-2: Imaging Techniques \n15", "SP-3: Neck (Cervical Spine) Pain Without/With Neurological \nFeatures (Including Stenosis) and Trauma \n24", "SP-4: Upper Back (Thoracic Spine) Pain Without/With Neurological \nFeatures (Including Stenosis) and Trauma \n28", "SP-5: Low Back (Lumbar Spine) Pain/Coccydynia without \nNeurological Features \n31", "SP-6: Lower Extremity Pain with Neurological Features \n(Radiculopathy, Radiculitis, or Plexopathy and Neuropathy) With or \nWithout Low Back (Lumbar Spine) Pain \n35", "SP-7: Myelopathy \n39", "SP-8: Lumbar Spine Spondylolysis/Spondylolisthesis \n42", "SP-9: Lumbar Spinal Stenosis \n45", "SP-10: Sacro-Iliac (SI) Joint Pain, Inflammatory \nSpondylitis/Sacroiliitis and Fibromyalgia \n47", "SP-11: Pathological Spinal Compression Fractures \n50", "SP-12: Spinal Pain in Cancer Patients \n52", "SP-13: Spinal Canal/Cord Disorders (e.g. Syringomyelia) \n53", "SP-14: Spinal Deformities (e.g. Scoliosis/Kyphosis) \n55", "SP-15: Post-Operative Spinal Disorders \n58", "SP-16: Other Imaging Studies and Procedures Related to the Spine \nImaging Guidelines \n61", "SP-17: Nuclear Medicine \n65" ], "meta": { "page_no": 2, "page_text": "Spine Imaging \nGuidelines\n Procedure Codes Associated with Spine Imaging\n 3 SP-1: General Guidelines\n 5 SP-2: Imaging Techniques\n 15 SP-3: Neck (Cervical Spine) Pain Without/With Neurological \nFeatures (Including … -
When I'm running the server in VScode it is showing this error
Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 600, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 413, in check messages.extend(check_resolver(pattern)) File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\abcd\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 607, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'polls.urls' from 'C:\Users\abcd\Desktop\PythonDjango\mysite\polls\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. -
How to create a virtualenv with fish shell on Mac OS?
I am trying to create a virtual environment for a django project. I already installed it with pip3. When I try to create the environment through : ❰C❙~/meltingpot(git:main)❱✔≻ virtualevn meltingpot I get this error fish: Unknown command virtualevn Can somebody please show me how can I create virtualenv successfully -
inheritance another class attributes in model class
While creating database, we have to write some attributes in every tables like (status, registerd_by, registered_dt). So is there any way in django that I create a separete class for these fields and inherit this class in another classes. For example, Creating a common class, class Common(models.Model): registerd_by = models.CharField(max_length = 10) status = models.CharField(max_length = 1) registered_dt = models.CharField(max_length = 10) class Users(models.Model): username = models.CharField(max_length = 10) password = models.CharField(max_length = 10) name = models.CharField(max_length = 200) class Patients(models.Model): name = models.CharField(max_length = 200) age = models.CharField(max_length = 3) gender = models.CharField(max_length = 1) dob = models.CharField(max_length = 10) How to inherit the Common class in these two classes such that the attributes of the Common classes will also become member of these two classes. In this way, I don't have to write the repeating fields in all my classes. -
how to acces key of dictionaries where keys are dyanamic
print(mydict.keys()) dict_keys(['style', '7 colors', '3 sizes']) dict_keys(['style', '6 colors', '4 sizes']) dict_keys(['style', '2 colors', '2 sizes']) needed o/p: I want to acces key '7 colors' and '3 sizes' like print(mydict['7 colors']) but for every loop 7,6,2 may changes,its dynamic so. how to acces thses key values. any one please help me. thanks in advance. -
Hi everyone!! Please help me. I wanna write code in Python using Django library
I have a model with boolean fields(service_1, service2..servicen) and decimal fields(price_1,price_2.. price_n) and also total_price, all of this in same model. I want if user click service_1 and it became True, price_1 append in to total price, if service is empty price didnt append in total price.Please advice me best way how i can do it. p/s sorry for my English, i didnt practice a lot.enter image description here -
How do i get the auto increment from my primary key to my foreign key the moment i create a new question
I have two tables called questions and modelanswer class Questions(models.Model): question_id = models.AutoField(primary_key=True) question = models.TextField() class Meta: db_table = "QUESTIONS" class Answer(models.Model): question_id = models.ForeignKey( Questions, on_delete=models.CASCADE, db_column="question_id" ) answer_id= models.AutoField(primary_key=True) model_ans = models.TextField() class Meta: db_table = 'MODEL' @require_http_methods(["POST"]) @login_required def create_question(request): req = json.loads(request.body) question = req["question"] answer = req["answer"] models.Questions.objects.get_or_create( question=question, ) for answers in answer: models.Answer.objects.create( #question_id=(the auto increment of the new question id from question table after question is created) question_id=models.Questions.objects.get(pk=question_no) model_ans=guided_answers["model_ans"], ) return success({"res": True}) A new question id will be incremented after a new question is created, and what i would like to do is get the new question_id that was just created and pass it to the foreign key in my answers table,however i do not know how to do it, i tried using the question_id=models.Questions.objects.get(pk=question_no) to get it but it gives me a keyerror,is there another way to do it? -
Handling a success and failure response Django
user is sending an api request to crate order along with information in request body and after saving the data i am returning the order_id and access_token to the user.I have used few authentications also with using model.full_clean().Now i am stuck on the part to return success and failure status code and message along with the order_id and access_token. @api_view(['POST']) def orderdetails(request): try: ACCESS_KEY_ID = request.META.get('HTTP_ACCESS_KEY_ID') ACCESS_KEY_SECRET = request.META.get('HTTP_ACCESS_KEY_SECRET') applications = Applications.objects.all() id=0 for e in applications: if(e.ACCESS_KEY_ID==ACCESS_KEY_ID and e.ACCESS_KEY_SECRET==ACCESS_KEY_SECRET ): id = e.id+id print(id) break else: return Response({"Message":"Enter Valid Credentials"}) except ValueError: return Response({"ACCESS":"DENIED"}) if request.method == 'POST': data=request.data print(data) orders = Orders(applications=Applications.objects.get(id=id), purpose_code = data['purpose_code'], amount=data['amount'], currency=data['currency'], note=data['note'], payer_name=data['payer_name'], payer_email=data['payer_email'], payer_phone_country_code=data['payer_phone_country_code'], payer_phone_number=data['payer_phone_number'], payee_name=data['payee_name'], payee_email=data['payee_email'], payee_phone_country_code=data['payee_phone_country_code'], payee_phone_number=data['payee_phone_number'], payee_pan = data['payee_pan'], payee_bank_account_holder_name=data['payee_bank_account_holder_name'], payee_bank_account_number=data['payee_bank_account_number'], payee_bank_account_ifsc=data['payee_bank_account_ifsc'], payee_bank_account_type=data['payee_bank_account_type'], payee_bank_account_beneficiary_identifier=data['payee_bank_account_beneficiary_identifier'], payment_collection_webhook_url=data['payment_collection_webhook_url'], payment_transfer_webhook_url=data['payment_transfer_webhook_url'], payment_gateway_code = data['payment_gateway_code'], isActive=data['isActive'] ) try: orders.full_clean() except ValidationError: return Response({"Error message":"invalid request body"}) else: orders.save() serializer = OrderSerializer(orders) order_id = serializer.data['id'] access_token = serializer.data['access_token'] return Response({"orderId":order_id,"accessToken":access_token}) required Success and failure response in the format bellow : Success response (201/202) along with order_id and access_token Failure response (422) along with message: "error message content" -
Why obj.save() in django return 'none' even after data is saved in database
contact.save() is triggered and data is also saved in database ,but it return none after saving. Anyone explain. I just want display success or error message for the operation. As it return none it jumps to else block. You can see the output 'none' as i print the contact.save() object. -
python manage.py collect static not working. Raises a 'utf-8' codec can't decode byte 0xff issue
Hi guys so i have been trying to deploy my django application to heroku and i ran through a couple of issues. Below is some of the static setting that i have in my settings.py file STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # this takes us to 'src/media/' not 'static/media' The 2 lines below generate the same error. python manage.py collectstatic heroku run python manage.py collectstatic The error for python manage.py collectstatic is (venv) nmj@pc-nm:~/PROJECTS/abc/b99/mysite/src$ python manage.py collectstatic You have requested to collect static files at the destination location as specified in your settings: /home/nmj/PROJECTS/abc/blueMust/mysite/src/staticfiles This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "/home/nmj/PROJECTS/abc/blueMust/mysite/src/manage.py", line 22, in <module> main() File "/home/nmj/PROJECTS/abc/blueMust/mysite/src/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/nmj/PROJECTS/abc/SubmissionMgtSyst/mysite/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/nmj/PROJECTS/abc/SubmissionMgtSyst/mysite/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/nmj/PROJECTS/abc/SubmissionMgtSyst/mysite/venv/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/nmj/PROJECTS/abc/SubmissionMgtSyst/mysite/venv/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/nmj/PROJECTS/abc/SubmissionMgtSyst/mysite/venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/home/nmj/PROJECTS/abc/SubmissionMgtSyst/mysite/venv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 128, in collect for original_path, processed_path, processed in processor: … -
How to give path for zip file to store at particular folder after done with zip in python3
zip file is storing directly into project directory, how to give the path. ZipFile = zipfile.ZipFile(f"{sentgroupid}.zip", "w" ) for zip_files in list_append: ZipFile.write(zip_files, compress_type=zipfile.ZIP_DEFLATED) ZipFile.close() -
Individual test function works, but chaining them get: "FOREIGN KEY constraint failed"
I can run individual test (by calling the function directly), but if I chain them, I've got an error when the Testing enters the next function (the first running fine). django.db.utils.IntegrityError: FOREIGN KEY constraint failed` (I can change the order of the functions, the error is still on the second one). tests.py class MainPage_testing(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super(Text_read, cls).setUpClass() cls.pwd = 'selenium20!!!' cls.user_1 = UserFactory(password=cls.pwd) cls.selenium = WebDriver() cls.selenium.get('{}'.format(cls.live_server_url)) cls.find(By.NAME, 'login').send_keys(cls.user_1.username) cls.find(By.NAME, 'password').send_keys(cls.pwd) cls.find(By.CSS_SELECTOR, "button[type='submit']").click() def test_Create_a_post(self): text = TextsFactory(owner=self.user_1) ... def test_Create_a_comment(self): text2 = TextsFactory(owner=self.user_1) # <-- Triggers the error ... I can run test_Create_a_comment, but if I run the entire test class MainPage_testing, the error appears at the line: text2 = TextsFactory(owner=self.user_1) django.db.utils.IntegrityError: FOREIGN KEY constraint failed` -
How to make a text Bold in Django Administration
Is there a way to make a text bold or e.g. bold in Django Administration. Let's say I have a text field with this Lorum Ipsum text and i want the second word of the sentence to be bold and/or cursive (just like here): Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. -
MultiValueDictKeyError at /search/ when using post request in django
I am Unable to get query, which user is searching for from a POST request Template file <!-- search bar --> <form action="{% url 'search' %}" method="post">{% csrf_token %} <div class="container py-3 row"> <div class="col-md-8 offset-2"> <div class="input-group"> <input name="searchfieldText" type="text" class="form-control" placeholder="Search"> <button class="btn btn-danger" type="submit">Search</button> </div> </div> </div> </form> urls.py ...... path('search/', views.search,name='search'), ..... views.py def search(request): usr_qry= request.POST['searchfieldText'] print(usr_qry) # and some more code which is irrelavent to paste here ..... Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/search/?searchfieldText=window Django Version: 3.2.2 Python Version: 3.9.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'App_wfi_Community', 'django.contrib.humanize', 'askQuestion', 'authentiCation'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\saurav\Documents\GitHub\WFI-Community\venv\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) During handling of the above exception ('searchfieldText'), another exception occurred: File "C:\Users\saurav\Documents\GitHub\WFI-Community\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\saurav\Documents\GitHub\WFI-Community\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\saurav\Documents\GitHub\WFI-Community\App_wfi_Community\decorators.py", line 7, in wrapper_func return func_arg(request, *args, **kwargs) File "C:\Users\saurav\Documents\GitHub\WFI-Community\App_wfi_Community\views.py", line 178, in search usr_qry= request.POST['searchfieldText'] File "C:\Users\saurav\Documents\GitHub\WFI-Community\venv\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__ raise MultiValueDictKeyError(key) Exception Type: MultiValueDictKeyError at /search/ Exception Value: 'searchfieldText' i want to get user search query or whatever user is searching for.. … -
" Your requirements.txt is invalid. Snapshot your logs for details" at eb deploy
I just update my local pip ver to 21 and then I resolved dependencies conflicts. Just after this when I run eb deploy it showed error Your requirements.txt is invalid. Snapshot your logs for details. File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. What can I do to fix this? -
With Django, how to display User friendly names in the template using grouper?
My model offers a choice list: class Interview(models.Model): class InterviewStatus(models.Model): PENDING = '1-PDG' XED = '0-XED' DONE = '2-DON' COMPLETE = '3-COM' ITW_STATUS = [ (PENDING, "Interview Planned"), (XED, "Interview Cancelled"), (DONE, "Interview Done"), (COMPLETE, "Interview Done and Assessed") ] which is implemented in the model fields: status = models.CharField(max_length=5, blank=False, null=False, default=InterviewStatus.PENDING, choices=InterviewStatus.ITW_STATUS, verbose_name="Statut de l'interview") When creating a new object, everything is OK. My template is written as such : {% regroup object_list by status as status_list %} <h1 id="topic-list">Interview List</h1> <ul> {% for status in status_list %} <li><h2>{{ status.grouper }}</h2></li> <ul> {% for interview in status.list %} <li><a href="{{ interview.get_absolute_url }}">{{ interview.official }}{{ interview.date_effective }} </a></li> {% endfor %} </ul> What I get as an outcome in my browser is: . 1-PDG item1 item2 etc. My Question is: How could I obtain the User friendly names instead of the values, which are supposed to be displayed exclusively in the html field: <option value="1-PDG" selected>Interview Planned</option> -
How can i send post request from one django project to another django project?
I have two different projects, inwhich i want to call post request and send the data from one django project to another django project. -
Need guidance on Django Rest API development
I have currently developed an application using Django Rest framework. React is chosen as the front-end for the app. The API endpoints developed needs to be checked/reviewed to ensure correctness before reaching out to the Front-end. Also, a code review is required to ensure a correct programming methodology. Thanks -
wrong URL configuration/pattern in django
In django template, to call url for a link this is what I have done {% for url in request.session.url %} <a href="{{url.linkfield}}" > {{url.name}} </a> {% endfor %} With the above when I load the page the links comes out very well as expected. e.g. www.url.com/ for home www.url.com/staff/firstpage for firstpage www.url.com/staff/secondpage for secondpage etc But when I click on any of the links it would extend the link of the existing page e.g. clicking on firstpage with link www.url.com/staff/firstpage result turns out to be e.g. www.url.com/staff/firstpage for home www.url.com/staff/firstpage/firstpage for firstpage www.url.com/staff/firstpage/secondpage for secondpage etc This is my url.py app_name="application_name" urlpatterns=[ url(r"^staff/",include('application_name.staff_url', namespace='staff')), url(r"^customer/",include('application_name.customer_url', namespace='customer')), ] my staff_url.py from application_name import views app_name="staff" urlpatterns=[ url(r"^customers/",views.customers, name='customers'), url(r"^orders/$", views.orders, name='orders'), url(r"^payments/$", views.payments, name='payments'), ] but when I use {% url %} i.e. instead of {{linkfield}} i am using {% url url.linkfield %} it is producing error in the console i.e. raise NoReverseMatch(msg) dango.urls.exceptions.NoReverseMatch: Reverse for 'whatever_linkname' not found. 'whatever_linkname' is not a valid view function or pattern name. This is my url.py app_name="application_name" urlpatterns=[ url(r"^staff/",include('application_name.staff_url', namespace='staff')), url(r"^customer/",include('application_name.customer_url', namespace='customer')), ] my staff_url.py from application_name import views app_name="staff" urlpatterns=[ url(r"^customers/",views.customers, name='customers'), url(r"^orders/$", views.orders, name='orders'), url(r"^payments/$", views.payments, name='payments'), ] my customer_url.py from … -
keep the data in the input box after submitting form in Django
I have used Django2 to develop a web app. After submitting the form, I want to keep the data in the the form in the frontend. HTML: <form id="myform" action="/content_checklist_name_url/" method="POST" onsubmit="return confirm('Do you want to confirm entries?');"> {% csrf_token %} <label> Discipline:</label> <select id="discipline" name="discipline"> <option value="" selected disabled hidden>--Select--</option> {% for discipline in query_results %} <option value="{{ discipline.id }}">{{ discipline.code }}</option> {% endfor %} </select><br> <label for="name_1"> Discipline Code(e.g. ACC): </label> <input type="text" id="name_1" name="name_1" onkeyup="this.value = this.value.toUpperCase();" ><br> <label for="name_2"> Course Code(e.g. 201): </label> <input type="text" id="name_2" name="course_code" onkeypress='validate(event)'><br> <label for="name_3"> Course Title: </label> <input type="text" id="name_3" name="course_title" ><br> <label> Postgraduate Course: </label> <select id="postgraduate_course" name="postgraduate_course"> <option value="">--Select--</option> <option value="Yes">Yes</option> <option value="No">No</option> </select><br> <label> First Presenting Semester: </label> <select id="semester" name="semester"> <option value="">--Select--</option> {% for semester in query_results_2 %} <option value="{{ semester.id }}">{{ semester.slug }}</option> {% endfor %} </select><br> <!--label> First Presenting Year: </label> <select id="year" > <option value="">--Select--</option> <option value="Dropdown_2021">2021</option> <option value="Dropdown_2022">2022</option> </select><br--> <label> Term: </label> <select id="term" > <option value="">--Select--</option> <option value="Dropdown_1">1</option> <option value="Dropdown_2">2</option> </select><br> <label> Presentation pattern: </label> <select id="Presentation_pattern" name="Presentation_pattern"> <option value="">--Select--</option> <option value="Every_Semester">EVERY SEMESTER</option> <option value="Every_January">EVERY JAN</option> <option value="Every_July">EVERY JUL</option> </select><br> <label> Course Type: </label> <!--select id="type" name="type" > <option value="">--Select--</option> {% … -
djagno use multiple widgets in form field
I'm trying to use two widgets (one to add custom class names, one for the choices) in one field, but not sure how.. there's no clear way specified in the official documentation to do this widget=forms.TextInput(attrs={'class': 'select is-medium'}) widget=forms.Select -
How to update a queryset to include User's full name
Currently in my project I use the following code to obtain a list of Users: all_manager = User.objects.filter(id__in=manager_list).values( "id", "first_name", "last_name" ) For the User model there is no field called 'full_name' or something similar. I read the official documentation and there is a method get_full_name() The question is: How can I modify the queryset to include a 'full_name' key with its value? Dummy Queryset: <QuerySet [{'id': 1, 'first_name': 'Steve', 'last_name': 'Jobs'}, {'id': 3, 'first_name': 'Tim', 'last_name': 'Cook'}]> Desired Queryset: <QuerySet [{'id': 1, 'first_name': 'Steve', 'last_name': 'Jobs', 'full_name': 'Steve Jobs'}, {'id': 3, 'first_name': 'Tim', 'last_name': 'Cook', 'full_name': 'Tim Cook'}]> -
want to show the specific data of opened Accordion in a modal for update operation using Django
here simply I just want to perform an update operation. the data (basically a set of questions from views.py ), and each question is shown in form of a bootstrap accordion. the scenario I want is when we open the accordion, there is a modal toggle button for update the data, and when the button pressed it opens the modal which contains the question of that particular opened accordion which allows the user to update that data. The problem is that in the current code when I click the model button of the 1st question it displays the 1st question data(means work fine) but when I click the 2nd accordion modal button (which contains different question) show the data of the 1st question means 1st accordion data. I can't figure out how to get the desired output means opening the model of a specific accordion should display the data of the particular accordion so that we can perform an update operation. here is my template file {% extends 'base.html' %} {% block title %}Add Questions{% endblock title %} {% block body %} <body> <label for=""><h4 style="color: indianred">Grade >> {{classname}} >> {{topicname}} >> {{subtopicnames}} </h4></label><br> <br> <br> <br> </div> </form> <div …