仅允许字母、数字、下划线或连字符django

仅允许字母、数字、下划线或连字符django,django,Django,我有一个表单,允许用户使用UserModel注册我的应用程序。我试图在用户名中只允许字母、数字、下划线或连字符。我一直在尝试使用validate_slug¨但我不知道如何使用它来验证提交的输入是否只有字母、数字、下划线或连字符,否则会引发错误 谁能帮帮我吗 class UserRegistration(forms.Form): username = forms.CharField() email = forms.EmailField() password = forms.

我有一个表单,允许用户使用UserModel注册我的应用程序。我试图在用户名中只允许字母、数字、下划线或连字符。我一直在尝试使用validate_slug¨但我不知道如何使用它来验证提交的输入是否只有字母、数字、下划线或连字符,否则会引发错误

谁能帮帮我吗

class UserRegistration(forms.Form):
    username = forms.CharField()
    email = forms.EmailField()
    password = forms.CharField(
        widget=forms.PasswordInput(render_value=False))


        def clean_username(self):
            username = self.cleaned_data['username']

                if "@" in username:
                    raise forms.ValidationError("Sorry , you cannot use the symbol @")
                return username

您可以使用正则表达式匹配,而不是验证所有可能性,只验证允许的字符:

import re
if not re.match(r'^[A-Za-z0-9_-]+$', username):
    raise forms.ValidationError("Sorry , you can only have alphanumeric, _ or - in username") 

您可以使用正则表达式匹配,而不是验证所有可能性,只验证允许的字符:

import re
if not re.match(r'^[A-Za-z0-9_-]+$', username):
    raise forms.ValidationError("Sorry , you can only have alphanumeric, _ or - in username")