I have a basic Django ModelForm working. I am trying to add a Django choice (select/drop-down) to that ModelForm. The code I have has been cobbled together from various example on the web (see below) – as I try to learn Django. So far I cannot find the correct code to add the Django choice. What I have coded is below. I have tried various combinations of keywords and parameters in forms.py for example:
from django.forms import ModelForm
#
from .models import P2Poll
#
categ_choice= [
('AB', 'AB'),
('CD', 'CD'),
('EF', 'EF'),
('GH', 'GH'),
]
#
class AnyForm(ModelForm):
class Meta:
model = P2Poll
fields = ['q_text', 'Choice1_text', 'Choice2_text','C1_Type','C2_Type']
#
category = forms.ChoiceField(max_length=2, choices=categ_choice)
#
The code has been taken from the following (among others)
django use model choices in modelform
https://docs.djangoproject.com/en/4.0/topics/forms/modelforms/
https://www.geeksforgeeks.org/meta-class-in-models-django/
http://www.learningaboutelectronics.com/Articles/How-to-create-a-drop-down-list-in-a-Django-form.php
When trying the code variation above, I get the following error message:
.. \forms.py", line 28, in Meta category = forms.ChoiceField(max_length=2, choices=categ_choice) NameError: name 'forms' is not defined
I have tried a variety of other code attempts to add the choice/select to my Django form, for example:
from django.forms import ModelForm, forms
and I can’t get any to work – there are different error messages, but they all relate to my attempt to add the Django choice to the (model?) form.
Now, as I understand, creating the (basic) form in Django one has to be fairly detailed about what goes in the form. (As I understand) using ModelForms, one just codes what data should appear on the form and Django makes intelligent/standard choice about the appearance of the form. Maybe I am trying to merge ModelForms with (standard?) Django forms – I don’t know. I am just trying to understand how to add a choice/select to a Django (model) form. I am learning.
Now maybe what I am trying to do is not possible with the “parts” I have assembled. I have read the Django documentation on forms, and I find it incomprehensible with my level of knowledge. I’m sure my understanding of the documentation will improve as I understand Django more.