Django 1.9 URLField removing the necessary http:// prefix

流过昼夜 提交于 2020-01-15 03:41:29

问题


I've seen a bunch of questions about this, but havent found an answer yet.

This is my models:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    .
    .
    . 
    website = models.URLField(max_length=100, blank=True, null=True)

and my forms.py:

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('website')

    def clean_website(self):
        website = self.cleaned_data['website']
        if website and not website.startswith('http://'):
            website = 'http://' + website
            return website

    # def clean(self):
    #     cleaned_data = self.cleaned_data
    #     url = cleaned_data.get('url')
    #
    #     if url and not url.startswith('http://'):
    #         url = 'http://' + url
    #         cleaned_data['url'] = url
    #         return cleaned_data

I've tried to clean the web address, but I the way django is set up I dont have an opportunity to get to the clean functions.

How can I change Django to allow user the ability to not put in the http(s):// prefix?

I don't want to initialize it with this type of code:

url = forms.URLField(max_length=200, help_text="input page URL", initial='http://')

I've seen this thread:django urlfield http prefix But admittedly am not sure where to put it to see if it even works.


回答1:


This validation isn't being done by Django, but by your browser itself. You can disable that by putting novalidate in the surrounding <form> element.



来源:https://stackoverflow.com/questions/39642003/django-1-9-urlfield-removing-the-necessary-http-prefix

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