Reverse for 'record' with arguments '('',)' not found. 1 pattern(s) tried: ['record/(?P<pk>[^/]+)\\Z']

Views.py file:

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from .models import Record
from .forms import AddRecordForm

# Create your views here.
def home(request):
    records = Record.objects.all()[:10]
    print(records)
    if request.method == 'POST':
        username = request.POST['username'].lower().strip().removesuffix('@sanimabank.com')
        password = request.POST['password']
        print(f'Username is {username}')
        print(f'Password is {password}')
        user = authenticate(request, username=username, password = password)
        print(f'User is {user}')
        #user = check_login(username, password)
        if user is not None:
            login(request, user)
            messages.success(request, "You Have Been Logged In")
            return redirect('home')
        else:
            messages.success(request, "Error Logging in. Please try again with correct credentials.")
            return redirect('home')
        
    return render(request, 'home.html', {'records':records})
    
    

def customer_record(request,pk):
    if request.user.is_authenticated:
        #look up_records
        customer_record = Record.objects.get(email=pk)
        print(f'Customer record is {customer_record}')
        return render(request,'record.html',{'customer_record':customer_record})
    else:
        messages.success(request, "Login First to view this page")
        return redirect('home')
    
def logout_user(request):
    logout(request)
    messages.success(request, "You have been Logged Out....")
    return redirect('home')

def update_record(request, pk):
    if request.user.is_authenticated:
        current_record = Record.objects.get(email=pk)
        print(f'pk is {pk}')
        print(f'current record is {current_record}')
        print(f'current record email is {current_record.email}')
        print(f'current users email is {request.user.email}')
        print(f'current users username is {request.user.username}')
        
        if (request.user.email == pk) or (request.user.username == 'admin'):
            print('USER OK TO UPDATE')
            return redirect('home')
        else:
            messages.success(request, "Not Allowed!! You can update only your own record.")
            return redirect('home')
# =============================================================================
#             print("NOT OK TO UPDATE")
#             return redirect('record')

# =============================================================================
    else:
        messages.success(request, "You must be logged in first to make changes here")
        return redirect('home')
    
    
def add_record(request):
    form = AddRecordForm(request.POST or None)
    if request.user.is_authenticated:
        if request.method == "POST":
            if form.is_valid():
                add_record = form.save()
                messages.success(request, "Record Addded Successfully")
                return redirect('home')
        return render(request,'add_record.html',{'form':form})
    else:
        messages.success(request, "YOU MUST BE LOGGED IN ")
        return redirect('home')

home.html

{% extends 'base.html' %}
{% block content %}

{% if user.is_authenticated %}

<H1> AFTER LOGIN </H1>
<table class="table table-striped table-hover table-bordered">
  <thead class ="table-dark">
    <tr>
      
      <th scope="col">NAME</th>
      <th scope="col">Email_ID</th>
      <th scope="col">SIP_Number</th>
    </tr>
  </thead>
  <tbody>

{% if records  %}
    {% for record in records %}
    <tr>
        <td>{{record.first_name}} {{record.last_name}}</td>
        <td><a href = "{% url 'record' record.email %}">{{record.email}}</a></td>
        <td>{{record.SIP_number}}</td>
        
    </tr>

    {% endfor %}

{% endif %}

</tbody>
</table>


{% else %}

<h1>LOGIN PAGE </h1>

<H1> Login to the SIP Directory </H1>
<br/>
<form method ="POST" action = "{% url 'home' %}">
        {% csrf_token %}
<form>


  <div class="mb-3">
    
    <input type="text" class="form-control" name ="username", placeholder = "Username"  required>
  </div>
  <div class="mb-3">
    
    <input type="password" class="form-control" name ="password", placeholder = "Password" required>
  </div>
 
  <button type="submit" class="btn btn-primary">Login</button>
</form>
</form>

{% endif %}

{% endblock %}

urls.py file:

