gpt4 book ai didi

How to use the redirect_field_name in Django's auhviews?(如何在Django的auhview中使用REDIRECT_FIELD_NAME?)

转载 作者:bug小助手 更新时间:2023-10-25 11:00:02 25 4
gpt4 key购买 nike



I am creating a django project involving multiple types of users. For that, I have not created new User classes, rather I have just extended the model using a OneToOne relation (like we do while creating a profile model). Model in one app is like this:

我正在创建一个Django项目,涉及多种类型的用户。为此,我没有创建新的用户类,而只是使用ONEtoONE关系扩展了模型(就像我们在创建概要文件模型时所做的那样)。一款应用中的模型是这样的:


class Dev(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE)
BaseSkills = models.ManyToManyField(ProjectBaseSkills,
help_text='Adding Base skills help us to identify the best projects for you', blank=True)
PhoneNumber = models.BigIntegerField(
help_text="Don't add the country code (the user base is restricted to India for now)")

def __str__(self):
return f'{self.user.first_name} {self.user.last_name}'

and in the other app is like this:

在另一款应用中是这样的:


class Hirer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
Name = models.CharField(max_length=120, default='Hirer')
PhoneNumber = models.BigIntegerField(blank=True)

This shows how there are two types of users: Devs and Hirers.
Now since there are multiple user types, I need to redirect the different users to different urls after login, so I can't just rely on the LOGIN_REDIRECT_URL settings. Also I don't want to define a login view myself, so I am using the default LoginView from django auth.
Here is the urls.py for the app where Dev user is used:

这显示了如何有两种类型的用户:开发者和雇佣者。现在由于有多种用户类型,我需要在登录后将不同的用户重定向到不同的URL,所以我不能只依赖LOGIN_REDIRECT_URL设置。我也不想自己定义登录视图,所以我使用django auth的默认LoginView。以下是使用Dev用户的应用程序的urls.py:


from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from . import views

urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name='dev_user/login.html'), name='dev-login'),
path('register/', views.Register, name='dev-register')
] + static(settings.MEDIA_URL, document_root =settings.MEDIA_ROOT)

And the one where Hirer user is used:

和使用Hirer用户的版本:


from django.urls import path
from django.contrib.auth import views as auth_views
from django.conf import settings
from django.conf.urls.static import static
from . import views

urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name='client_user/login.html'), name='client-login'),
path('register/', views.Register, name='client-register'),
] + static(settings.MEDIA_URL, document_root =settings.MEDIA_ROOT)

