Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/amazon-web-services/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么这个循环总是返回原始参数?_Python_Django_Loops - Fatal编程技术网

Python 为什么这个循环总是返回原始参数?

Python 为什么这个循环总是返回原始参数?,python,django,loops,Python,Django,Loops,我有一个检查用户名的循环。 如果用户名存在,我想增加每个循环的计数器。 然后将该Id附加到用户名 这个循环总是返回传递的原始参数,我不知道为什么。我让它在forms.py中的表单上执行def save def check_username(self, username): """ check if username is taken. if it is then increment the counter and append to the username """

我有一个检查用户名的循环。 如果用户名存在,我想增加每个循环的计数器。 然后将该Id附加到用户名

这个循环总是返回传递的原始参数,我不知道为什么。我让它在forms.py中的表单上执行
def save

def check_username(self, username):
    """
    check if username is taken. if it is then increment the counter and append to the username
    """
    counter = 001
    if User.objects.filter(username__iexact=username).exists():
        counter += 1
        username += str(counter)
        self.check_username(username)
    return username

检查
if User.objects…
条件的有效性,因为
username
如果进入该块,应该更改。

您可能应该使用
return self。检查
if
块中的用户名(username)
,否则,递归调用不会有多大作用

这里的柜台可能也不是你想要的。您将继续在尝试的每个用户名的末尾添加“2”,例如
username
->
username2
->
username2
->
username22

话虽如此,这里的
while
循环肯定更容易阅读。我想试试这样的东西:

def check_username(self, username):
    counter = 1
    new_username = username
    while not User.objects.filter(username__iexact=new_username).exists():
        counter += 1
        new_username = username + str(counter)
    return new_username

你在做一个if,那不是一个循环。你应该用一段时间。哈哈,你是对的,这不是一个循环。。。但我回到了同一个def。然而,一个while循环就是答案。