Django apache:apache服务器上没有更新管理员字段

时间:2015-12-16 14:59:05

标签: django apache

我有一个django应用程序,可以在django的开发服务器上工作。但它在appache服务器上无法正常工作。将管理页面添加到模型后,没有新字段。只有在Django的开发服务器上运行应用程序时才会出现它们。 我试图用appache httpd设置解决它并显示admin / static的静态文件路径,但它没有效果。 请帮忙解决这个问题。 我的appache django.conf:

<VirtualHost *:80>
Alias /static /usr/local/mainproject/mysite/mysite/static/
Alias /static/admin /usr/local/lib/python3.3/site-    packages/django/contrib/admin/static/
Alias /media/admin /usr/local/lib/python3.3/site-packages/django/contrib/admin/media/

<Directory /usr/local/mainproject/mysite/mysite/static/>
    Require all granted
</Directory>

<Directory /usr/local/lib/python3.3/site-packages/django/contrib/admin/static/>
    Require all granted
</Directory>

<Directory /usr/local/lib/python3.3/site-packages/django/contrib/admin/media/>
    Require all granted
</Directory>

WSGIDaemonProcess mysite python-path=/usr/local/mainproject/mysite:/usr/local/lib/python3.3/site-packages
WSGIProcessGroup mysite
WSGIScriptAlias / /usr/local/mainproject/mysite/mysite/wsgi.py process-group=mysite

<Directory /usr/local/mainproject/mysite/mysite>
<Files wsgi.py>
  Require all granted 
</Files>
</Directory>
</VirtualHost>

我的 admin.py

 from django.contrib import admin
 from testres.models import Task, Issue, Result

 class IssueInline(admin.StackedInline):
     model = Issue

 class TaskAdmin(admin.ModelAdmin):
     fieldsets = [
         (None,  {'fields':['task_name']}),
         ('Description', {'fields':['task_description']}),
 #       ('Date information', {'fields': ['task_pub_date']}),
         ('Owners', {'fields':['task_owner']}),
     ]
     inlines = [IssueInline]

 class IssueAdmin(admin.ModelAdmin):
     fieldsets = [
         (None,  {'fields':['issue_name']}),
         ('Severity', {'fields':['issue_severity']}),
         ('Type', {'fields':['issue_type']}),
         ('Task', {'fields': ['task']}),
         ('Description', {'fields': ['issue_description']}),
     ]

 class ResultAdmin(admin.ModelAdmin):
     fieldsets = [
         ('Teacher Name',  {'fields':['teacher_name']}),
         ('Student Name', {'fields':['student_name']}),
         ('Task', {'fields': ['task']}),
         ('English level', {'fields':['english_level']}),
         ('Comment to result', {'fields': ['result_comment']}),
         ('Total Results', {'fields': ['total_result']}),
         ('Result Resolution', {'fields': ['result_resolution']}),

     ]


 admin.site.register(Task, TaskAdmin)
 admin.site.register(Issue, IssueAdmin)
 admin.site.register(Result, ResultAdmin)

我的 models.py

# -*- coding: utf-8 -*-

from django.db import models
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User


class Task(models.Model):
    task_name = models.CharField(max_length=100)            # name of the task
    task_description = models.CharField(max_length=2000)    # description of the task
    task_pub_date = models.DateField(db_index=True, auto_now_add=True)       # date of publication
    task_owner = models.ManyToManyField(User)

    def __unicode__(self):              # __unicode__ on Python 2
        return self.task_name

    def get_absolute_url(self):
        return reverse('view_task', kwargs={'task_id': self.id})



class Issue(models.Model):
    issue_name = models.CharField(max_length=100)
    # Issue severity field
    CRITICAL = 'CRT'
    BLOCKER = 'BLC'
    MAJOR = 'MJR'
    AVERAGE = 'AVG'
    MINOR = 'MIN'
    ISSUE_SEVERITY_CHOICES = (
        (CRITICAL, 'Critical'),
        (BLOCKER, 'Blocker'),
        (MAJOR, 'Major'),
        (AVERAGE, 'Average'),
        (MINOR, 'Minor'),
    )
    issue_severity = models.CharField(max_length=3, choices=ISSUE_SEVERITY_CHOICES, default=AVERAGE)
    #Issue type field
    SPEC = 'SPC'
    HIGHPRIORITY = 'HGH'
    NOTTRIVIAL = 'NTR'
    ALLOTHER = 'ALL'
    ISSUE_TYPE_CHOICES = (
        (SPEC, 'Дефекты на несоответствие со спецификацией'),
        (HIGHPRIORITY, 'Дефекты 1-го и 2-го приоритета'),
        (NOTTRIVIAL, 'Нетривиальные дефекты'),
        (ALLOTHER, 'Остальные дефекты'),
    )
    issue_type = models.CharField(max_length=3, choices=ISSUE_TYPE_CHOICES, default=ALLOTHER)
    task = models.ForeignKey(Task)
    issue_description = models.TextField(max_length=3000, default='empty')

    def __unicode__(self):
        return self.issue_name

    def get_absolute_url(self):
        return reverse('view_issue', kwargs={'issue_id': self.id})


class Result(models.Model):
    teacher_name = models.CharField(max_length=100)
    result_pub_date = models.DateField(db_index=True, auto_now_add=True)
    task = models.ForeignKey(Task)
    student_name = models.CharField(max_length=100)
    total_result = models.FloatField(default=0)
    english_level_choices =(
        ('1','elementary'),
        ('2','pre-intermediate'),
        ('3','intermediate'),
        ('4','upper-intermediate'),
        ('5','русскоязычное задание'),
    )
    english_level = models.CharField(max_length=20, choices=english_level_choices, default='5')
    result_comment = models.TextField(max_length=3000, default='empty')
    RESULT_RESOLUTION_CHOICES = (
        ('Reject', 'Rejected'),
        ('Accept', 'Accepted'),
    )
    result_resolution = models.CharField(max_length=7, choices=RESULT_RESOLUTION_CHOICES, default='Reject')

    def __unicode__(self):
        return self.student_name

    def get_absolute_url(self):
        return reverse('view_result', kwargs={'result_id': self.id})

我的 settings.py

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
# -*- coding: utf-8 -*-
import os
from unipath import Path
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_DIR = Path(__file__).parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3kd1=9yyyqcsl2%f(9^ed6ye917nhc5!vq8+gxiu)s4-r+)3oq'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls',
    'testres',
    'django_python3_ldap',
    'bootstrap3',
    'django_static_jquery',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    #'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    #'django.middleware.csrf.CsrfResponseMiddleware',

)

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'




# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
# django.db.backends.mysql - engine for old version

DATABASES = {
    'default': {
        'ENGINE': 'mysql_cymysql',
        'NAME': 'testresult',
        'USER': 'trdbuser',
        'PASSWORD': 'qwe123QWE',
        'HOST': 'localhost',        
    }
}


# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_ROOT = PROJECT_DIR.child('static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
        PROJECT_DIR.child('static'),
)

# Login info
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/loggedin/'

# LDAP INSTALLATION
AUTHENTICATION_BACKENDS = (
    'django_python3_ldap.auth.LDAPBackend',
    'django.contrib.auth.backends.ModelBackend',
)

# The URL of the LDAP server.
LDAP_AUTH_URL = "ldap://ldap.testserver.corp:389"

# Initiate TLS on connection.
LDAP_AUTH_USE_TLS = False

# The LDAP search base for looking up users.
LDAP_AUTH_SEARCH_BASE = "OU=Active,OU=Users,OU=testserver,DC=testserver,DC=corp"

# The LDAP class that represents a user. ??????
LDAP_AUTH_OBJECT_CLASS = "user"

