Home > Software engineering >  Error while working on the site in Django
Error while working on the site in Django

Time:12-03

This is a continuation of the previous question. When I continued to work on the site and when I wanted to test the site through "python manage.py runserver" in the C:\mysite\site\miniproject directory, the following error pops up:

C:\Program Files\Python36\lib\site-packages\django\db\models\base.py:321: RuntimeWarning: Model 'blog.post' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models.
  new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
C:\Program Files\Python36\lib\site-packages\django\db\models\base.py:321: RuntimeWarning: Model 'blog.post' was already registered. Reloading models is not advised as it can lead to inconsistencies, most notably with related models.
  new_class._meta.apps.register_model(new_class._meta.app_label, new_class)
Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\site-packages\django\urls\conf.py", line 17, in include
    urlconf_module, app_name = arg
ValueError: too many values to unpack (expected 2)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "C:\Program Files\Python36\lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Program Files\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
    self.check(display_num_errors=True)
  File "C:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 423, in check
    databases=databases,
  File "C:\Program Files\Python36\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "C:\Program Files\Python36\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "C:\Program Files\Python36\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
    return check_method()
  File "C:\Program Files\Python36\lib\site-packages\django\urls\resolvers.py", line 416, in check
    for pattern in self.url_patterns:
  File "C:\Program Files\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Program Files\Python36\lib\site-packages\django\urls\resolvers.py", line 602, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "C:\Program Files\Python36\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Program Files\Python36\lib\site-packages\django\urls\resolvers.py", line 595, in urlconf_module
    return import_module(self.urlconf_name)
  File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "C:\mysite\site\miniproject\miniproject\urls.py", line 20, in <module>
    url(r'^admin/', include(admin.site.urls)),
  File "C:\Program Files\Python36\lib\site-packages\django\urls\conf.py", line 27, in include
    'provide the namespace argument to include() instead.' % len(arg)
django.core.exceptions.ImproperlyConfigured: Passing a 3-tuple to include() is not supported. Pass a 2-tuple containing the list of patterns and app_name, and provide the namespace argument to include() instead.

Here is a link to the chapter where I worked: https://pocoz.gitbooks.io/django-v-primerah/content/sozdanie-shablonov-dlia-view.html , Most likely I made a mistake somewhere. Next, I will show you the contents of the files:

base.html:
{% load static files %}
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}{% endblock %}</title>
    <link href="{% static "css/blog.css" %}" rel="stylesheet">
</head>
<body>
<div id="content">
    {% block content %}
    {%endblock%}
</div>
<div id="sidebar">
    <h2>My blog</h2>
    <p>This is my blog.</p>
</div>
</body>
</html>

list.html:
{% extends "blog/base.html" %}
{% block title %}My Blog{% endblock %}
{% block content %}
    <h1>My Blog</h1>
    {% for post in posts %}
        <h2>
            <a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
        </h2>
        <p >
            Published {{ post.publish }} by {{ post.author }}
        </p>
        {{ post.body|truncatewords:30|linebreaks }}
    {% endfor %}
{%endblock%}

detail.html:
{% extends "blog/base.html" %}
{% block title %}{{ post. title }}{% endblock %}
{% block content %}
    <h1>{{post.title}}</h1>
    <p >
        Published {{ post.publish }} by {{ post.author }}
    </p>
{{ post.body|linebreaks}}
{%endblock%}

C:\mysite\site\miniproject\blog\views.py:
from django.shortcuts import render, get_object_or_404
from .models import Post

def post_list(request):
    posts = Post.published.all()
    return render(request, 'blog/post/list.html', {'posts': posts})

def post_detail(request, year, month, day, post):
    post = get_object_or_404(Post, slug=post,
                                   status='published',
                                   publish_year=year,
                                   publish__month=month,
                                   publish_day=day)
    return render(request,'blog/post/detail.html', {'post': post})

# Create your views here.

C:\mysite\site\miniproject\blog\urls.py:
from django.conf.urls import url
from. import views

urlpatterns = [
    # post views
    url(r'^$', views.post_list, name='post_list'),
    url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\
        r'(?P<post>[-\w] )/$',
        views.post_detail,
        name='post_detail'),
]

C:\mysite\site\miniproject\miniproject\urls.py:
"""miniproject URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import: from my_app import views
    2. Add a URL to urlpatterns: path('', views.home, name='home')
class-based views
    1. Add an import: from other_app.views import Home
    2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin

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

C:\mysite\site\miniproject\blog\models.py:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.shortcuts import reverse
class Post(models.Model):
    def get_absolute_url(self):
        return reverse('blog:post_detail',
                        args=[self.publish.year,
                              self.publish.strftime('%m'),
                              self.publish.strftime('%d'),
                              self.slug])

class Post(models.Model):
    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('published', 'Published'),
    )
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250, unique_for_date='publish')
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')

class Meta:
    ordering = ('-publish',)

def __str__(self):
    return self.title


# Create your models here.

I updated the Python libraries and carefully checked everything, read the Django documentation and nothing helped, maybe I inserted the Python code incorrectly

CodePudding user response:

Change the import line to from django.shortcuts import reverse.

CodePudding user response:

The error lies in your urls file

app_name is passed as an arg instead of a kwarg

    url(r'^blog/', include('blog.urls',
                            namespace='blog',
                            app_name='blog')), 

This should fix the issue

    url(r'^blog/', include('blog.urls', "blog",  namespace='blog'),

here is the implemtation behind include method

def include(arg, namespace=None):
    app_name = None
    if isinstance(arg, tuple):
        # Callable returning a namespace hint.
        try:
            urlconf_module, app_name = arg
        except ValueError:
            if namespace:
                raise ImproperlyConfigured(
                    "Cannot override the namespace for a dynamic module that "
                    "provides a namespace."
                )
            raise ImproperlyConfigured(
                "Passing a %d-tuple to include() is not supported. Pass a "
                "2-tuple containing the list of patterns and app_name, and "
                "provide the namespace argument to include() instead." % len(arg)
            )
    else:
        # No namespace hint - use manually provided namespace.
        urlconf_module = arg
       ...
  • Related