cannot set initial value for forms.choicefield in django

  • Last Update :
  • Techknowledgy :

May be something like this:

class ArticleForm(forms.Form):
    LETTER_A = 'a'
    LETTER_B = 'b'
    # look not a dict
    CHOICES = ((LETTER_A,'letter a'),
               (LETTER_B,'letter b'))

    choice = forms.ChoiceField(choices=CHOICES)

    def __init__(self, *args, **kwargs):
        initial =  kwargs.get('initial', {})
        choice = initial.get('choice', None)

        # set just the initial value
        # in the real form needs something like this {'choice':'a'}
        # but in this case you want {'choice':('a', 'letter_a')}
        if choice:
            kwargs['initial']['choice'] = choice[0]

        # create the form
        super(ArticleForm, self).__init__(*args, **kwargs)

        # self.fields only exist after, so a double validation is needed
        if  choice and choice[0] not in (c[0] for c in self.CHOICES):
            self.fields['choice'].choices.append(choice)


form = ArticleForm(initial={'choice':('c','other')})
form.as_p()
>>> u'<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">\n<option value="a">letter a</option>\n<option value="b">letter b</option>\n<option value="c" selected="selected">other</option>\n</select></p>'

Suggestion : 2

The best way will be to override get_initial() method.,To initialize the text field with the value from your model, you need to define your own initializer and use the State(wrappedValue:) initializer for @State vars:,Then exclude the field from the form as Exprator shows. If you want to include the field on the form only under some conditions, you can edit the form's .fields during __init__.,You've set your choices up as strings so it should be a CharField(max_length=1, choices=SEX) in the model. You could then use a ModelForm instead of repeating all the logic in a separate form. For example:

class ArticleForm(forms.Form):
    LETTER_A = 'a'
    LETTER_B = 'b'
    # look not a dict
    CHOICES = ((LETTER_A,'letter a'),
               (LETTER_B,'letter b'))

    choice = forms.ChoiceField(choices=CHOICES)

    def __init__(self, *args, **kwargs):
        initial =  kwargs.get('initial', {})
        choice = initial.get('choice', None)

        # set just the initial value
        # in the real form needs something like this {'choice':'a'}
        # but in this case you want {'choice':('a', 'letter_a')}
        if choice:
            kwargs['initial']['choice'] = choice[0]

        # create the form
        super(ArticleForm, self).__init__(*args, **kwargs)

        # self.fields only exist after, so a double validation is needed
        if  choice and choice[0] not in (c[0] for c in self.CHOICES):
            self.fields['choice'].choices.append(choice)


form = ArticleForm(initial={'choice':('c','other')})
form.as_p()
>>> u'<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">\n<option value="a">letter a</option>\n<option value="b">letter b</option>\n<option value="c" selected="selected">other</option>\n</select></p>'
if "submit" in request.GET:
   form = tablePageSettingsForm(request.GET)
if form.is_valid():
   cd = form.cleaned_data
   ...do something with cd and redirect...
      else:
         form = tablePageSettingsForm()
   return render(request, 'template.html', {
      'form': form
   })
def get_changeform_initial_data(self, request):
   return {
      'affected_user': request.user
   }
struct Fahrenheit {
   var temperature = 32.0
}
# models.py
class MyModel(models.Model):
   SEX_CHOICES = (
      ('F', 'Female', ),
      ('M', 'Male', ),
      ('U', 'Unsure', ),
   )
sex = models.CharField(
   max_length = 1,
   choices = SEX_CHOICES,
)

# forms.py
class MyForm(forms.MyForm):
   class Meta:
   model = MyModel
fields = ['sex', ]
class ProfileView(generic.CreateView):
   form_class = writerChangeForm
template_name = 'diary/profile.html'

def get_initial(self):
   # get_initial should
return dict.They should be rendered in template.
writer = Writer.objects.get(pk = 1) # first get data from database.
# dictionary key names should be same as they are in forms.
return {
   'username': writer.username,
   'email': writer.email,
   'first_name': writer.first_name
}

Suggestion : 3

Given a form field’s initial value, returns whether or not the widget can be rendered with the required HTML attribute. Forms use this method along with Field.required and Form.use_required_attribute to determine whether or not to display the required attribute for each field.,Given data and files dictionaries and this widget’s name, returns whether or not there’s data or files for the widget.,'required': A boolean indicating whether or not the field for this widget is required.,This attribute is optional when the form field does not have a choices attribute. If it does, it will override anything you set here when the attribute is updated on the Field.

from django
import forms

class CommentForm(forms.Form):
   name = forms.CharField()
url = forms.URLField()
comment = forms.CharField(widget = forms.Textarea)
from django
import forms

BIRTH_YEAR_CHOICES = ['1980', '1981', '1982']
FAVORITE_COLORS_CHOICES = [
   ('blue', 'Blue'),
   ('green', 'Green'),
   ('black', 'Black'),
]

class SimpleForm(forms.Form):
   birth_year = forms.DateField(widget = forms.SelectDateWidget(years = BIRTH_YEAR_CHOICES))
favorite_colors = forms.MultipleChoiceField(
   required = False,
   widget = forms.CheckboxSelectMultiple,
   choices = FAVORITE_COLORS_CHOICES,
)
>>> from django
import forms
   >>>
   CHOICES = [('1', 'First'), ('2', 'Second')] >>>
   choice_field = forms.ChoiceField(widget = forms.RadioSelect, choices = CHOICES) >>>
   choice_field.choices[('1', 'First'), ('2', 'Second')] >>>
   choice_field.widget.choices[('1', 'First'), ('2', 'Second')] >>>
   choice_field.widget.choices = [] >>>
   choice_field.choices = [('1', 'First and only')] >>>
   choice_field.widget.choices[('1', 'First and only')]
from django
import forms

class CommentForm(forms.Form):
   name = forms.CharField()
url = forms.URLField()
comment = forms.CharField()
>>> f = CommentForm(auto_id=False)
>>> f.as_table()
<tr>
   <th>Name:</th>
   <td><input type="text" name="name" required></td>
</tr>
<tr>
   <th>Url:</th>
   <td><input type="url" name="url" required></td>
</tr>
<tr>
   <th>Comment:</th>
   <td><input type="text" name="comment" required></td>
</tr>
class CommentForm(forms.Form):
   name = forms.CharField(widget = forms.TextInput(attrs = {
      'class': 'special'
   }))
url = forms.URLField()
comment = forms.CharField(widget = forms.TextInput(attrs = {
   'size': '40'
}))

Suggestion : 4

Django initial value of choicefield,initial value for django form choice field ignored,django model form initial value on choicefield,Django ChoiceField Initial Value Not Setting for All ChoiceFields

Try setting the initial value for that field as follows and see if that works:

form = FeeChargeForm(initial = {
   'section': section
})

I assume you're going to be doing a lot of other things when the user posts the form, so you could separate the POST form from the standard form using something like:

if request.method == 'POST':
   form = FeeChargeForm(request.POST)
form = FeeChargeForm(initial = {
   'section': section
})

In views.py:

if request.method == "POST":
   form = FeeChargeForm(request.POST)
else:
   form = FeeChargeForm()

In forms.py:

class FeeChargeForm(ModelForm):
   section_instance = ...#get instance desired from Model
name = ModelChoiceField(queryset = OtherModel.objects.all(), initial = {
   'section': section_instance.id
})

Suggestion : 5

© peterbe.com 2003 - 2022,10 January 2020   10 comments   Python, Web development, Django

class MyForm(forms.Form):
    name = forms.CharField(required=False)

def view(request):
    form = MyForm(initial={'name': 'Peter'})
    return render(request, 'page.html', form=form)

# Imagine, in 'page.html' that it does this:
#  <label>Name:</label>
#  {{ form.name }}
<label>Name:</label>
<input type="text" name="name" value="Peter">
def view(request):
   form = MyForm(request.GET, initial = {
      'name': 'Peter'
   }) # data passed!
   if form.is_valid(): # makes it bound!
   print(form.cleaned_data['name'])
return render(request, 'page.html', form = form)
import copy

class MyForm(forms.Form):
   name = forms.CharField(required = False)

def __init__(self, data, ** kwargs):
   initial = kwargs.get('initial', {})
data = {
   ** initial,
   ** data
}
super().__init__(data, ** kwargs)
<label>Name:</label>
<input type="text" name="name" value="Ashley">
from django.utils.datastructures
import MultiValueDict

   ...

   def __init__(self, data, ** kwargs):
   initial = kwargs.get("initial", {})
data = MultiValueDict({
   ** {
      k: [v]
      for k,
      v in initial.items()
   },
   ** data
})
super().__init__(data, ** kwargs)