python - 如何在我的Django文件中包含一个表单?

标签 python mysql django

我在mysite/new_player.html中创建了一个表单。它接受与数据库中Player表相对应的3个字段:user_name、real_name和site_played。

<h1> New Player </h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="/stakeme/new/" method="post">
{% csrf_token %}
User Name: <input type="text" name="user_name" id="user_name"/><br>
Real Name: <input type="text" name="real_name" id="real_name"/><br>
Site Played: <input type="text" name="site_played" id="site_played"/><br><br>
<input type="submit" value="New Player" />
</form>

。我已经完成了民意测验教程,但教程中使用的唯一表单是“民意测验”的多项选择,我似乎无法将其调整为文本字段。
def new_player(request):
    return render_to_response('stakeme/new_player.html',
                           context_instance=RequestContext(request))

。。
我正在阅读Django文档,但我觉得我只是在合成一些我不明白的东西。。

最佳答案

。。
Using Django Forms
。。。
Start a new django project:

$ django.admin.py startproject mysite

Add a new app:
$ ./mysite/manage.py startapp myapp

让我们创建联系人表单(从Django forms doc中的示例修改)。Create a file in side the myapp/ directory called called forms.py and put the following in it:
from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField(max_length=100)

。In your models.py file, add the following:
class Feedback(models.Model):
    subject = models.CharField(max_length=100)
    message = models.TextField()
    sender = models.CharField(max_length=100)

    def __unicode__(self):
        return "Subject:{subject}\nSender:{sender}\n{msg}".format(subject=self.subject,
                                                                sender=self.sender,
                                                                msg=self.message)

(您可能会注意到这与我们之前定义的表单非常相似;通常在这样的场景中,人们会使用v1.3 forms documentation直接从模型创建表单,但我们正在手工构建表单作为学习体验)
We also need to get Django to create the required table in our database for this Feedback model, so at the top of your settings.py insert the following useful code:
import os
PROJECT_DIR = os.path.dirname(__file__)

并将DATABASES中的Django model forms设置更改为以下设置以使用settings.py数据库:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': os.path.join(PROJECT_DIR, "sqlite.db").replace('\\', '/'),   # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

Finally, change the sqlite setting to the following to include our recently created application INSTALLED_APPS in the list of installed applications for myapp:
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
    # Uncomment the next line to enable the admin:
    # 'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
)

现在运行mysite命令以获取Django来创建SQLite数据库中的表(由于SQLSite,如果不存在,则将创建该表):
$ ./mysite/manage.py syncdb

(Django will prompt you to create a superuser as well: you don't have to create a superuser now since we don't need it and you can use syncdb to create one when you need it, but you can create now now if you like)
。In your django-admin.py createsuperuser file, add the following (modified slightly from Django forms docs):
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from myapp.forms import ContactForm
from myapp.models import Feedback

def thanks(request):
    return render_to_response('thanks.html')

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            sender = form.cleaned_data['sender']

            feedback = Feedback(subject=subject, message=message, sender=sender)
            feedback.save()

            return HttpResponseRedirect(reverse('thanks')) # Redirect after POST
    else:
        form = ContactForm() # An unbound form

    return render_to_response('contact.html', {
        'form': form,
    }, context_instance=RequestContext(request))

。Open views.py and make it look like the following
from django.conf.urls.defaults import patterns, include, url

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    url(r'^thanks/$', 'myapp.views.thanks', name='thanks'),
    url(r'^$', 'myapp.views.contact', name='contact'),
    # url(r'^mysite/', include('mysite.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
)

。创建一个目录,在其中创建一个文件,并在其中放置以下内容:
<html>
    <head>
        <title>Contact Us</title>
    </head>
    <body>
        <p>Please fill out the following information and click submit:</p>

        <form action="{% url contact %}" method="post">{% csrf_token %}
            {{ form.as_p }}
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>

Also create a mysite/urls.py page for the thank you page, and put the following in it:
<html>
    <head>
        <title>Thanks</title>
    </head>
    <body>
        <p>Thank you. Your feedback is important to us</p>

        <p>Please leave some more feedback at the <a href="{% url contact %}">Contact page</a></p>
    </body>
</html>

Next, we need to make sure Django can find our templates, so modify the mysite/templates/ in contact.html setting to the following:
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_DIR, "templates").replace('\\', '/'),
)

Now, (finally!), you can run the debug server and test that everything works:
$ ./mysite/manage.py runserver 8080

。。You can check the details are entered into the database:
$ ./mysite/manage.py shell

在shell中键入:
>>> from myapp.models import Feedback
>>> for f in Feedback.objects.all(): print f

(note that you need to press enter twice after entering the last line)

在HTML中手动创建表单


其他教程
因为这个问题的原始形式需要一些教程:thanks.html有一个http://localhost:8080/,其中一些涉及表单。请注意,这些教程中有很多都很老(大多是2007-2009年的)。

关于python - 如何在我的Django文件中包含一个表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8904083/

相关文章:

python - 如何使用 matplotlib 中的直方图输出绘制散点图?

python - 如何创建以列表为参数的 SELECT 语句?

python - 循环遍历表单 POST 将数据存储在 python 变量中

python - django auth 用户截断电子邮件字段

python - 升级到Django 1.7 : Getting AppRegistryNotReady for translation infrastructure

python - 使用 Python 计算点密度

php - 空值被插入数据库

php - 使用原则保存多条记录并获取每条记录的 ID

php - 如何从数据库中的字符之间获取多个字符串

python - Django-如何将 'autonumber' 列添加到 View 创建的表中?