表单输入框不显示 [英] Form input-box not displaying

查看:196
本文介绍了表单输入框不显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Django显示一个简单的表单输入文本框。我正在部署在Amazon AWS上。该站点在不同的服务器上工作正常(pythonanywhere),但在AWS上存在一个主要问题。具体来说,输入框没有显示。我使用的模板如下:



home.html

  {%extends'lists / base.html'%} 

{%block header_text%}开始一个新的待办事项列表{%endblock%}

{%block form_action%} {%url'new_list'%} {%endblock%}

base.html

 <!DOCTYPE html> 
< html lang =en>

< head>
< meta charset =utf-8>
< meta http-equiv =X UA兼容content =IE-edge>
< meta name =viewportcontent =width = device-width,initial-scale = 1>
< title>待办事项列表< / title>
< link href =/ static / bootstrap / css / bootstrap.min.css =stylesheet>
< link href =/ static / base.css =stylesheet>
< / head>
< body>
< div class =container>

< div class =row>
< div class =col-md-6 col-md-offset-3 jumbotron>
< div class =text-center>
< h1> {%block header_text%} {%endblock%}< / h1>
< form method =POSTaction ={%block form_action%} {%endblock%}>
{{form.text}}
{%csrf_token%}
{%if form.errors%}
< div class =form-group has-error> ;
< span class =help-block> {{form.text.errors}}< / span>
< / div>
{%endif%}
< / form>
< / div>
< / div>
< / div>

< div class =row>
< div class =col-md-6 col-md-offset-3>
{%block table%}
{%endblock%}
< / div>
< / div>
< / div>
< / body>
< / html>

models.py


$ b $从django.db导入模型的


$ b .core.urlresolvers import reverse


class List(models.Model):
def get_absolute_url(self):
return reverse('view_list',args = [self.id])

#创建你的模型这里。
类项目(models.Model):
text = models.TextField(default ='')
list = models.ForeignKey(List,default = None)
#list = models.ForeignKey(List,default = None)

forms.py / p>

 从django导入表单

从lists.models导入项

EMPTY_ITEM_ERROR =你不能有空列表项
class ItemForm(forms.models.ModelForm):
class Meta:
model = Item
fields =('text' ,)
widgets = {
'text':forms.fields.TextInput(attrs = {
'placeholder':'输入待办事项',
'class' :'form-control input-lg',
}),
}
error_messages = {
'text':{'required':EMPTY_ITEM_ERROR}
}

views.py

  from django.shortcuts import redirect,render 
from lists.models import Item,List
from django.core.exceptions import ValidationError
from lists.forms import ItemForm
from lists.models import Item,List

#在这里创建您的视图。
def home_page(request):
return render(request,'lists / home.html',{'form':ItemForm()})
pre>

urls.py

 从django.conf.urls import url 
从列表导入视图

urlpatterns = [
url(r'^ new $',views.new_list,name ='new_list') ,
url(r'^(\d +)/ $',views.view_list,name ='view_list'),

]

目前该网站显示以下内容:





但是它应该(并在不同的网站上)显示:



我推/ p将整个项目整理为github,并且每个站点之间的代码是相同的,但我不明白为什么文本输入不显示,除非表单需要在Django中以某种方式初始化或者是对AWS的一个怪癖?



当比较两个网站时,没有文本框的人不会生成以下内容:

 < input class =form-control input-lgid =id_textname =textplaceholder =输入待办事项type =text/> 

尽管它应该是根据 base.html 语法。



更新



完整的 views.py (根据建议的评论)是:

 从django.shortcuts导入重定向,从lists.models导入
导入项,从django.core.exceptions导入列表
从lists.forms导入ValidationError
从lists.models导入ItemForm
导入项目,列表

#在此创建您的视图。
def home_page(request):
return render(request,'lists / home.html',{'form':ItemForm()})

def new_list(request) :
form = ItemForm(data = request.POST)
如果form.is_valid():
list_ = List.objects.create()
Item.objects.create(text = request.POST ['text'],list = list_)
return redirect(list_)
else:
return render(request,'lists / home.html',{form :form})

def view_list(request,list_id):
list_ = List.objects.get(id = list_id)
form = ItemForm()

如果request.method =='POST':
form = ItemForm(data = request.POST)
如果form.is_valid():
Item.objects.create(text = request.POST ['text'],list = list_)
return redirect(list_)
return render(request,'lists / list.html',{'list':list_,form form})


解决方案

ce与Django,有两件你经常(总是?)需要做的是将静态文件刷新后推送到远程服务器:


  1. 运行 ./ manage.py collectstatic 以确保所有静态文件位于正确的位置。

  2. ssh 编入您的服务器运行命令 sudo reboot now 重新启动服务器(请注意,这将使您脱离您的ssh会话和您的服务器将无法访问一段时间 - 通常在我的情况下只需几秒钟)。

至于步骤 2 可能会有一个更好的方法来做到这一点,但根据我的经验,当我更新静态文件时,更新的版本不会提供,直到我这样做,并重新启动 nginx 等不足以使更改生效。请注意,这意味着您的网站(如果实时)在服务器重新启动时几秒钟内无法访问(这是什么让我认为可能会有更好的方法),但对我和我的小型用户群这不是一个大问题。



