title: Reverse for 'post_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<slug>[-\\w]+)/$']
body: <p><strong>Using Django 1.11</strong>|
  Having this issue, I thought it was because I copied some urls and views from another project, but even after deleting, the issue reappeared. I just was trying to remove my PostImg field and add a the image field as a FileField, but got issues for not having the postImg field even after deleting the database and all migrations etc.
  This issue only occurs when I have no posts (not object of the model Post) in my database. I can log into admin no problem, then create a post, and then it works. I think it's because I', displaying all posts with template tags and somehow these tags can't handle it if there are no objects.</p>
  
  <p>Note: I had trouble adding slugs, but I found a nice way (I will not have any duplicate blog titles). However, this issue occured even before I added slugs.</p>
  
  <p><strong>base.html</strong></p>
  
  <pre><code>{% load staticfiles %}
  &lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
  
    &lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"&gt;
    &lt;link rel="stylesheet" href="{% static 'css/main.css' %}"&gt;
    &lt;script src="//cdn.jsdelivr.net/medium-editor/latest/js/medium-editor.min.js"&gt;&lt;/script&gt;
      &lt;link rel="stylesheet" href="//cdn.jsdelivr.net/medium-editor/latest/css/medium-editor.min.css" type="text/css" media="screen" charset="utf-8"&gt;
    &lt;script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"&gt;&lt;/script&gt;
    &lt;script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"&gt;&lt;/script&gt;
    &lt;script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"&gt;&lt;/script&gt;
  &lt;title&gt;
   Base working  
  &lt;/title&gt;
  &lt;head&gt;
  &lt;body&gt;
    &lt;div class="container"&gt;
      &lt;img class="top_logo" src="https://electrek.co/wp-content/uploads/sites/3/2018/08/SX3Semi-Family-e1534526883239.jpg?quality=82&amp;strip=all&amp;w=1600"&gt;
    &lt;/div&gt;
    &lt;nav class="navbar navbar-expand-md navbar-light bg-light"&gt;
      &lt;div class="container"&gt;
        &lt;a class="navbar-brand" href="{% url 'blog:home' %}"&gt;Home&lt;/a&gt;
        &lt;button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"&gt;
          &lt;span class="navbar-toggler-icon"&gt;&lt;/span&gt;
        &lt;/button&gt;
  
        &lt;div class="collapse navbar-collapse" id="navbarSupportedContent"&gt;
          &lt;ul class="navbar-nav mr-auto"&gt;
            &lt;li class="nav-item"&gt;
              &lt;a class="nav-link" href="{% url 'blog:post_list' %}"&gt;Archive&lt;/a&gt;
            &lt;/li&gt;
            &lt;li class="nav-item dropdown"&gt;
              &lt;a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"&gt;
                Dropdown
              &lt;/a&gt;
              &lt;div class="dropdown-menu" aria-labelledby="navbarDropdown"&gt;
                &lt;a class="dropdown-item" href="#"&gt;Action&lt;/a&gt;
                &lt;a class="dropdown-item" href="#"&gt;Another action&lt;/a&gt;
                &lt;div class="dropdown-divider"&gt;&lt;/div&gt;
                &lt;a class="dropdown-item" href="#"&gt;Something else here&lt;/a&gt;
              &lt;/div&gt;
            &lt;/li&gt;
            &lt;li class="nav-item"&gt;
              &lt;a class="nav-link" href="#" tabindex="-1" aria-disabled="true"&gt;&lt;/a&gt;
            &lt;/li&gt;
          &lt;/ul&gt;
          &lt;ul class="navbar-nav navbar-right"&gt;
            &lt;li class="nav-item"&gt;
              {% if user.is_authenticated %}
                &lt;a class="nav-link" href="{% url 'logout' %}"&gt;Log Out&lt;/a&gt;
              {% else %}
                &lt;a class="nav-link" href="{% url 'login' %}"&gt;Log In&lt;/a&gt;
              {% endif %}
            &lt;/li&gt;
            {% if not user.is_authenticated %}
              &lt;li class="nav-item"&gt;
                &lt;a class="nav-link" href="{% url 'register' %}"&gt;Sign up&lt;/a&gt;
              &lt;/li&gt;
            {% endif %}
          &lt;/ul&gt;
          &lt;form class="form-inline my-2 my-lg-0"&gt;
            &lt;input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"&gt;
            &lt;button class="btn btn-outline-success my-2 my-sm-0" type="submit"&gt;Search&lt;/button&gt;
          &lt;/form&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/nav&gt;
  &lt;div class="container"&gt;
    {% if messages %}
      {% for message in messages %}
      &lt;div class="alert alert-{{ message.tags }}"&gt; {{ message }} 
      &lt;/div&gt;
      {% endfor %}
    {% endif %}
  &lt;/div&gt;
  &lt;main role="main" class="container"&gt;
    &lt;div class="row"&gt;
      &lt;div class="col-lg-9 customcontainer"&gt;
        {% block content %}
        {% endblock %}
      &lt;/div&gt;
  
      &lt;!-- SideBar --&gt;
      &lt;div class="col-sm d-none d-lg-block"&gt;
      &lt;article class="info_box"&gt;
        BONUS TEXT
        asdgfdg gararg rsiogj origj  g grjiog orej greiog jreaoig jaeorig jioareg joiareg jioaergj ioaergjio
      &lt;/article&gt;
      &lt;br/&gt;
      &lt;article class="info_box"&gt;
        BONUS TEXT
        asdgfdg gararg rsiogj origj  g grjiog orej greiog jreaoig jaeorig jioareg joiareg jioaergj ioaergjio
      &lt;/article&gt;
      &lt;br/&gt;
      &lt;article class="info_box"&gt;
        BONUS TEXT
        asdgfdg gararg rsiogj origj  g grjiog orej greiog jreaoig jaeorig jioareg joiareg jioaergj ioaergjio
      &lt;/article&gt;
      &lt;br/&gt;
      &lt;a href="https://www.tesla.com/models"&gt;
        &lt;img class="sidebar_img_link" src="https://www.tesla.com/sites/tesla/files/carousel/image/charger-1%402.jpg"&gt;
      &lt;/a&gt;
    &lt;/div&gt;
  
  
  
    &lt;/div&gt;
  &lt;/main&gt;
  
  
  
  &lt;footer class="home_footer"&gt;
    &lt;div class="container"&gt;
      &lt;div class="row"&gt;
        &lt;div class="footer_item col-sm"&gt;
          &lt;a href="#"&gt;Contact Us&lt;/a&gt;
        &lt;/div&gt;
        &lt;div class="footer_item col-sm"&gt;
          &lt;h4 class=""&gt;Copyright &lt;/h4&gt;
        &lt;/div&gt;
        &lt;div class="footer_item col-sm"&gt;
          &lt;a href=""&gt;Partner with me&lt;/a&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/footer&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>home.html</strong> (the page I'm trying to access)</p>
  
  <pre><code>{% extends 'blog/base.html' %}
  {% block content %}
  
  
  &lt;div class="intro_text"&gt;
      &lt;h3&gt;Hello and welcome!&lt;/h3&gt;
      &lt;article&gt;
          this is the official PhyBlog! We talk about all thing physics and engineering here, mainly concerning the environment and global heating,
      &lt;/article&gt;
  &lt;/div&gt;
  &lt;br&gt;
  &lt;div class="home_text"&gt;
      &lt;div class="latest_post"&gt;
          {% with post_list|first as post  %}
          &lt;img class=" home_post_img" src="{{ post.postImg }}"&gt;
  
              &lt;h2&gt;&lt;a class="post_title_a" href="{% url 'blog:post_detail' post.slug %}"&gt;{{ post.title }}&lt;/a&gt;&lt;/h2&gt;
              &lt;article class="intro_text"&gt;{{ post.text|safe|truncatewords:20 }}&lt;/article&gt; &lt;a class="post_more_a" href="{% url 'blog:post_detail' post.slug %}"&gt;mehr lesen&lt;/a&gt;
              &lt;p class="post_list_pub"&gt;Posted: {{ post.published_date }}&lt;/p&gt;
  
          {% endwith %}
      &lt;/div&gt;
  &lt;/div&gt;
  &lt;br&gt;
   &lt;h1&gt;Hello and welcome on the Homepage!&lt;/h1&gt;
   &lt;div class="filler"&gt;
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut est lorem, congue sed eleifend ac, luctus non mauris. Praesent scelerisque quam eu metus tristique, eu luctus ligula dictum. Sed eu felis aliquam, maximus enim sed, tempus turpis. Cras et sapien lacus. Mauris nec enim mollis, pulvinar augue vel, mollis elit. Fusce nec sem finibus lorem imperdiet tempus eu eget purus. Donec ac sagittis est. Phasellus vitae vehicula lacus. Nulla facilisi. &lt;br/&gt;
  
      Pellentesque odio dui, finibus vitae nunc slug, varius cursus risus. Etiam mollis augue a vulputate venenatis. Nulla et purus vestibulum, hendrerit mauris slug, dignissim ligula. Vivamus ut arcu vehicula, vehicula ante vel, aliquam sem. Pellentesque at maximus quam. Nunc condimentum erat eu tellus suscipit, ut finibus ipsum semper. Ut rhoncus vel metus sed rutrum. Fusce tellus odio, auctor non lacus sit amet, sagittis gravsluga enim. Praesent porttitor dui nec metus vulputate, sit amet vulputate urna ornare.&lt;br/&gt;
  
      Curabitur lacinia ut tellus eu scelerisque. In hac habitasse platea dictumst. Fusce pulvinar egestas nibh sed porttitor. Nulla consectetur massa ut mattis vehicula. Nullam tempus mattis enim, sit amet fermentum massa varius sit amet. Nullam slug sem vel sem luctus scelerisque vel vel nisi. Ut ultrices vel dui semper dapibus. Proin velit lacus, vehicula ac tincslugunt in, aliquam ac arcu.&lt;br/&gt;
  
      Cras nec quam blandit, facilisis justo nec, faucibus quam. Cras sed lobortis augue. Fusce justo mauris, commodo egestas ornare sed, porta slug lectus. Sed nulla nibh, molestie vitae faucibus nec, vulputate tristique ipsum. Etiam hendrerit nisi diam, pulvinar rutrum diam viverra in. Donec blandit metus in nibh tristique tempor. Proin rhoncus dolor sed lorem convallis, eu vehicula quam congue. Sed scelerisque tellus ac tellus semper laoreet. Maecenas laoreet vehicula congue. Cras imperdiet egestas tellus, in porttitor nulla tempus quis. Proin gravsluga nibh ut nunc tincslugunt, non venenatis nisl mattis. Morbi efficitur congue nunc. Proin hendrerit ipsum non orci finibus, et ultricies massa finibus. In sodales, massa slug elementum elementum, quam lectus consequat lectus, nec ornare justo augue sit amet sem. Praesent ac porta ligula.&lt;br/&gt;
  
      Etiam augue quam, aliquet vel mi ut, vestibulum congue tortor. Aliquam congue, nunc a auctor mollis, elit tellus aliquam augue, at ornare ante nisi slug lectus. Praesent quis semper mi. Nulla scelerisque lacus ut nisl molestie aliquet. Morbi lobortis tincslugunt felis, ac gravsluga erat. Aenean eu tristique elit. Quisque malesuada lacus in sem dictum, quis faucibus mi euismod. Quisque ut ante ut nibh laoreet venenatis.&lt;br/&gt;
   &lt;/div&gt;
  &lt;br/&gt;
  
  &lt;h1&gt;Recent posts:&lt;/h1&gt;
  
  &lt;div class="posts"&gt;
      &lt;div class="popular_posts"&gt;
          {% for post in post_list %}
          &lt;div class="post_homepage row"&gt;
              &lt;img class="col-xs home_post_list_img" src="{{ post.postImg }}"&gt;
              &lt;div class="col-lg"&gt;
                  &lt;h2&gt;&lt;a class="post_title_a" href="{% url 'blog:post_detail' post.slug %}"&gt;{{ post.title }}&lt;/a&gt;&lt;/h2&gt;
                  &lt;article class="intro_text"&gt;{{ post.text|safe|truncatewords:50 }}&lt;/article&gt; &lt;a class="post_more_a" href="{% url 'blog:post_detail' post.slug %}"&gt;mehr lesen&lt;/a&gt;
                  &lt;p class="post_list_pub"&gt;Posted: {{ post.published_date }}&lt;/p&gt;
              &lt;/div&gt;
          &lt;/div&gt;
          &lt;br&gt;
          {% endfor %}
      &lt;/div&gt;
  &lt;/div&gt;
  
  {% endblock %}
  
  </code></pre>
  
  <p><strong>blog/views.py</strong></p>
  
  <pre><code>from django.utils import timezone
  from blog.models import Post, Comment
  from blog.forms import PostForm, CommentForm    
  from django.views.generic import (TemplateView,
                                    ListView,
                                    DetailView,)
  
  class HomeView(ListView):
      template_name = "home.html"
      model = Post
  
  
      def get_queryset(self):
          return Post.objects.all().order_by('-published_date')
  
  
  class PostListView(ListView):
      model = Post
  
      def get_queryset(self):
          return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
  
  class PostDetailView(DetailView):
      model = Post
      slug_field = 'slug'
  
  
  </code></pre>
  
  <p><strong>blog/urls.py</strong></p>
  
  <pre><code>from . import views
  from django.conf.urls import url
  
  urlpatterns = [
      url(r'^$', views.HomeView.as_view(), name="home"),
      url(r'^posts/$', views.PostListView.as_view(), name="post_list"),
      url(r'^post/(?P&lt;slug&gt;[-\w]+)/$', views.PostDetailView.as_view(),name="post_detail"),
  ]
  </code></pre>
  
  <p>models.py</p>
  
  <pre><code>from django.db import models
  from django.utils import timezone
  from django.urls import reverse
  from django.db.models.signals import pre_save
  from django.utils.text import slugify
  
  
  class Post(models.Model):
      author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
      title = models.CharField(max_length=200)
      teaser_text = models.CharField(max_length=300, default="",blank=True,null=True)
      text = models.TextField()
      slug = models.SlugField(max_length=200, null=True, blank=True)
      image = models.FileField(null=True, blank=True)
      postImg = models.CharField(max_length=5000, null=True, blank=True)
      created_date = models.DateTimeField(
              default=timezone.now)
      published_date = models.DateTimeField(
              blank=True, null=True)
  
      def publish(self):
          self.published_date = timezone.now()
          self.save()
  
      def approve_comments(self):
          return self.comments.filter(approved_comment=True)
  
      def get_absolute_url(self):
          return reverse('blog:post_detail',kwargs={'pk':self.pk})
  
      def __str__(self):
          return self.title
  
  def slug_generator(sender, instance, *args, **kwargs):
      if not instance.slug:
          instance.slug = slugify(instance.title)
  
  pre_save.connect(slug_generator, sender=Post)
  
  class Comment(models.Model):
      post = models.ForeignKey('blog.Post', related_name='comments', on_delete=models.CASCADE)
      author = models.CharField(max_length=200)
      text = models.TextField()
      created_date = models.DateTimeField(default=timezone.now)
      approved_comment = models.BooleanField(default=False)
  
      def approve(self):
          self.approved_comment = True
          self.save()
  
      def get_absolute_url(self):
          return reverse("post_list")
  
      def __str__(self):
          return self.text
  </code></pre>
  
  <p><strong>urls.py of the project</strong></p>
  
  <pre><code>from django.conf.urls import url
  from django.contrib.auth import views as auth_views
  from django.contrib import admin
  from django.conf.urls import include
  from users import views as user_views
  
  urlpatterns = [
      url(r'^admin/', admin.site.urls),
      url(r'^', include(("blog.urls", "blog"), namespace="blog")),
      url(r'^register/', user_views.register, name="register"),
      url(r'^profile/', user_views.profile, name="profile"),
      url(r'^login/', auth_views.LoginView.as_view(template_name="users/login.html", redirect_authenticated_user=True), name="login"),
      url(r'^logout/', auth_views.LogoutView.as_view(template_name="users/logout.html"), name="logout"),
  ]
  
  </code></pre>
  
  <p>settings.py</p>
  
  <pre><code>import os
  
  # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  TEMPLATE_DIR = os.path.join(BASE_DIR,'blog/templates/blog')
  
  # Quick-start development settings - unsuitable for production
  # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
  
  # SECURITY WARNING: keep the secret key used in production secret!
  SECRET_KEY = '$j+l6i#857mae-*onf%=i7zta&amp;l&amp;bbxt8^bso4_376b9cr3@h1'
  
  # SECURITY WARNING: don't run with debug turned on in production!
  DEBUG = True
  
  ALLOWED_HOSTS = ["127.0.0.1", "www.pythonanywhere.com"]
  
  
  # Application definition
  
  INSTALLED_APPS = [
      'django.contrib.admin',
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.messages',
      'django.contrib.staticfiles',
      'blog',
      'users',
      'crispy_forms',
  ]
  
  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',
  ]
  
  ROOT_URLCONF = 'phyblog.urls'
  
  TEMPLATES = [
      {
          'BACKEND': 'django.template.backends.django.DjangoTemplates',
          'DIRS': [TEMPLATE_DIR],
          'APP_DIRS': True,
          'OPTIONS': {
              'context_processors': [
                  'django.template.context_processors.debug',
                  'django.template.context_processors.request',
                  'django.contrib.auth.context_processors.auth',
                  'django.contrib.messages.context_processors.messages',
              ],
          },
      },
  ]
  
  WSGI_APPLICATION = 'phyblog.wsgi.application'
  
  
  # Database
  # https://docs.djangoproject.com/en/1.11/ref/settings/#databases
  
  DATABASES = {
      'default': {
          'ENGINE': 'django.db.backends.sqlite3',
          'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
      }
  }
  
  
  # Password validation
  # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
  
  AUTH_PASSWORD_VALIDATORS = [
      {
          'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
      },
      {
          'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
      },
      {
          'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
      },
      {
          'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
      },
  ]
  
  
  # Internationalization
  # https://docs.djangoproject.com/en/1.11/topics/i18n/
  
  LANGUAGE_CODE = 'en-us'
  
  TIME_ZONE = 'Europe/Berlin'
  
  USE_I18N = True
  
  USE_L10N = True
  
  USE_TZ = True
  
  
  # Static files (CSS, JavaScript, Images)
  # https://docs.djangoproject.com/en/1.11/howto/static-files/
  
  STATIC_URL = '/static/'
  STATIC_DIR = os.path.join(BASE_DIR, 'blog/static/')
  CRISPY_TEMPLATE_PACK = 'bootstrap4'
  
  LOGIN_REDIRECT_URL = 'blog:home'
  
  LOGIN_URL = 'login'
  </code></pre>
  
  <p>If I'm misssing any files please tell me, otherwise, thank you very much for your help </p>