Django表单字段验证

时间:2017-08-03 18:44:21

标签: python django forms

我有一个需要URL作为输入的表单。我想检查网址是以http://还是https://开头。

如果它没有这两个叮咬中的一个'在开始时,表单提交应该给出错误。

我对如何开始这个没有任何线索,根据我对django的有限知识找不到任何信息,我也不知道要查找哪些搜索词。

基本提示将是一个很大的帮助。

谢谢!

我当前的forms.py有一个基于模型的表单:

class AddUrlForm(forms.ModelForm):

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

models.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片段,其中显示了表单的整合方式:

        <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:

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))

2 个答案:

答案 0 :(得分:0)

您可以为每个表单字段创建验证方法。 def clean_FIELDNAME()。我将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"]

答案 1 :(得分:0)

对于 2021 年来到这里的任何人。

如今,Django 提供了实现这种验证的工具。

基于Django 3.2 documentation


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