Home > front end >  Passing default values into an unbound django form
Passing default values into an unbound django form

Time:01-08

I have two select classes that I am trying to create in an unbound form. The data selections are only relevant to the presentation that is created in the view, so are throwaways and do not need to be saved in a model.

The challenge I have is that I can pass in the field listings ok, but how do I set "default" checked / selected values so that the form becomes 'bound'?

views.py

def cards(request):

sort_name = []
    sort_name.append("Alphabetic Order")
    sort_name.append("Most Popular")
    sort_name.append("Least Popular")
    sort_name.append("Highest Win Rate")
    sort_name.append("Lowest Win Rate")

    sort_id = range(len(sort_name))
    sort_list = list(zip(sort_id, sort_name))    

    <more code to make filt_list and zip it>

    if request.method == 'POST':
        form = cardStatsForm(request.POST, sortList=sort_list, filtList=filt_list)
        if form.is_valid():
           do something
        else:
           do something else

   else:
        form = cardStatsForm(filter_list, sort_list)

forms.py

class cardStatsForm(forms.Form):
    def __init__(self, filterList, sortList, *args, **kwargs):
        super(cardStatsForm, self).__init__(*args, **kwargs)
        self.fields['filts'].choices = filterList
        self.fields['filts'].label = "Select player rankings for inclusion in statistics:"
        self.fields['sorts'].choices = sortList
        self.fields['sorts'].label = "Choose a sort order:"

    filts = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=(), required=True)
    sorts = forms.ChoiceField(choices=(), required=True)

The difficulty I am having is the the form fails the "is_valid" test since it is not bound, and I have the "required=true" setting (so that the user must select a checkbox / select a value), but I cannot enforce the logic since it seems the form is never 'bound'.

CodePudding user response:

You can use django forms validation or pass defult value in your views.py. It will return unbound forms if value doesn't match with your default value.

let show you how to do it in your views.py:

error_message = None 
default_value = "jhone" 
if form.is_valid():
           name = request.POST['name']
           defult_name = jhone
           if defult_name != name:
              error_message = 'Name must be jhone'
           if not error_message:
                 form.save()  #it will only save forms if default value match                       
           
           
        else:
           do something else
context = {'error_message':error_message,
           'default_value': default_value, 
            'form':form,  
           } #pass the context in your html template for showing default value and error message 

in your .html

    {{error_message}}
   <input type=text name='name' {%if form.is_bound %} value="{{default_value}} {%endif%}">

CodePudding user response:

I was able to correct my issue by adding "inital=0" and modifying my form call as outlined below:

forms.py

filts = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=(), initial=0, required=True)
sorts = forms.ChoiceField(choices=(), initial=0, required=True)

views.py

    if request.method == 'POST':
        form = cardStatsForm(data=request.POST, sortList=sort_list, filterList=filter_list)
    else:
        form = cardStatsForm(filter_list, sort_list)
  •  Tags:  
  • Related