python django:目录中的视图,模型和表单

时间:2017-11-29 04:53:17

标签: python django

django 1.11

python 3.x

我一直试图将模型,视图和表单分解为文件夹。我从模型开始,它似乎工作。将views.py更改为views/index.py让我很难过。

我已经看过这个帖子而我认为我正在设置__init__.py个文件,但makemigrations仍然对我大吼大叫views/Profile.py

  File "/home/me/AppBase/MyApp/Members/urls.py", line 3, in <module>
    from . import views
  File "/home/me/AppBase/MyApp/Members/views/__init__.py", line 1, in <module>
    from .Profile import *
  File "/home/me/AppBase/MyApp/Members/views/Profile.py", line 7, in <module>
    from MyApp.Members.models.Profile import *
ImportError: No module named 'MyApp.Members'

文件结构

MyApp
|-- Members
|   |-- __init__.py
|   |-- account_adapter.py
|   |-- admin.py
|   |-- apps.py
|   |-- forms
|   |   |-- ProfileForm.py
|   |   |-- __init__.py
|   |-- models
|   |   |-- Profile.py
|   |   |-- __init__.py
|   |-- tests.py
|   |-- urls.py
|   `-- views
|       |-- Profile.py
|       |-- __init__.py

views/__init__.py是:

    from .Profile import *

views/Profile.py是:

    from django.contrib import messages
    from django.core.exceptions import *
    from django.shortcuts import redirect
    from django.shortcuts import render

    from MyApp.Members.models.Profile import *


    def create_profile(user):
        pass


    def profile(request):
        if not request.user.is_authenticated:
            return redirect('/account/login')

        try:
            profile = Profile.objects.get(user=request.user)
            messages.add_message(request, 1, "have profile")
        except ObjectDoesNotExist:
            messages.add_message(request, 1, "create profile")
            create_profile(request.user)

        return render(request, 'Members/index.html')

urls.py是:

    from django.conf.urls import url

    from . import views

    urlpatterns = [
        url(r'^$', views.Profile, name='profile'),
    ]

我使用PyCharm作为IDE,它声称所有路径都可以。我不确定我错过了什么。

1 个答案:

答案 0 :(得分:1)

from Members.models.Profile import *

你不需要从项目名称绝对导入,使用appname然后导入你需要的东西,希望这有帮助