开发者

Decorate GET URL using forms

I have some question:

I use django form, and fields like MultipleChoiceField

in view.py I clean data and get GET URL like this

http://localhost:8000/?category=&style=&sex=&brand=ASICS&brand=Be+Positive&low_price=&high_price=

Give me advise, can I regroup brand field and hide empty.

I want getting something like this:

http://localhost:8000/?brand=1+2

And else one question:

How can I set empty value(empty_label) for forms.ModelMultipleChoiceFIeld

forms.py:

brand = forms.MultipleChoiceField(required=False,
                                  widget=forms.SelectMultiple(attrs={'size':1})
                                  )
def __init__(self,app_label=None, *args, **kwargs):        
    super(Search, self).__init__(*args, *开发者_开发问答*kwargs)
    self.fields['brand'].choices = [('', 'All brands')]+[(brand.name, brand) for brand in Brand.objects.all() ]

views.py:

 if request.method == 'GET' and request.GET:
     form = SearchForm(app_label, request.GET)
     if form.is_valid():   
        brands = form.cleaned_data['brand']
        kwargs.update({"brand__name__in": brands})


This is how the browser submits multiple data. It's part of the HTML specification, trying to change it would be folly and technically I can't understand why you would try to care about how your url GET data looks.

That being said, if you want to change the way it submits you'll need javascript to transform the data on form submit. Django has nothing to do with the matter.

Using jQuery for example:

$('#form').submit(function(){
    //Get form data
    //Transform into my custom set of vars
    //Redirect to form's ACTION with my querystring appended.
});

Please keep in mind you will not get any automatic parsing of the values on the Django side. Normally it would turn it into a list for you, but now you're responsible for parsing the 'value+value+value' yourself.


For empty label in forms you could do this -

class SomeForm(forms.Form):
    h=forms.CharField(label=u'',widget=forms.TextInput(attrs={'value':'Search'}))

By keeping label as '', you get the label as empty. The attrs are basically the HTML attributes of the form text field.

UPDATE: I didn't understand the first part of your Q, elaborate...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