【问题标题】:Django Forms Help needed需要 Django 表单帮助
【发布时间】:2010-04-27 06:57:18
【问题描述】:

我是 django 新手,正在尝试制作一个几乎没有验证的用户注册表单。 除此之外,我还想要一个用户名建议代码,它会告诉用户他尝试注册的用户名是否可用或已经在使用中。然后它应该给出一些可供选择的建议。任何可能从事过相同或相同项目的人都可以帮助我解决这个问题。

谢谢

【问题讨论】:

    标签: python django-forms


    【解决方案1】:

    查看django-registration 应用程序。并查看 Class registration.forms.RegistrationForm 及其方法 clean_username。

    应该很容易扩展表单以建议一些用户名。

    这里是一些示例代码,用于生成带有编号后缀的唯一用户名:

        username # filled with user input or first/lastname etc.
    
        #check for other profile with equal names (and those with a postfix)
        others = [int(username.replace(name, "0")) 
                  for p in User.objects.filter(username__startswith=username).exclude(user=self.user)
                  if username.replace(name, "0").isdigit()]
    
        #do we need a postfix
        if len(others) > 0 and 0 in others:
            username = "%s%d" % (username, max(others) + 1)
    

    您可以在表单选择字段中填写生成的名称: http://docs.djangoproject.com/en/dev/ref/forms/fields/#choicefield

    【讨论】:

    • 嗨,maersu,感谢您提供的信息,非常感谢。我安装了该应用程序并正在解决一些您可能可以帮助我解决的问题。我坚持扩展建议的一些用户名部分。你能帮我做些什么吗
    • 我已经更新了我的答案。顺便说一句:阅读我的评论来自stackoverflow.com/questions/2719452/django-forms-help-needed
    • 您好 Maersu,我添加了您提供的示例代码以生成带有数字后缀的用户名,并将其添加到 def clean_username(self): 下所有其他验证。如果我错了或者需要去其他地方,请纠正我。问候
    猜你喜欢
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 2012-02-14
    相关资源
    最近更新 更多