# -*- coding: utf-8 -*-

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('record/<str:pk>', views.customer_record, name='record'),
    path('logout/', views.logout_user, name='logout'),
    path('update_record/<str:pk>', views.update_record, name='update_record'),
    ]

models.py file

from django.db import models

# Create your models here.

class Record(models.Model):
    
    created_at = models.DateTimeField(auto_now_add=True)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    branch = models.CharField(max_length=50)
    staff_id = models.CharField(max_length=6) 
    department_name = models.CharField(max_length=40) 
    designation = models.CharField(max_length=40)
    email = models.CharField(max_length=100, unique=True, primary_key=True)
    SIP_number = models.CharField(max_length=6, blank= True)
    Landline_Number = models.CharField(max_length=15, blank= True)
    
    
    def __str__(self):
        return(f"{self.first_name} {self.last_name}")

Side note: When posting code, templates, or error messages here, enclose the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted. (I’ve taken the liberty of fixing your original post for you.) The “blockquote” tag here doesn’t do you any good.

Which view being executed is causing this error?

Also, it’s generally more helpful if you post the complete error with the traceback as it is displayed in the server console. (Not what gets displayed in the browser.)

Thank you for your suggestions sir.
The view that is causing the error is ‘home’.

The complete trace is:

System check identified no issues (0 silenced).
March 03, 2024 - 21:16:17
Django version 5.0.1, using settings 'new.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

HERO HERO
[03/Mar/2024 21:16:27] "GET / HTTP/1.1" 200 2918
HERO HERO
Username is abhishek.poudel
Password is san#12345
User is abhishek.poudel
[03/Mar/2024 21:16:37] "POST / HTTP/1.1" 302 0
HERO HERO
Internal Server Error: /
Traceback (most recent call last):
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\Documents\OFFICE_STUDY\ELASTICSEARCH\DJANGO_TEST\new\auth_app\views.py", line 28, in home
    return render(request, 'home.html', {'records':records})
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\shortcuts.py", line 24, in render
    content = loader.render_to_string(template_name, context, request, using=using)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\backends\django.py", line 61, in render
    return self.template.render(context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 171, in render
    return self._render(context)
           ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 163, in _render
    return self.nodelist.render(context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 1000, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 1000, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 961, in render_annotated
    return self.render(context)
           ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\loader_tags.py", line 159, in render
    return compiled_parent._render(context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 163, in _render
    return self.nodelist.render(context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 1000, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 1000, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 961, in render_annotated
    return self.render(context)
           ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\loader_tags.py", line 65, in render
    result = block.nodelist.render(context)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 1000, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 1000, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 961, in render_annotated
    return self.render(context)
           ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\defaulttags.py", line 325, in render
    return nodelist.render(context)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 1000, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 1000, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 961, in render_annotated
    return self.render(context)
           ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\defaulttags.py", line 325, in render
    return nodelist.render(context)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 1000, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 1000, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 961, in render_annotated
    return self.render(context)
           ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\defaulttags.py", line 241, in render
    nodelist.append(node.render_annotated(context))
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\base.py", line 961, in render_annotated
    return self.render(context)
           ^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\template\defaulttags.py", line 478, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\urls\base.py", line 88, in reverse
    return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\abhishek.poudel\AppData\Local\anaconda3\Lib\site-packages\django\urls\resolvers.py", line 848, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'record' with arguments '('',)' not found. 1 pattern(s) tried: ['record/(?P<pk>[^/]+)\\Z']
[03/Mar/2024 21:16:37] "GET / HTTP/1.1" 500 205450

The browser error:

The error is being thrown at this line in the template:

<td><a href = "{% url 'record' record.email %}">{{record.email}}</a></td>

It’s being caused by the email field being blank or null - there’s no parameter being passed to the url tag to create the reversed url. You have an entry in that model where the email field has not been set.

Side note: It’s generally unwise to overload functionality of your views. In the common case, the best practice would be to have a login view that is independent of your home view.

1 Like

Sir, I guess this first record is causing the issue.

I deleted the record from the DB. Now the site is working as expected.

Thank you very much Sir.