简体   繁体   English

Django 表单字段验证

[英]Django Form Field validation

I have a form that requires a URL as input.我有一个需要 URL 作为输入的表单。 I would like to check if the URL begins with http:// or https:// .我想检查 URL 是否以http://https://开头。

If it doesn't have one of these two 'stings' in the beginning, the form submission should give an error.如果一开始没有这两个“刺”中的一个,则表单提交应该会出错。

I don't have any clue on how to get started with this and could not find any info based on my limited knowledge of django and I have no clue what search terms to look up.我对如何开始使用这个没有任何线索,也无法根据我对 django 的有限知识找到任何信息,我也不知道要查找哪些搜索词。

A basic hint would be a great help.一个基本的提示将是一个很大的帮助。

Thanks!谢谢!

My current forms.py has a form based on a model:我当前的 forms.py 有一个基于模型的表单:

class AddUrlForm(forms.ModelForm):

    class Meta:
        model = forwards
        # fields = '__all__'
        exclude = ["user", "counterA", "counterB", "shortcodeurl", "uniqueid"]

models.py:模型.py:

class forwards(models.Model):
    uniqueid = models.AutoField(primary_key=True)
    user = models.CharField(max_length = 150)
    urlA = models.CharField(verbose_name="URL Version A", max_length = 254)
    counterA = models.DecimalField( max_digits=19, decimal_places=0,default=Decimal('0'))
    urlB = models.CharField(verbose_name="URL Version B",max_length = 254)
    counterB = models.DecimalField( max_digits=19, decimal_places=0,default=Decimal('0'))
    timestamp = models.DateTimeField('date created', auto_now_add=True)
    shortcodeurl = models.CharField(max_length = 254)

html segment where that shows how the form is integrated: html 段,其中显示了如何集成表单:

        <form method="post">
            {% csrf_token %}
            {% for field in forwardform %}
                <span>{{ field.label_tag }} </span>
                <p style="color: black">{{ field }} </p>
                {% for error in field.errors %}
                        <p style="color: red">{{ error }}</p>
                {% endfor %}
            {% endfor %}
        <button class="btn btn-outline btn-xl type="submit">Generate URL</button>
        </form>

views.py:视图.py:

def forwardthis(request):
    forwardform = AddUrlForm(request.POST or None)
    if forwardform.is_valid():
        forward = forwardform.save(commit=False)
        forward.user = request.user.username
        forward = forwardform.save()
        uniqueid_local = forward.uniqueid
        uniqueid_local_bytes = uniqueid_local.to_bytes((uniqueid_local.bit_length() + 7) // 8, byteorder='little')
        shortcodeurl_local  = urlsafe_base64_encode(uniqueid_local_bytes)
        forward.shortcodeurl = shortcodeurl_local
        forward.save()
        return HttpResponseRedirect('/forwardthis')
    query_results = forwards.objects.filter(user=request.user.username)
    query_results_qty = query_results.count()
    click_results = clickstats.objects.filter(user=request.user.username)
    template = loader.get_template('forwardthis.html')
    context = {
        'forwardform': forwardform ,
        'query_results':query_results,
        'query_results_qty': query_results_qty
    }
    return HttpResponse(template.render(context,request))

You can create a validation method for each form field.您可以为每个表单字段创建一个验证方法。 def clean_FIELDNAME() . def clean_FIELDNAME() I supose the url field is shortcodeurl :我假设 url 字段是shortcodeurl

class AddUrlForm(forms.ModelForm):

    def clean_shortcodeurl(self):
        cleaned_data = self.clean()
        url = cleaned_data.get('shortcodeurl')
        if not is_valid_url(url):  # You create this function
            self.add_error('shortcodeurl', "The url is not valid")
        return url

    class Meta:
        model = forwards
        # fields = '__all__'
        exclude = ["user", "counterA", "counterB", "shortcodeurl", "uniqueid"]

For anyone coming here in 2021.对于 2021 年来到这里的任何人。

Nowadays Django provides the tools to achieve this kind of validation.现在 Django 提供了实现这种验证的工具。

Based on Django 3.2 documentation基于Django 3.2 文档


from django import forms
from django.core.exceptions import ValidationError

class AddUrlForm(forms.ModelForm):

    class Meta:
        model = forwards
        # fields = '__all__'
        exclude = ["user", "counterA", "counterB", "shortcodeurl", "uniqueid"]

    def clean_shortcodeurl(self):
        data = self.cleaned_data['shortcodeurl']
        if "my_custom_example_url" not in data:
            raise ValidationError("my_custom_example_url has to be in the provided data.")
        return data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM