最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Form without submit button in Django - Stack Overflow

programmeradmin0浏览0评论

I see that forms without buttons are very popular (like here). How to create a form that will be automatically submit for two different fields in Django, after the user selects the field (example 1) or type in the text and clicks something (it means completes typing) (example 2):

1.) ChoiceField

forms.py

class Search(forms.Form):
    field = forms.ChoiceField(choices=MY_CHOICES)

views.py

if request.method == "GET":
    form = Search(request.GET)
    if form.is_valid():
    print('it's work')

template.html

<form method="GET">
  {% csrf_token %}
  {{ form }}
</form>

2.) CharField

forms.py

class Search(forms.Form):
    field = forms.CharField(max_length=10)

* other files like above

I see that forms without buttons are very popular (like here). How to create a form that will be automatically submit for two different fields in Django, after the user selects the field (example 1) or type in the text and clicks something (it means completes typing) (example 2):

1.) ChoiceField

forms.py

class Search(forms.Form):
    field = forms.ChoiceField(choices=MY_CHOICES)

views.py

if request.method == "GET":
    form = Search(request.GET)
    if form.is_valid():
    print('it's work')

template.html

<form method="GET">
  {% csrf_token %}
  {{ form }}
</form>

2.) CharField

forms.py

class Search(forms.Form):
    field = forms.CharField(max_length=10)

* other files like above

Share Improve this question edited Mar 21, 2020 at 15:51 halfer 20.4k19 gold badges108 silver badges201 bronze badges asked Sep 8, 2019 at 18:42 Maddie GrahamMaddie Graham 2,1775 gold badges27 silver badges57 bronze badges 2
  • 3 You set an on_change event on the field, and use AJAX requests. – willeM_ Van Onsem Commented Sep 8, 2019 at 18:44
  • Maybe this is from my little experience, but can you give an example of what it should look like AJAX requests? – Maddie Graham Commented Sep 8, 2019 at 20:21
Add a comment  | 

2 Answers 2

Reset to default 14

You may simply change forms.py:

class Search(forms.Form):
    field = forms.ChoiceField(choices=MY_CHOICES,
        widget=forms.Select(attrs={'onchange': 'submit();'}))

Nothing else to add, no jquery needed.

See also here.

You can use jquery in your template like this:

$('#search_field').change(function(){
    $('#your_form').submit()
});

or when user click on something:

$('#something').click(function(){
    $('#your_form').submit()
});
发布评论

评论列表(0)

  1. 暂无评论