Django的新手,遇到了问题。我正在尝试配置我的项目,以便在用户登录时将他们重定向到account / profile / + username + /。我以为我错过了一些基本知识,但还无法确定。在此先感谢您的帮助。
已编辑 忘了提我有LOGIN_REDIRECT_URL ='accounts:profile'并且我收到的错误消息是:
在/ accounts / login /下的NoReverseMatch 反向查找“ profile”,未找到任何参数。尝试了1种模式:['帐户/个人资料/(?P [-a-zA-Z0-9 _] +)/ $']
结束编辑
models.py
class User(auth.models.User, auth.models.PermissionsMixin):
def __str__(self):
return '@{}'.format(self.username)
class Meta:
db_table = 'users'
urls.py
app_name = 'accounts'
urlpatterns = [
path('signup/', views.SignUp.as_view(), name='signup'),
path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(next_page='/'), name='logout'),
path('profile/<slug:slug>/', views.Profile.as_view(), name='profile')
]
views.py
class SignUp(CreateView):
form_class = forms.UserCreateForm
success_url = reverse_lazy('login')
template_name = 'accounts/signup.html'
class Profile(DetailView, LoginRequiredMixin):
model = models.User
slug_field = 'username'
def get_context_data(self, request, **kwargs):
context = super().get_context_data(**kwargs)
context['username'] = request.user.username
return context
def get_success_url(self):
return reverse_lazy('accounts:profile', kwargs={'slug': self.username})
login.html
{% extends 'base.html' %}
{% load bootstrap4 %}
{% block bodyblock %}
<div class="container">
<h1>Header Here</h1>
<form class="login-form" method="POST">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" value="Log In">
</form>
</div>
{%endblock%}
profile.html
{% extends 'base.html' %}
{% block bodyblock %}
<div class="container">
<h1>Welcome {{user.username}} !</h1>
</div>
{% endblock %}
答案 0 :(得分:0)
默认情况下,django使用next
的GET参数确定登录后重定向到的位置。如果要禁用此功能,请将redirect_field_name
设置为None
(其值不是RHSmith159指出的URL-这是一个字段名称,默认值为next
)。还可以使用settings.LOGIN_REDIRECT_URL
指定标准重定向目标(默认为/accounts/profile/
)-这是您当前正在观察的内容。