如何更改 django 表单中表单字段的输入类型?

问题描述 投票:0回答:3

我的 form.py 文件中有一个表单类,我在其中启动了表单字段的属性。我想将“描述”字段从输入字段更改为高度为 5 行的文本区域字段。还想将我的“截止日期”字段更改为日期输入字段,因为目前它是输入文本字段。

class JobPost_form(ModelForm):
class Meta:
    model = Job_post
    fields = "__all__"

def __init__(self, *args, **kwargs):
    self.fields['Job_role'].widget.attrs.update(
        {'class': 'form-control Password2', 'id': 'form3Example1c', 'placeholder': 'Job role'})
    self.fields['Company'].widget.attrs.update(
        {'class': 'form-control', 'id': 'form3Example1c', 'placeholder': 'Company'})
    self.fields['Deadline'].widget.attrs.update(
        {'class': 'form-control', 'id': 'form3Example1c', 'placeholder': 'YYYY-MM-DD HH:MM:SS'})
    self.fields['Description'].widget.attrs.update(
        {'class': 'form-control', 'id': 'form3Example1c', 'placeholder': 'Description'})
django forms django-models django-forms
3个回答
0
投票

我认为在您传递的代码中缺少表格,因为元和 init 将位于类中:JobPost_form。至于将描述字段标记为文本区域,您应该这样做:

class JobPost_form(ModelForm):
    description = forms.CharField(widget=forms.TextInput(attrs={"class": "form-control"}))

    class Meta:
        model = Job_post
        fields = "__all__"

    def __init__(self, *args, **kwargs):
...

0
投票

您可以使用 django 在表单 api 中提供的 wigets(attrs="{}") 来实现这些事情

模型.py

class DemoClass(models.Model):
    description = models.TextField()
    deadline = models.DateField()

表格.py

class DemoForm(forms.ModelForm):
    class Meta:
        model = DemoClass
        fields = "__all__"

        widgets={
            'description':forms.Textarea(attrs={"rows":"4", "cols":"50"}),
            'deadline':forms.TextInput(attrs={'type':'date'}),
            --------------- OR -------------------------------
            'deadline':forms.DateInput(attrs={'type':'date'}),
            
        }

HTML

{% block body %}
  <div class="container">
    <div class="row">
      <div class="col-lg-12">

        {{form.as_p}}
        
      </div>
    </div>
  </div>
{% endblock body %}

输出

enter image description here


0
投票

我找到了一种完全改变输入的方法。在此代码中,我将其更改为 type=range 并向其中添加了引导类。

class RangeBooted(Input):
def get_context(self, name, value, attrs):
    ctx = super(RangeBooted, self).get_context(name, value, attrs)
    ctx['widget']['type'] = "range"
    ctx['widget']['attrs']['class'] = "form-range bg-secondary rounded shadow w-75 p-2"
    ctx['widget']['attrs']['min'] = "0"
    ctx['widget']['attrs']['max'] = "100"
    ctx['widget']['attrs']['step'] = "2"
    return ctx
© www.soinside.com 2019 - 2024. All rights reserved.