如何在django表单中格式化用户的输入

时间:2017-07-22 12:57:51

标签: python django django-forms django-templates

如何强制用户使用格式化输入 name.extention

我需要在表单中实现两种格式:

  1. 用户只能输小写字母(不允许使用大写字母) 需要tagName字段
  2. 对于另一个字段,用户需要输入filename.extentio(server.js)需要文件名字段
  3. 如何在我的Django表单或模板中实现这两个场景

    forms.py

    from django import forms
    
    
    class BuildImageForm(forms.Form):
        instances = forms.CharField(max_length=255)
        tagName = forms.CharField(max_length=255)
    

    buildImage.html

    <div class="form-group">
          <span class="col-md-1 col-md-offset-2 text-center"><label for="package">Docker Image Tag Name:</label></span>
           <div class="col-md-8">
           <input  type="text" name="tagName"  id="tagName" placeholder="e.g node_image/istiogui" class="form-control" required>
           /div>
          <div class="col-md-8">
           <input  type="text" name="filename"  id="fileName" placeholder="e.g server.js" class="form-control" required>
           /div>
    </div>
    

1 个答案:

答案 0 :(得分:0)

您的表格:

class BuildImageForm(forms.Form):
    instances = forms.CharField(max_length=255)
    tagName = forms.CharField(max_length=255)


    def clean_instances(self, *args, **kwargs):
        instances = self.cleaned_data.get("instances").lower()
        return instances

    def clean_tagName(self, *args, **kwargs):
        tagName = self.cleaned_data.get("tagName")
        if tagName[-3:] == '.js'
            return tagName
        return ValidationError('Invalid value')

您的观点:

def your_view(request):
    form = BuildImageForm(request.POST or None)

    if request.method == 'POST':
        form = BuildImageForm(request.POST or None)
        if form.is_valid():
            # Or Use in valid form
            item = form.commit(commit=False)
            item.instances = item.instances.lower()
            item.save()
     return ...