In the documentation (https://docs.djangoproject.com/en/3.0/topics/auth/default/#django.contrib.auth.views.LoginView) it is said that we can override the redirect url by using the redirect_field_name in GET field of the LoginView. But there's not example code or something, and I'm quite new at programming, so I don't know how to do that. There are also no examples on the net, so please someone help me out here.

在文档(https://docs.djangoproject.com/en/3.0/topics/auth/default/#django.contrib.auth.views.LoginView)中,我们可以通过在登录视图的GET字段中使用REDIRECT_FIELD_NAME来覆盖重定向URL。但是没有示例代码之类的东西,而且我对编程还很陌生,所以我不知道该怎么做。网上也没有这样的例子,所以请谁来帮帮我。


更多回答

It means the url should look like this: localhost:8000/login/?redirect=/admin

这意味着URL应该如下所示:本地主机:8000/登录/?重定向=/admin

Pardon my naiveness, but can you specify it in a snippet that should be changed in my project?

请原谅我的天真,但您能在我的项目中指定应该更改的代码片段吗?

OK, let's say you are in an unauthorised view, but do know the email. So you'd like to do the login and afterwards redirect to let's say /youraction so your view must do like: return HttpResponseRedirect(reverse('auth_login') + '?next=/youraction)

好吧,假设你处于未经授权的视图中,但确实知道这封电子邮件。因此,您希望进行登录,然后重定向到/YOUR操作,因此您的视图必须执行如下操作:返回HttpResponseReDirect(Reverse(‘auth_LOGIN’)+‘?Next=/Youraction)

I am understanding that I'll have to write this statement. But I still don't know where I have to write them? Like somewhere in the urls.py modules or in the views module...

我明白我必须写这份声明。但我还是不知道要写在哪里?比如在urls.py模块或视图模块中的某个地方.

@ruddra is this how you meant to use it: path('login/', auth_views.LoginView(template_name='dev_user/login.html', redirect_field_name=HttpResponseRedirect(reverse('auth_login') + '?next=/youraction')), name='dev-login'),

@Ruddra您是这样使用它的吗:Path(‘LOGIN/’,auth_views.LoginView(template_name=‘dev_user/login.html’,redirect_field_name=HttpResponseRedirect(reverse(‘auth_login’)+‘?Next=/Youraction’),name=‘dev-LOGIN’),

优秀答案推荐

I am grateful to all the people who answered. Though my original query was not solved, I did find a get around to do a login. Here's what I did for others to implement if they're stuck in a similar situation:
(views.py):

我感谢所有回答问题的人。虽然我最初的问题没有得到解决,但我确实找到了一个办法来登录。以下是我为其他人在遇到类似情况时所做的实现:(views.py):


def Login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return redirect('dev-profile')

return render(request, 'client_user/login.html')

(template):

(模板):


{% extends "home/base.html" %}
{% block content %}
{% load crispy_forms_tags %}

<div class="separator-row">
<div class="col-sm-12 col-md-4">
<div class="add-padding">
<form method="POST">
<fieldset>
{% csrf_token %}
<legend><h2 class="signup-info-title">Welcome Back Hirer!</h2></legend>
<div id="div_id_username" class="form-group">
<label for="username" class=" requiredField">
Username
<span class="asteriskField">*</span>
</label>
<div class="">
<input type="text" name="username" autofocus="" autocapitalize="none" autocomplete="username" maxlength="150" class="textinput textInput form-control" required="" id="username">
</div>
</div>
<div id="div_id_password" class="form-group">
<label for="password" class=" requiredField">
Password
<span class="asteriskField">*</span>
</label>
<div class="">
<input type="password" name="password" autocomplete="current-password" class="textinput textInput form-control" required="" id="password">
</div>
</div>
</fieldset>
<button class="login-buttons" type="submit">Login</button>
<hr>
<div class="login-footers">
<p class="text-muted">Don't have an account? <a href="">Sign up</a> as a Hirer!</p>
<p class="text-muted">Not a Hirer? <a href="">Login</a> or <a href="">Sign Up</a> as a Dev</p>
</div>
</form>
</div>
</div>
</div>

{% endblock %}

Also if you have an answer to the original query, please do answer!

另外,如果你对原来的问题有答案,请一定要回答!



You can try something like this (in your views):

您可以尝试这样的操作(在您的观点中):


@login_required
def custom_redirect(request):
if request.user.dev.filter(BaseSkills='xxx'):
return redirect('xxx')
elif request.user.dev.filter(BaseSkills='xxx'):
return redirect('xxx')

Also note that best practise is to have model field names in lowercase, using underscores instead of camelCase.

另请注意,最佳做法是使用小写的模型字段名称,使用下划线而不是CamelCase。



This is how I could change the redirect_field_name:

以下是我更改REDIRECT_FIELD_NAME的方法:


return login_required(view_func, redirect_field_name="return_to")(request, *view_args, **view_kwargs)

Full Sample code:

完整的示例代码:


from django.contrib.auth.decorators import login_required


def login_exempt(view):
view.login_exempt = True
return view


class LoginRequiredMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
return self.get_response(request)

def process_view(self, request, view_func, view_args, view_kwargs):
if getattr(view_func, 'login_exempt', False):
return

if request.user.is_authenticated:
return

return login_required(view_func, redirect_field_name="return_to")(request, *view_args, **view_kwargs)

更多回答

Thanks for attempting to answer. I am grateful for that gesture. But it seems you have misunderstood some of the part maybe because my question's incomplete. I'll add some other snippets so that it is clear.

感谢您尝试回答。我对这一姿态表示感谢。但你似乎误解了其中的某些部分,可能是因为我的问题不完整。我将添加一些其他代码片段,这样就清楚了。

Though your answer does seem to answer my queries, I am still unclear where I should use this snippet example (i,e in the views of both apps or somewhere else).

虽然你的回答似乎确实回答了我的问题,但我仍然不清楚我应该在哪里使用这个代码片段示例(即在两个应用程序的视图中还是在其他地方)。

In your views. I didn't know what different user types you meant, it wasn't clear in your question. So are the different users Dev and Hirer?

在你看来。我不知道你指的是什么不同的用户类型,在你的问题中不清楚。那么不同的用户是Dev和Hirer吗?

Yes. I am sorry for the incomplete question. I have added new snippets so that it can be more clear. Also, comment whatever else that might be hard to understand so that I can improve the question (as I am just beginning, my coding conventions may be very hard to understand).

是。很抱歉,我的问题不完整。我添加了新的代码片段,以便它可以更清晰。此外,评论任何其他可能难以理解的内容,以便我可以改进这个问题(因为我才刚刚开始,我的编码约定可能很难理解)。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com