无法将表单类导入视图

时间:2017-09-21 20:31:16

标签: django django-forms

Django新手在这里。我的视图功能无法导入PostForm class。所有三个py文件都是兄弟姐妹。模型中的Post class可以成功导入。

你能帮忙解决这个问题吗?

错误消息:

  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/home/ubuntu/workspace/django_projects/urls.py", line 1, in <module>
    import blog_app.blog_urls
  File "/home/ubuntu/workspace/blog_app/blog_urls.py", line 2, in <module>
    from . import views
  File "/home/ubuntu/workspace/blog_app/views.py", line 8, in <module>
    from .forms import PostForm
ImportError: cannot import name PostForm

views.py:

from __future__ import unicode_literals
from django.shortcuts import render, get_object_or_404

from .models import Post
from .forms import PostForm


def post_new(request): 
    form = PostForm()
    return render(request, 'blog_app/post_edit.html', {'form': form})

forms.py:

from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'text',)

models.py:

from django.utils import timezone


class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()

    def __str__(self):
        return self.title

2 个答案:

答案 0 :(得分:0)

使用应用名称导入而不是.forms

<强> views.py

from __future__ import unicode_literals
from django.shortcuts import render, get_object_or_404

from .models import Post
from <you_app_name>.forms import PostForm


def post_new(request): 
    form = PostForm()
    return render(request, 'blog_app/post_edit.html', {'form': form})

答案 1 :(得分:0)

问题解决了:

我不得不对文件结构做一些修改。因此,创建了一个forms包并向其添加了__init__.py模块。然后将forms.py模块重命名为post_forms.py并将其移至forms包中。现在当我导入像PostForm这样的from blog_app.forms.post_forms import PostForm类时,它可以正常工作。显然重命名forms.py在这里并不重要,但我这样做是为了让文件更有条理,以防我将来为其他模型添加表单。