Django 新手并遇到问题。我正在尝试配置我的项目,以便当用户登录时,他们被重定向到 account/profile/ + username + / 。我假设我错过了一些基本的东西,但还没有确定下来。我提前感谢任何帮助。
编辑 忘了提到我有 LOGIN_REDIRECT_URL = 'accounts:profile' 并且我收到的错误消息是:
NoReverseMatch at /accounts/login/ 为“profile”反向,未找到任何参数。尝试了 1 种模式:['accounts/profile/(?P[-a-zA-Z0-9_]+)/$']
结束编辑
模型.py
class User(auth.models.User, auth.models.PermissionsMixin):
def __str__(self):
return '@{}'.format(self.username)
class Meta:
db_table = 'users'
网址.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')
]
视图.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})
登录.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 %}