Which Django Form Field can provide me a HTML output of <input type=“range” />?

Deadly 提交于 2021-01-21 09:49:05

问题


I've got a html form with this input:

    <input id="duration_slider" type="range" min="1" max="168" value="48" />

However I'd now like to convert this slider to a django form field, so I can use it in a Django form. The field name is duration so I'll change the id to id=id_duration.

What would my models.py and forms.py looks like for this field?

Currently it's just:

class AdvertisePost(Post):
    ...
    duration = models.IntegerField(default=48)

    def __str__(self):
        return self.title

class AdvertisePostForm(forms.ModelForm):
    duration = ?

    class Meta:
        model = AdvertisePost
        fields = [
            ...
            #'duration'    
        ]

EDIT

views

if options_form.is_valid():
    instance = options_form.save(commit=False)
    print(instance.duration) #prints the default value every time

form field

duration = forms.IntegerField(widget=forms.NumberInput(attrs={'type':'range', 'step': '1', 'min': '1', 'max': '148'}), required=False)

回答1:


Oof two years! I'm very late

class AdvertisePostForm(forms.ModelForm):
     class Meta:
         model = AdvertisePost
         fields = ['duration', ...]
         widgets = {
         'duration': forms.TextInput(attrs={'type': 'range'})
         }

Hope this works edit: You will need some javascript if you want to display it tho and some of work in the backend side to turn it into Int



来源:https://stackoverflow.com/questions/49772684/which-django-form-field-can-provide-me-a-html-output-of-input-type-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!