如何在我的Django文件中包含一个表单? [英] How do I include a form into my Django file?

查看:79
本文介绍了如何在我的Django文件中包含一个表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a form created in mysite/new_player.html. It accepts 3 fields, user_name, real_name, and site_played that correspond to the Player table in the database.

<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>

我对如何将此添加到mysite/views.py文件一无所知.我已经阅读了民意测验教程,但是该教程中使用的唯一形式是民意测验"的多选选择",我似乎无法适应文本字段.

I am stuck on how to add this to my mysite/views.py file. I have gone through the polls tutorial, but the only form that is used in the tutorial is a multiple choice "choice" of the "poll" and I can't seem to adapt that to text fields.

def new_player(request):
    return render_to_response('stakeme/new_player.html',
                           context_instance=RequestContext(request))

据我了解,我需要创建类似def add(request): return render_to_response('stakeme/new/'.. etc的内容并在此处添加POST数据,但这就是我迷路的地方.我不确定如何将数据导入数据库.

So as I understand it, I would need to create something like def add(request): return render_to_response('stakeme/new/'.. etc and add the POST data in here, but that's where I am lost. I am not sure how to get the data into the database.

我正在阅读Django文档,但是我觉得我只是在复合一些我不理解的东西.如果有人能指出正确的方向,我将不胜感激.

I am reading the Django docs, but I feel like I am just compounding something that I do not understand. If someone could point me in the right direction, I would really appreciate it.

推荐答案

首先,您无需定义新视图即可处理表单数据.另外,您可以直接使用HTML创建表单-可以以这种方式工作(请参阅后面的部分),但是使用Django Forms库更好(更容易).

Firstly, you don't need to define a new view to process the form data. Also, you are creating your form directly in HTML - it's possible to work this way (see later section of post) but it's better (easier) to use the Django Forms library.

使用Django表单

从头到尾包括以下文档( v1.3表单文档).使用模板显示表单"解释了使用表单库的基本知识,因此我将复制&从那里自由粘贴.我还将假设您熟悉基本的python构造&安装了Django 1.3.事不宜迟,这是我的即席表格教程.

The documentation (v1.3 forms documentation) from the start up to and including ''Displaying a form using a template'' explains the basics of using the forms library, so I'll copy & paste liberally from there. I'll also assume that you're familiar with basic python constructs & have Django 1.3 installed. Without further ado, here's my adhoc forms tutorial.

开始一个新的django项目:

Start a new django project:

$ django.admin.py startproject mysite

添加新应用:

$ ./mysite/manage.py startapp myapp

让我们创建联系表单(从Django表单doc中的示例进行了修改).在myapp/目录的旁边创建一个名为forms.py的文件,并将以下内容放入其中:

Lets create our contact form (modified from example in 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)

接下来,由于您提到将收到的联系表中的数据存储在数据库中,因此我们将添加一个反馈模型来跟踪收到的联系表.在您的models.py文件中,添加以下内容:

Next, since you mentioned storing data from received contact forms in a database, we'll add a model, Feedback, to track received contact forms. 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)

(您可能会注意到,这与我们之前定义的形式非常相似;通常在这种情况下,人们会使用

(You may notice this is very similar to the form we defined earlier; normally in a scenario like this, one would use Django model forms to create a form directly from a model, but we are building our forms by hand as a learning experience)

我们还需要让Django在我们的数据库中为此反馈模型创建所需的表,因此在settings.py的顶部插入以下有用的代码:

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__)

并将settings.py中的 DATABASES 设置更改为以下内容以供使用 sqlite 数据库:

And change the DATABASES setting in settings.py to the following to use a sqlite database:

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.
    }
}

最后,将 INSTALLED_APPS 设置更改为以下内容,以包括最近为mysite安装的应用程序列表中创建的应用程序myapp:

Finally, change the INSTALLED_APPS setting to the following to include our recently created application myapp in the list of installed applications for mysite:

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

现在运行 syncdb 命令以让Django创建表在您的sqlite数据库中(由于它是sqlite,如果尚不存在,将创建它):

Now run the syncdb command to get Django to create the tables in your sqlite database (which, since it's sqlite, will be created if it doesn't exist yet):

$ ./mysite/manage.py syncdb

(Django也会提示您创建一个超级用户:您现在不必创建超级用户,因为我们不需要它,您可以使用

(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 django-admin.py createsuperuser to create one when you need it, but you can create now now if you like)

现在,我们需要一个视图来显示联系表单,并需要一个视图来感谢人们提交该表单.在您的views.py文件中,添加以下内容(从Django表单文档中略作修改):

Now we need a view to display the contact form, and a view to thank people for submitting it. In your views.py 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))

现在,我们需要将URL映射到视图.打开mysite/urls.py并使其如下所示

Now we need to map URLs to views. Open mysite/urls.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)),
)

现在,我们需要一些模板来显示联系表&谢谢页面.创建目录mysite/templates/,在其中创建文件contact.html,并将以下内容放入其中:

Now we need some templates to display the contact form & the thankyou page. Create a directory mysite/templates/, create a file contact.html inside it, and put the following in it:

<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>

还为感谢页面创建一个thanks.html页面,并在其中添加以下内容:

Also create a thanks.html 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>

接下来,我们需要确保Django可以找到我们的模板,因此请修改 mysite/settings.py设置为以下内容:

Next, we need to make sure Django can find our templates, so modify the TEMPLATE_DIRS in mysite/settings.py 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

转到 http://localhost:8080/并尝试输入一些反馈.当您单击提交时,它应该将您输入的详细信息放入数据库&中.显示谢谢页面.您可以检查详细信息是否已输入数据库:

Go to http://localhost:8080/ and try to enter some feedback. When you click Submit, it should put your entered details into the database & show the thank you page. You can check the details are entered into the database:

$ ./mysite/manage.py shell

在外壳中,键入:

>>> from myapp.models import Feedback
>>> for f in Feedback.objects.all(): print f

(请注意,在输入最后一行之后,您需要按两次Enter键)

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

您应该看到您创建的反馈条目.

You should see the feedback entries you have created.

使用HTML手动创建表单

如果您坚持要执行此操作,则可以使用request.POST词典直接在视图中访问表单的请求变量,然后手动实例化对象的模型&调用save(如上面的contact()视图函数中一样).

If you insist on doing this, you can access the form's request variables directly in your view using the request.POST dictionary, and then instantiating a model of your object manually & calling save (like in the contact() view function above).

我不建议您这样做,因为您会丢失Django Forms提供的许多不错的功能(CSRF保护,验证等).

I would not recommend doing this, because you lose a whole bunch of nice features that Django Forms provides (CSRF protection, validation, etc).

其他教程

由于此问题的原始形式要求提供一些教程:官方Django Wiki 具有

Since the original form of this question asked for some tutorials: the official Django wiki has a page listing some tutorials, some of which deal with forms. Be aware that a lot of those tutorials are quite old (mostly from 2007-2009).

这篇关于如何在我的Django文件中包含一个表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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