Django视图:根据架构名称(从URL获取)将用户重定向到模板

2024-06-26 14:49:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图根据用户的模式名称将用户重定向到各种应用程序。到目前为止,我已经写了以下内容:

def loginUser(request, url):
    
    schema_list1 = ['pierre']
    schema_lsit2 = ['itoiz']

    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        t = urlparse(url).netloc
        dbschema = '"' + t.split('.', 1)[0] + '"'
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            
           
            if dbschema in schema_list1:
                print('yes')
                redirect = '/upload.html'
                return HttpResponseRedirect(redirect)
            
            elif dbschema in schema_list2:
                print('yes')
                redirect = '/dash2.html'
                return HttpResponseRedirect(redirect)
                
    else:
        form = AuthenticationForm()

    context = {
        'form': form,
        }
    return render(request, 'loginUser.html', context)

我的问题是我得到了错误:

TypeError at /loginUser
loginUser() missing 1 required positional argument: 'url'
Request Method: GET
Request URL:    https://itoiz.exostock.net/loginUser
Django Version: 3.0.5
Exception Type: TypeError
Exception Value:    
loginUser() missing 1 required positional argument: 'url'
Exception Location: /home/ubuntu/exo/lib/python3.6/site-packages/django/core/handlers/base.py in _get_response, line 113

我是django的新手,我对为什么会出现这个错误感到困惑,特别是因为我在其他地方使用了完全相同的方法,而且效果很好。我想知道是否有人能看到我错过了什么。顺便问一下,还有其他方法可以获取用户的url吗


Tags: 用户informurlreturnifrequestschema
2条回答

当您提交表单时,您可能会向“loginUser”发送请求,而不带参数

另一件事是,您可能不需要将URL作为参数,您只需从请求中获取它:

request.build\u absolute\u uri()

你想做穷人的事吗

如果是这样的话,使用https://github.com/bernardopires/django-tenant-schemas(我们已经用了好几年了,效果非常好。)还有一个,https://github.com/django-tenants/django-tenants它更易于维护,但我从来没有用过它。概念是一样的

除此之外,请执行以下操作:

def login_user(request):  # we don't do camel-casing
    
    # I don't know your exact use case, but having this in the view seems wrong..
    schema_list1 = ['pierre']
    schema_lsit2 = ['itoiz']

    # This will be an empty "{}" if it's not a POST, meaning, you don't need the 
    # extra if, it will work in both cases
    form = AuthenticationForm(data=request.POST)
    if request.method == 'POST':
        dbschema, _, _ = request.get_host().partition('.')
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            
            if dbschema in schema_list1:
                print('yes')
                redirect = '/upload.html'
                return HttpResponseRedirect(redirect)
            elif dbschema in schema_list2:
                print('yes')
                redirect = '/dash2.html'
                return HttpResponseRedirect(redirect)
            else:
                raise Exception('HANDLE THIS!!!')

    context = {
        'form': form,
    }
    return render(request, 'loginUser.html', context)

相关问题 更多 >