Reputation: 927
I'm trying to write forms using Django but I don't manage to set the name of Select field.
class MyForm(forms.Form):
successor = forms.ChoiceField(widget=forms.Select(
attrs = {'name': 'to_player', 'onclick':'this.form.submit();'}
)
)
Gives this output:
<label for="id_successor">Successor:</label>
<select id="id_successor" name="successor" onclick="this.form.submit();"></select>
but should be name="to_player" not name="successor". Why?
Upvotes: 1
Views: 1873
Reputation: 1256
I resolved this problem using javascript.
You can add id attribute in your form:
class MyForm(forms.Form):
successor = forms.ChoiceField(widget=forms.Select(attrs = {'id':'id_player', 'name': 'to_player','onclick':'this.form.submit();'} ))
And at the end of the template you can put this javascript code:
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
...
<script type="text/javascript">
$(document).ready(function(){
document.getElementById('id_player').name = 'to_player';
});
</script>
</body>
</html>
In this way I solved this problem., and works 100% !
Have a nice day !
Upvotes: 2
Reputation: 13188
I believe the name
attribute can't be overwritten using attrs
because of the way the widget is rendered. However, if you check out this answer to a similar question, you will find a wrapper function that will allow you to specify your own name attribute.
Upvotes: 1