1

When a user clicks 'login' I want them to be logged in and redirected to i.e., www.exampledomain.com/accounts/usernameGoesHere/

EDIT:: I changed my url regex pattern to accept an empty string like so:

url(r'^$|(?P<username>[0-9a-zA-Z._]+)/$', login_required(views.IndexView.as_view()), name = 'index'),

now whenever I login to the django admin backend first then navigate to http://localhost:8000/accounts/FlashBanistan/ or http://localhost:8000/accounts/ the page renders as it should but exactly the same which tells me the username is getting lost on it's way somewhere.

Here are my top level urls:

from django.conf.urls import url, include
from django.contrib import admin

# Namespace URLs
app_name = "pto_request"

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^accounts/', include('accounts.urls')),
]

and here are the urls for accounts:

from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from accounts.views import (login_view, register_view, logout_view)
from . import views

app_name = 'accounts'

urlpatterns = [
    # root url will look like www.website.com/accounts/

    url(r'^login/$', login_view, name='login'),
    url(r'^logout/$', logout_view, name='logout'),
    url(r'^register/$', register_view, name='register'),
    url(r'^(?P<username>[0-9a-zA-Z._]+)/$', login_required(views.IndexView.as_view()), name = 'index'),
]

This is my login view:

def login_view(request):
    title = "Login"
    user_form = UserLoginForm(request.POST or None)
    if user_form.is_valid():
        username = user_form.cleaned_data.get('username')
        password = user_form.cleaned_data.get('password')
        user = authenticate(username=username, password=password)
        login(request, user)
        return redirect(reverse('accounts:index', args=[username]))
    return render(request, 'form.html', {'user_form':user_form, 'title':title})

This is my login form:

class UserLoginForm(forms.Form):
    # Define form fields to include.
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)
    # Check if user exists and logs in.
    def clean(self, *args, **kwargs):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')
        if username and password:
            user = authenticate(username=username, password=password)
            if not user:
                raise forms.ValidationError('Username or password is incorrect.')

        return super(UserLoginForm, self).clean(*args, **kwargs)

and finally this is the traceback log of the error I am receiving:

Environment:


Request Method: GET
Request URL: http://localhost:8000/accounts/FlashBanistan/

Django Version: 1.10.5
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'crispy_forms',
 'datetimewidget',
 'accounts']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.locale.LocaleMiddleware']


Template error:
In template C:\django projects\PTO\accounts\templates\accounts\index.html, error at line 0
   Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['accounts/(?P<username>[0-9a-zA-Z._]+)/$']   1 : {% extends 'base.html' %}
   2 : {% load crispy_forms_tags %}
   3 : 
   4 : {% block content %}
   5 : 
   6 : {{ form.media }}
   7 : 
   8 : 
   9 : <div class="container">
   10 :   <div id="calendar">


Traceback:

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py" in inner
  39.             response = get_response(request)

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  217.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  215.                 response = response.render()

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\response.py" in render
  109.             self.content = self.rendered_content

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\response.py" in rendered_content
  86.         content = template.render(context, self._request)

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\backends\django.py" in render
  66.             return self.template.render(context)

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py" in render
  208.                     return self._render(context)

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py" in render
  994.                 bit = node.render_annotated(context)

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py" in render_annotated
  961.             return self.render(context)

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\loader_tags.py" in render
  174.         return compiled_parent._render(context)

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py" in _render
  199.         return self.nodelist.render(context)

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py" in render
  994.                 bit = node.render_annotated(context)

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py" in render_annotated
  961.             return self.render(context)

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\defaulttags.py" in render
  315.                 return nodelist.render(context)

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py" in render
  994.                 bit = node.render_annotated(context)

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\base.py" in render_annotated
  961.             return self.render(context)

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\template\defaulttags.py" in render
  439.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\base.py" in reverse
  91.     return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\resolvers.py" in _reverse_with_prefix
  392.             (lookup_view_s, args, kwargs, len(patterns), patterns)

Exception Type: NoReverseMatch at /accounts/FlashBanistan/
Exception Value: Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['accounts/(?P<username>[0-9a-zA-Z._]+)/$']
FlashBanistan
  • 426
  • 1
  • 9
  • 25
  • Possible duplicate of [What is a NoReverseMatch error, and how do I fix it?](http://stackoverflow.com/questions/38390177/what-is-a-noreversematch-error-and-how-do-i-fix-it) – Sayse Jan 13 '17 at 18:38
  • and for what it's worth i've done "reverse('accounts:index', args=[username])" in the shell and it appears to work fine. No errors are generated. – FlashBanistan Jan 13 '17 at 18:50
  • please try kwargs instead of args since you use a named regex to capture the username: return redirect(reverse('accounts:index', kwargs={'username': username})) – Jingo Jan 13 '17 at 18:50
  • Oh yes I'm sure it would because I believe the problem is that `cleaned_data.get('username')` is returning None in the above code. Just not sure why yet.. – Sayse Jan 13 '17 at 18:51
  • @Jingo I replaced args with kwargs in my login_view function and it didn't change anything. – FlashBanistan Jan 13 '17 at 18:53
  • @Sayse Thanks, I removed it and you're right, it didn't fix the issue. Here is the project on github if it helps. https://github.com/FlashBanistan/pto – FlashBanistan Jan 13 '17 at 18:58
  • Can you try changing it in your view to `username = self.cleaned_data.get('username', 'foo')`? This will at least tell you whether or not it is username being None thats the problem – Sayse Jan 13 '17 at 19:04
  • @Sayse Do you want to look at my edit and tell me what you think? – FlashBanistan Jan 13 '17 at 21:57
  • Django [can't handle](https://github.com/django/django/blob/master/django/utils/regex_helper.py#L98) disjunct patterns outside capture groups, so changing it to `r'^$|(?P[0-9a-zA-Z._]+)/$'` will surely prevent you from ever reversing the url. – knbk Jan 13 '17 at 22:18
  • @knbk I'm not going to keep it that way. I just found that 'username' was empty somewhere based on my error so I changed the url to accept an empty string. Once i'm already logged into the system I can then navigate to /accounts/Flashbanistan and it works. This is where I currently am stuck. – FlashBanistan Jan 13 '17 at 22:22

1 Answers1

0
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^accounts/', include('accounts.urls', namaspace="accounts")),
]

You can use 'accounts:index' when use namepsace

  • This won't solve the issue since Django is already able to find the correct url so the url name isn't the problem. – Sayse Jan 13 '17 at 18:47