#Data for user model collected from LDAP account

LDAP_AUTH_USER_FIELDS = {
    "username": "sAMAccountName",
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail",
}

# A tuple of django model fields used to uniquely identify a user.???????
LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",)

# Path to a callable that takes a dict of {model_field_name: value},???????
# returning a dict of clean model data.
# Use this to customize how data loaded from LDAP is saved to the User model.
LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data"

# Path to a callable that takes a user model and a dict of {ldap_field_name: [value]},???????
# and saves any additional user relationships based on the LDAP data.
# Use this to customize how data loaded from LDAP is saved to User model relations.
# For customizing non-related User model fields, use LDAP_AUTH_CLEAN_USER_DATA.
LDAP_AUTH_SYNC_USER_RELATIONS = "django_python3_ldap.utils.sync_user_relations"

# Path to a callable that takes a dict of {ldap_field_name: value},???????
# returning a list of [ldap_search_filter]. The search filters will then be AND'd
# together when creating the final search filter.
LDAP_AUTH_FORMAT_SEARCH_FILTERS = "django_python3_ldap.utils.format_search_filters"

LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory"

LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = 'testserver'

# The LDAP username and password of a user for authenticating the `ldap_sync_users`
# management command. Set to None if you allow anonymous queries.
LDAP_AUTH_CONNECTION_USERNAME = 'CN=Test Link,OU=ServiceAccounts,OU=Users,OU=testserver,DC=testserver,DC=corp'
LDAP_AUTH_CONNECTION_PASSWORD = 'testpass'

#SMTP settings
EMAIL_HOST = 'mail.testserver.corp'
#EMAIL_HOST_USER = ''
#EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = 25
EMAIL_USE_TLS = False

我的 urls.py

# -*- coding: utf-8 -*-
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth.views import login, logout
from . import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.conf.urls.static import static


urlpatterns = [
    url(r'^$', views.home, name='home' ),
    url(r'^testres/', include('testres.urls', namespace="testres")),
    url(r'^admin/', include(admin.site.urls)),

    # user auth urls
    url(r'^login/$', login, name='login'),
    url(r'^logout/$', logout, name='logout'),
    url(r'^loggedin/$', views.loggedin, name='loggedin'),

]

if settings.DEBUG == True:
    urlpatterns += staticfiles_urlpatterns()

我的 wsgi.py

# -*- coding: utf-8 -*-
import os
import sys

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

sys.path.insert(0, '/usr/local/mainproject/mysite')
sys.path.append('/usr/local/mainproject')
sys.path.append('/usr/local/mainproject/mysite')
sys.executable = '/usr/local/bin/python3.3/'
sys.path.append('/usr/local/lib/python3.3/site-packages/django')
sys.path.append('/usr/local/lib/python3.3/site-packages/MySQLdb')

application = get_wsgi_application()

找到了解决方案: 问题出在不同的Apache接口上。 我使用了 apachectl restart ,但是这个没有重启.py文件。 httpd -k restart 重启deamon并修复此问题

1 个答案:

答案 0 :(得分:0)

也许这是一个apache配置问题,这是我的apache配置:

#set wsgi
WSGIDaemonProcess example.com python-path=/var/www/sciblog:/usr/local/lib/python2.7/site-packages
WSGIProcessGroup example.com
WSGIScriptAlias / /var/www/sciblog/sciblog/wsgi.py process-group=example.com
#set public directories for apache
Alias /img/ /var/www/sciblog/img/
Alias /static/ /var/www/sciblog/blog/static/
<Directory /var/www/sciblog/blog/static>
    Require all granted
</Directory>
<Directory /var/www/sciblog/img>
    Require all granted
</Directory>
<Directory /var/www/sciblog/sciblog>
    <Files wsgi.py>
        Require all granted
    </Files>
</Directory>

管理文件已添加到项目中。我也没有把vitualhost标签。请查看此存储库:sciblog