0

New to Django and running into a problem. I'm trying to configure my project so that when a user logs in, they are redirected to account/profile/ + username + / . I'm assuming I'm missing something fundamental but haven't been able to nail it down yet. My appreciation in advance for any help.

edited Forgot to mention I have LOGIN_REDIRECT_URL = 'accounts:profile' and that the error message I'm getting is:

NoReverseMatch at /accounts/login/ Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['accounts/profile/(?P[-a-zA-Z0-9_]+)/$']

end edit

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 %}
ecdnj
  • 21
  • 6

1 Answers1

1

by default, django uses a next GET parameter to determine where to redirect after logging in. If you want to disable this, set redirect_field_name to None (its value is not a URL as RHSmith159 states - it is a field name, the default is next). Also use settings.LOGIN_REDIRECT_URL to specify a standard redirect target (default is /accounts/profile/) - this is what you are currently observing.

dngrs
  • 269
  • 1
  • 4
  • 1
    `settings.LOGIN_REDIRECT_URL` lets you redirect to a fixed URL, e.g. `/accounts/profile/`. @ecdnj wants vary the URL depending on the username. – Alasdair Dec 17 '18 at 17:05