从阅读一些其他关于静态文件的文章不更新,似乎也可能是您的浏览器缓存静态文件,并重新启动您的浏览器/清除缓存也可能会做的伎俩,但我还没有机会尝试这个。


I'm trying to display a simple form input-text box with Django. I'm am deploying on Amazon AWS. The site works fine on a different server (pythonanywhere) but there is a major problem on AWS. Specifically, the input box is not being displayed. I'm using templates as follows:

home.html

{% extends 'lists/base.html' %}

{% block header_text %}Start a new To-Do list {% endblock %}

{% block form_action %}{% url 'new_list' %}{% endblock %}

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">
        <title>To-Do lists</title>
        <link href="/static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
        <link href="/static/base.css" rel="stylesheet">
    </head>
    <body>
        <div class="container">

            <div class="row">
                <div class="col-md-6 col-md-offset-3 jumbotron">
                    <div class="text-center">
                        <h1>{% block header_text %}{% endblock %}</h1>
                        <form method="POST" action="{% block form_action %}{% endblock %}">
                            {{ form.text }}
                            {% csrf_token %}
                            {% if form.errors %}
                                <div class = "form-group has-error">
                                    <span class = "help-block">{{ form.text.errors }}</span>
                                </div>
                            {% endif %}
                        </form>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6 col-md-offset-3">
                    {% block table %}
                    {% endblock %}
                </div>
            </div>
        </div>
    </body>
</html>

models.py

from django.db import models
from django

.core.urlresolvers import reverse


class List(models.Model):
    def get_absolute_url(self):
        return reverse('view_list', args=[self.id])

# Create your models here.
class Item(models.Model):
    text = models.TextField(default = '')
    list = models.ForeignKey(List, default = None)
    #list = models.ForeignKey(List , default=None)

forms.py

from django import forms

from lists.models import Item

EMPTY_ITEM_ERROR = "You can't have an empty list item"
class ItemForm(forms.models.ModelForm):
    class Meta:
        model = Item
        fields = ('text',)
        widgets ={
            'text' : forms.fields.TextInput(attrs={
                    'placeholder': 'Enter a to-do item',
                    'class': 'form-control input-lg',
            }),
        }
        error_messages = {
            'text' : { 'required': EMPTY_ITEM_ERROR }
        }

views.py

from django.shortcuts import redirect, render
from lists.models import Item, List
from django.core.exceptions import ValidationError
from lists.forms import ItemForm
from lists.models import Item, List

# Create your views here.
def home_page(request):
    return render(request, 'lists/home.html', {'form': ItemForm()})

urls.py

from django.conf.urls import url
from lists import views

urlpatterns = [
                url(r'^new$', views.new_list, name='new_list'),
                url(r'^(\d+)/$', views.view_list, name='view_list'),

        ]

Currently the site displays the following:

However it should (and does on a different website) display this:

I've pushed/pulled the entire project to github and the code between each site is identical, yet I'm not seeing why the text input isn't displayed, unless the form needs to be initialized in Django somehow or a quirk to AWS?

When comparing the two sites, the one without the text-box does not generate the following:

<input class="form-control input-lg" id="id_text" name="text" placeholder="Enter a to-do item" type="text" />

Even though it should, per the base.html syntax.

Updated

The full views.py (per suggested comment) is:

from django.shortcuts import redirect, render
from lists.models import Item, List
from django.core.exceptions import ValidationError
from lists.forms import ItemForm
from lists.models import Item, List

# Create your views here.
def home_page(request):
    return render(request, 'lists/home.html', {'form': ItemForm()})

def new_list(request):
    form = ItemForm(data=request.POST)
    if form.is_valid():
        list_ = List.objects.create()
        Item.objects.create(text=request.POST['text'], list=list_)
        return redirect(list_)
    else:
        return render(request, 'lists/home.html', {"form": form})

def view_list(request, list_id):
    list_ = List.objects.get(id=list_id)
    form = ItemForm()

    if request.method == 'POST':
        form = ItemForm(data=request.POST)
        if form.is_valid():
            Item.objects.create(text=request.POST['text'], list=list_)
            return redirect(list_)
    return render(request, 'lists/list.html', {'list': list_, "form": form})

解决方案

In my experience with Django, there are 2 things you often (always?) need to do to get static files to "refresh" after pushing them to a remote server:

  1. Run ./manage.py collectstatic to make sure all your static files are in the right place.
  2. While sshed into your server run the command sudo reboot now to restart your server (note that this will kick you out of your ssh session, and your server will be unreachable for a moment - usually just a few seconds in my case).

As for step 2 there might be a better way to do this, but in my experience, when I update static files the updated version is not served until I do this, and restarting nginx or the like is not sufficient for the changes to take effect. Note that this will mean that your site, if live, will not be reachable for a few seconds while the server is restarting (which is what makes me think there might be a better way to do it) but for me and my small user base this is not a big issue.

From reading some other posts about static files not updating, it seems like it could also be the case that your browser is caching the static files, and that restarting your browser/clearing the cache might do the trick as well, but I have not had a chance to try this yet.

这篇关于表单输入框不显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