启动Django服务器时循环导入导致错误

时间:2019-02-05 16:42:31

标签: python django django-models web-applications

因此,我尝试运行我一直在从事的该项目,这是一个简单的Django博客,但是当我尝试启动服务器时,出现以下错误:

pkr()

这是我在Django项目的博客应用中的urls.py文件:

Performing system checks...

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001A861F736A8>
Traceback (most recent call last):
  File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 535, in url_patterns
    iter(patterns)
TypeError: 'module' object is not iterable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
    self.check(display_num_errors=True)
  File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\core\management\base.py", line 379, in check
    include_deployment_checks=include_deployment_checks,
  File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\core\management\base.py", line 366, in _run_checks
    return checks.run_checks(**kwargs)
  File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks
    new_errors = check(app_configs=app_configs)
  File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 67, in _load_all_namespaces
    namespaces.extend(_load_all_namespaces(pattern, current))
  File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces
    url_patterns = getattr(resolver, 'url_patterns', [])
  File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\utils\functional.py", line 37, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\Alireza\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 542, in url_patterns
    raise ImproperlyConfigured(msg.format(name=self.urlconf_name))
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'blog.urls' from 'E:\\Projects\\Python\\web applications\\Django Simple Blog\\simple_blog\\blog\\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by
a circular import.

这是我在同一应用中的views.py:

from django.conf.urls import re_path
from blog import views

urlpattrens = [
    re_path(r'^$', views.PostListView.as_view(), name='post_list'),
    re_path(r'^about/$', views.AboutView.as_view(), name='about'),
    re_path(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(), name = 'post_detail'),
    re_path(r'^post/new/$', views.CreatePostView.as_view(), name='post_new'),
    re_path(r'^post/(?P<pk>\d+)/edit/$', views.PostUpdateView.as_view(), name='post_edit'),
    re_path(r'^post/(?P<pk>\d+)/remove/$', views.PostDeleteView.as_view(), name='post_remove'),
    re_path(r'^drafts/$', views.DraftListView.as_view(), name='post_draft_list'),
    re_path(r'^post/(?P<pk>\d+)/publish/$', views.post_publish, name='post_publish'),
    re_path(r'^post/(?P<pk>\d+)/comment/$', views.add_comment_to_post, name='add_comment_to_post'),
    re_path(r'^comment/(?P<pk>\d+)/approve/$', views.comment_approve, name='comment_approve'),
    re_path(r'^comment/(?P<pk>\d+)/remove/$', views.comment_remove, name='comment_remove'),
]

我不知道自己做错了什么,还是Django对此很敏感,但是我是Django新手,我对这种错误还不太熟悉。

这是我在博客应用中的forms.py:

from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from django.urls import reverse_lazy

from blog.models import Post, Comment
from blog.forms import PostForm, CommentForm

from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin

from django.views.generic import (TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView)


class AboutView(TemplateView):
    template_name = 'about.html'


class PostListView(ListView):
    model = Post

    # Customizing the generic class:
    def get_queryset(self):
        # grab all the objects from the post model and filter out conditions:
        # grab published date __less than or equal to the current time and order them by published date (- means by descending order)
        # Field lookups in the django documentation
        return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')


class PostDetailView(DetailView):
    model = Post


class CreatePostView(LoginRequiredMixin, CreateView):
    # Preventing anyone to access this function anonymouslly for usual views(function based) using decorators is enough
    # but here we are using class based views and should use the "LoginRequiredMixin"
    login_url = '/login/'
    redirect_field_name = 'blog/post_detail.html'
    form_class = PostForm

    model = Post


class PostUpdateView(LoginRequiredMixin, UpdateView):
    login_url = '/login/'
    redirect_field_name = 'blog/post_detail.html'
    form_class = PostForm

    model = Post


class PostDeleteView(LoginRequiredMixin, DeleteView):
    model = Post
    success_url = reverse_lazy('post_list')


class DraftListView(LoginRequiredMixin, ListView):
    login_url = '/login/'
    redirect_field_name = 'blog/post_list.html'
    model = Post

    def get_queryset(self):
        return Post.objects.filter(published_date__isnull = True).order_by('created_date')

################################
############################### 


@login_required
def post_publish(request, pk):
    post = get_object_or_404(Post, pk=pk)
    post.publish
    return redirect('post_detail', pk=pk)


@login_required  # make the entire view to be required as logged in
def add_comment_to_post(request, pk): # get the request alog with the pk which is passed
    post = get_object_or_404(Post, pk = pk) # either get the object or 404 page(can't find it)
    if request.method == 'POST': # if the request is 'POST' means someone actually filled in the form and hit Enter
        form = CommentForm(request.POST) # 
        if form.is_valid():
            comment = form.save(commit = False)
            comment.post = post # in models.py comment has an attribute which is post and it's a foreign key to the Post model
            comment.save()
            return redirect('post_detail', pk = post.pk)

    else:
        form = CommentForm()
    return render(request, 'blog/comment_form.html', {'form':form})


@login_required
def comment_approve(request, pk):
    comment = get_object_or_404(Comment, pk = pk)
    comment.approve() # run the approve function in the Comment class in models.py file to approve the comment
    return redirect('post_detail', pk = comment.post.pk)


@login_required
def comment_remove(request, pk):
    comment = get_object_or_404(Comment, pk = pk)
    post_pk = comment.post.pk
    comment.delete()
    return redirect('post_detail', pk = post_pk)

以及博客应用中的我的models.py:

from django import forms
from blog.models import Post,Comment


class PostForm(forms.ModelForm):

    class Meta():
        model = Post
        fields = ('author', 'title', 'text')

        widgets = {
            'title': forms.TextInput(attrs = {'class': 'textinputclass'}),
            'text': forms.Textarea(attrs = {'class': 'editable medium-editor-textarea postcontent'})
        }


class CommentForm(forms.ModelForm):
    class Meta():
        model = Comment
        fields = ('author', 'text')


        widgets = {
            'author': forms.TextInput(attrs={'class':'textinputclass'}),
            'text': forms.Textarea(attrs = {'class': 'editable medium-editor-textarea'})
            }

最后是我的主要urls.py:

from django.db import models
from django.utils import timezone
from django.urls import reverse

# Blog Models:

class Post(models.Model):
    author =            models.ForeignKey('auth.User', on_delete=models.CASCADE)
    title =             models.CharField(max_length = 200) 
    text =              models.TextField()
    create_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)

        # After Creating the post go to the post detail page by the primary key you created for it
    def get_absolute_url(self):
        return reverse("post_detail", kwargs={'pk': self.pk})

    def __str__(self):
        return self.title


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()
    create_date =           models.DateTimeField(default = timezone.now())
    approved_comment =      models.BooleanField(default = False)

    def approve(self):
        self.approved_comment = True
        self.save()

        # After approving a comment go back to the list of all the posts
    def get_absolute_url(self):
        return reverse('post_list')

    def __str__(self):
        return self.text

也是已安装应用程序的列表:

from django.conf.urls import url, include
from django.contrib import admin
from django.urls import path
from django.contrib.auth import views

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'', include('blog.urls')),
    url(r'accounts/login/$', views.LoginView, name='login'),
    url(r'accounts/logout/$', views.LogoutView, name = 'logout', kwargs={'next_page':'/'}),
]

0 个答案:

没有答案