简体   繁体   中英

Reverse for 'detail_account' with arguments '('',)' not found. 1 pattern(s) tried: ['account/account/(?P<slug>[^/]+)$']

I'm making a Django application and been trying to add a detail_profile_view, I want a button underneath the posts (it's a blog app) to direct you to a users account, the following isn't the entirety of my code its only what I think is relevant in the error.

I keep getting the following error:


Internal Server Error: /
Traceback (most recent call last):
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\dylan\myblogsite\blog\views.py", line 34, in home_view
    return render(request, 'home.html', context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\backends\django.py", line 61, in render
    return self.template.render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 171, in render
    return self._render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 163, in _render
    return self.nodelist.render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 163, in _render
    return self.nodelist.render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\defaulttags.py", line 309, in render
    return nodelist.render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\defaulttags.py", line 209, in render
    nodelist.append(node.render_annotated(context))
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader_tags.py", line 188, in render
    return template.render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 173, in render
    return self._render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 163, in _render
    return self.nodelist.render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\defaulttags.py", line 309, in render
    return nodelist.render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\defaulttags.py", line 443, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\urls\base.py", line 87, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "C:\Users\dylan\AppData\Local\Programs\Python\Python38\lib\site-packages\django\urls\resolvers.py", line 677, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'detail_account' with arguments '('',)' not found. 1 pattern(s) tried: ['account/account/(?P<slug>[^/]+)$']
[15/Jul/2020 21:59:29] "GET / HTTP/1.1" 500 224513

Here's my views.py:

def home_view(request):
    context = {} #sh
    query = ""
    if request.GET:
        query = request.GET['q']
        context['query'] = str(query)
    blog_posts = sorted(get_blog_queryset(query), key=attrgetter('date_published'), reverse=True)
    context['blog_posts'] = blog_posts

    return render(request, 'home.html', context)


def detail_account_view(request, slug):
    account = get_object_or_404(Account, slug=slug)
    return render(request, 'detail_blog.html', context={'account': account})

Here's my models.py:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.utils.text import slugify
from django.db.models.signals import pre_save
class MyAccountManager(BaseUserManager):
    def create_user(self, email, username, password=None):
        if not email:
            raise ValueError("Users must have an email address")
        if not username:
            raise ValueError("Users must have an username")

        user  = self.model(
                email=self.normalize_email(email),
                username=username,
            )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, username, password):
        user  = self.create_user(
                email=self.normalize_email(email),
                password=password,
                username=username,
            )
        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True
        user.save(using=self._db)
        return user


