Here is my scenario: I have multiple select boxes on a page, where a user selects choices from a ModelChoiceField and is re-directed to a view with the selected option(s) passed as a parameter. Something like:
class BrowseForm(forms.Form):
thing = forms.ModelChoiceField(queryset=Thing.objects.all(), empty_label=None, widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))
stuff = forms.ModelChoiceField(queryset=Stuff.objects.all(), empty_label=None, widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))
view:
def browse(request):
thing_list = Thing.objects.all()
if request.method == 'POST':
form = BrowseForm(request.POST)
if form.is_valid():
thing = form.cleaned_data['thing']
stuff = form.cleaned_data['stuff']
return HttpResponseRedirect(reverse('browse_thing', kwargs={'thing':thing, 'stuff':stuff}))
else:
form = BrowseForm()
return render(request, 'browse.html', {'form':form, 'thing_list':thing_list})
This requires that I submit both fields of BrowseForm, but I want so that there are two different urls for thing and stuff, where either thing or stuff is passed as the parameter, not both. Something like:
url(r'^browse/things/(?P<thing>[\w-]+)/$', 'views.browse', name='browse_thing'),
url(r'^browse/stuff/(?P<stuff>[\w-]+)/$', 'views.browse', name='browse_stuff'),
Is there a way to do this with one form and one view? Or do I need to write a different form for thing and stuff, then check to see which one is passed in my view and re-direct to the appropriate url accordingly? How would you do this? Thanks for your ideas!
Although it doesn’t seem very DRY, this is how I solved the problem:
forms.py:
view:
urls: