2015-03-12 10 views
-1

Я не знаю, почему, но я столкнулся с какой-то странной проблемой. Мои шаблоны просто не загружали и не показывали. не могли бы вы помочь мне. Я использую Django версию 1.7Шаблон Django не загружается и не отображается

Он показывает следующее предупреждение, а в CMD:

C: \ Users \ Om Компьютеры \ PyDisco \ venv \ ddisco \ регистраций \ forms.py: 5: RemovedInDjango18Warning: Создание ModelForm без любого атрибута «полей» или «исключить» атрибут является устаревшим - форма SignUpForm нуждается в обновлении класса SignUpForm (forms.ModelForm):

у меня есть приложение под названием ddisco и приложения в пределах он называется signups, и мои шаблоны хранятся в папке шаблонов.

settings.py

""" 
Django settings for ddisco project. 

For more information on this file, see 
https://docs.djangoproject.com/en/1.7/topics/settings/ 

For the full list of settings and their values, see 
https://docs.djangoproject.com/en/1.7/ref/settings/ 
""" 

# Build paths inside the project like this: os.path.join(BASE_DIR, ...) 
import os 
BASE_DIR = os.path.dirname(os.path.dirname(__file__)) 


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

# SECURITY WARNING: keep the secret key used in production secret! 
SECRET_KEY = '' 

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

TEMPLATE_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', 
    'signups', 
) 

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', 
) 

ROOT_URLCONF = 'ddisco.urls' 

WSGI_APPLICATION = 'ddisco.wsgi.application' 


# Database 
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases 

DATABASES = { 
    'default': { 
     'ENGINE': 'django.db.backends.sqlite3', 
     'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 
    } 
} 

# Internationalization 
# https://docs.djangoproject.com/en/1.7/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.7/howto/static-files/ 

STATIC_URL = '/static/' 

# Template location 
TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'), 
) 

if DEBUG: 
    MEDIA_URL = '/media/' 
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticonly') 
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media') 
    STATICFILES_DIRS = (
     os.path.join(BASE_DIR, 'static'), 
    ) 

urls.py

from django.conf.urls import patterns, include, url 

from django.conf import settings 
from django.conf.urls.static import static 


from django.contrib import admin 
admin.autodiscover() 

urlpatterns = patterns('', 
    # Examples: 
    url(r'^$', 'signups.views.home', name='home'), 
    url(r'^s/$', 'signups.views.home', name='home'), 
    # url(r'^blog/', include('blog.urls')), 

    url(r'^admin/', include(admin.site.urls)), 
) 

if settings.DEBUG: 
    urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) 
    urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) 

models.py

 from django.db import models 
from django.utils.encoding import smart_unicode 

# Create your models here. 
class SignUp(models.Model): 
    first_name = models.CharField(max_length=120,null=True,blank=True) 
    last_name = models.CharField(max_length=120,null=True,blank=True) 
    email = models.EmailField() 
    timestamp = models.DateTimeField(auto_now_add=True, auto_now = False) 
    updated = models.DateTimeField(auto_now_add=False, auto_now = True) 

    def __unicode__(self): 
     return smart_unicode(self.email) 

views.py

from django.shortcuts import render , render_to_response, RequestContext 

from .forms import SignUpForm 
# Create your views here. 
from django.template import Context, Template 

def home(request): 
     form = SignUpForm(request.POST or None) 

     if form.is_valid(): 
      save_it = form.save(commit=False) 
      save_it.save() 

     return render_to_response( "base.html", 
              locals(), 
         context_instance=RequestContext(request)) 


def home(request): 
     context = {} 
     template = "base.html" 
     return render(request, template, context) 

base.html

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
    <meta charset="utf-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <meta name="description" content=""> 
    <meta name="author" content=""> 
    <link rel="icon" href="../../favicon.ico"> 

    <title>Homepage</title> 

    <!-- Latest compiled and minified CSS --> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> 

    <!-- Optional theme --> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css"> 

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> 
    <!--[if lt IE 9]> 
     <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> 
     <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> 
    <![endif]--> 
    </head> 

    <body> 


<!-- Main jumbotron for a primary marketing message or call to action 
    <div class="jumbotron"> 
     <div class="container"> 
     <div class="col-lg-6"> 
     <h1>Hello, world!</h1> 
     <p>This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more unique.</p> 
     <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more &raquo;</a></p> 
     </div> 
     </div> 
    </div> 
--> 
<div class="container"> 
     {% block sign%} 
     {%endblock%} 
<hr> 

    <div class="container"> 


     <hr> 

     <footer> 
     <p>&copy; Company 2014</p> 
     </footer> 
    </div> <!-- /container --> 


    <!-- Bootstrap core JavaScript 
    ================================================== --> 
    <!-- Placed at the end of the document so the pages load faster --> 
    <script 

src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
     <!-- Latest compiled and minified JavaScript --> 
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script> 


    </body> 
</html> 

signup.html

{% extends "base.html" %} 

{% block sign %} 
    <form class="form-horizontal col-lg-4" method='POST' action=''> {% csrf_token%} 
    <legend>Sign Up</legend> 
    <!--{{form.as_p}}--> 
     <div class="col-lg-10 col-lg-offset-2"> 
     <button type="submit" class="btn btn-primary">Submit</button> 
     </div> 
    </div> 
    </fieldset> 
    </form> 

{% endblock %} 
+0

Здесь по крайней мере три довольно очевидные ошибки: у вас есть два URL-адреса, указывающих на одно и то же имя вида, «home»; у вас на самом деле есть две функции просмотра, называемые «home»; и вы на самом деле не передаете signup.html из любого из них. –

ответ

0

Вы определили свой домашний вид в два раза. Вы должны удалить эту вторую точку зрения, так что это не заменяет первый один:

def home(request): 
    context = {} 
    template = "base.html" 
    return render(request, template, context) 

Во-вторых, если вы хотите использовать signup.html, вы должны включить его, когда вы предоставляете шаблон:

return render(request, "signup.html", locals()) 

Я использовал render, потому что это проще, вы можете использовать render_to_response, если вы действительно этого хотите.

Предупреждение - это всего лишь предупреждение, это не ошибка. Он сообщает вам обновить свой класс формы до включения fields перед обновлением до Django 1.8.

+1

Обратите внимание, что есть два URL-адреса, указывающие на домашний вид. Возможно, OP означает, что каждый указывает на каждую из этих функций просмотра? –

+0

@ DanielRoseman Хорошая точка. Я буду ждать ответа op перед обновлением моего ответа. – Alasdair

Смежные вопросы