class Account(AbstractBaseUser):
    email                   = models.EmailField(verbose_name="email", max_length=60, unique=True)
    username                = models.CharField(max_length=30, unique=True)
    date_joined             = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
    last_login              = models.DateTimeField(verbose_name='last login', auto_now=True)
    is_admin                = models.BooleanField(default=False)
    is_active               = models.BooleanField(default=True)
    is_staff                = models.BooleanField(default=False)
    is_superuser            = models.BooleanField(default=False)
    slug                    = models.SlugField(unique=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    objects = MyAccountManager()

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

def pre_save_account_reciver(sender, instance, *args, **kwargs):
    slug = slugify(instance.username)
    exists = Account.objects.filter(slug=slug).exists()

    if exists:
        slug = "%s-%s" %(slug, instance.id)

    instance.slug = slug

pre_save.connect(pre_save_account_reciver, sender=Account)

Here's my urls.py:

from django.urls import path
from account.views import registration_view, logout_view, login_view, account_view, detail_account_view

app_name = 'account'

urlpatterns = [
    path('account/', account_view, name='account'),
    path('login/', login_view, name='login'),
    path('logout/', logout_view, name='logout'),
    path('register/', registration_view, name='register'),
    path('account/<slug>', detail_account_view, name='detail_account')
]

Here's my blog_post_snippet.html:

<style type="text/css">
    .card{
        max-width: 700px;
        width: 100%;
    }
    .card-body{
        padding: 20px;
    }
</style>

{% if blog_post %}
<div class="container">
    <div class="row">
        <!-- Blog Post -->
        <div class="card m-auto">
            <a href="{% url 'blog:detail' post.slug %}">
                <img class="card-img-top" src="{{blog_post.image.url}}">
            </a>
            <div class="card-body mt-2 mb-2">
                <a href="{% url 'blog:detail' post.slug %}">
                    <h2 class="card-title">{{blog_post.title}}</h2>
                </a>
                <p class="card-text">{{blog_post.body|safe|truncatechars:180}}</p>
                {% if blog_post.author == request.user %}
                    <a href="{% url 'blog:edit' blog_post.slug %}" class="btn btn-primary">Update</a>
                {% endif %}
            </div>
            <div class="card-footer text-muted">
              Updated on {{blog_post.date_updated}} by {{blog_post.author}}
                <a href="{% url 'account:detail_account' account.slug %}">Author</a>
            </div>
        </div>
    </div>
</div>

{% else %}

<div class="container">
    <div class="row">
        <div class="card m-auto">
            <div class="card-body mt-2 mb-2">
                <h2 class="card-title">No results</h2>
                <p class="card-text">There were no results matching the search: "{{query}}"</p>
            </div>
        </div>
    </div>
</div>

{% endif %}

Here's my home.html:

{% extends 'base.html' %}
{% load static %}

{% block content %}
<style type="text/css">

    @media (max-width: 768px) {
        .right-column{
            margin-left: 0px;
        }
    }

    @media (min-width: 768px) {
        .right-column{
            margin-left: 20px;
        }
    }

    .blog-post-container{
        margin-bottom: 20px;
        width: 100%;
    }
    .create-post-bar{
        background-color: #fff;
        margin-bottom:20px;
    }

    .left-column{
        padding:0px;
    }

    .right-column{
        padding:0px;
    }
    .lead{
        font-size: 17px;
    }
</style>


<!-- main content -->
<div class="container">
    <div class="row">

        <!-- blog feed -->
        <div class="left-column col-lg-7 offset-lg-1">

            <!-- Top 'create post' bar -->
            <div class="d-lg-none mb-3">
                <div class="card m-auto d-flex flex-column p-3">
                    <img class="img-fluid d-block m-auto pb-2" src="{% static 'logo.png' %}" width="150" height="150">
                    <p class="lead"></p>
                    <p class="m-auto"><a class="btn btn-primary" href="{% url 'blog:create_post' %}">Create post</a></p>
                </div>
            </div>
            <!-- end Top 'create post' bar -->

            <!-- Blog posts-->
            {% if blog_posts %}
                {% for post in blog_posts %}
                    <div class="blog-post-container">
                        {% include 'blog_post_snippet.html' with blog_post=post %}
                    </div>
                {% endfor %}
            {% else %}
                <div class="blog-post-container">
                    {% include 'blog_post_snippet.html' %}
                </div>
            {% endif %}
            <!-- End Blog posts-->




        </div>
        <!-- end blog feed -->


        <!-- Right 'create post' column  -->
        <div class="right-column col-lg-3 d-lg-flex d-none flex-column">

            <div class="card create-post-bar d-flex flex-column p-3">
                <img class="img-fluid d-block m-auto pb-2" src="{% static 'logo.png' %}" width="200" height="200">
                <p class="lead"></p>
                <p class="m-auto"><a class="btn btn-primary" href="{% url 'blog:create_post' %}">Create post</a></p>
            </div>

        </div>
        <!-- end Right 'create post' column  -->



    </div>
</div>

{% endblock content %}

I have tried looking at similar questions, but they don't seem to be of much use. I'm new to Django.

The error says django.urls.exceptions.NoReverseMatch: Reverse for 'detail_account' with arguments '('',)' not found. 1 pattern(s) tried: ['account/account/(?P<slug>[^/]+)$'] django.urls.exceptions.NoReverseMatch: Reverse for 'detail_account' with arguments '('',)' not found. 1 pattern(s) tried: ['account/account/(?P<slug>[^/]+)$'] , which means the argument is empty because you're not passing the account context.

Add it in your home_view function:

def home_view(request):
    context = {} #sh
    query = ""
    if request.GET:
        query = request.GET['q']
        context['query'] = str(query)
    blog_posts = sorted(get_blog_queryset(query), key=attrgetter('date_published'), reverse=True)
    context['blog_posts'] = blog_posts
    context['account'] =  # get the Account instance here

    return render(request, 'home.html', context)

I also suggest changing that path of your detail_account to this:

path('account/<slug:slug>/', detail_account_view, name='detail_account')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM