加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python之路,Day14 - It's time for Django

发布时间:2020-12-17 00:05:42 所属栏目:Python 来源:网络整理
导读:本节内容 Django流程介绍 Django url Django view Django models Django template Django form Django admin? Django流程介绍 Django URL div id="s-example" class="section" Example Here’s a sample URLconf: from . import views urlpatterns = [ url(r

本节内容

Django流程介绍

Django url

Django view

Django models

Django template

Django form

Django admin?

Django流程介绍

Django URL

<div id="s-example" class="section">

Example

Here’s a sample URLconf:

from . import views

urlpatterns = [
url(r'^articles/2003/$',views.special_case_2003),url(r'^articles/([0-9]{4})/$',views.year_archive),url(r'^articles/([0-9]{4})/([0-9]{2})/$',views.month_archive),url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$',views.article_detail),]

  

Notes:

    To capture a value from the URL,just put parenthesis around it.
  • There’s no need to add a leading slash,because every URL has that. For example,it’s?,not?.
  • The??in front of each regular expression string is optional but recommended. It tells Python that a string is “raw” – that nothing in the string should be escaped. See?.

Example requests:

    A request to??would match the third entry in the list. Django would call the function.
  • ?would not match any URL patterns,because the third entry in the list requires two digits for the month.
  • ?would match the first pattern in the list,not the second one,because the patterns are tested in order,and the first one is the first test to pass. Feel free to exploit the ordering to insert special cases like this. Here,Django would call the function?
  • ?would not match any of these patterns,because each pattern requires that the URL end with a slash.
  • ?would match the final pattern. Django would call the function.
Named groups

The above example used simple,?non-named?regular-expression groups (via parenthesis) to capture bits of the URL and pass them as?positional?arguments to a view. In more advanced usage,it’s possible to use?named?regular-expression groups to capture URL bits and pass them as?keyword?arguments to a view.

In Python regular expressions,the syntax for named regular-expression groups is?pattern),where??is the name of the group and??is some pattern to match.

Here’s the above example URLconf,rewritten to use named groups:

from . import views

urlpatterns = [
url(r'^articles/2003/$',url(r'^articles/(?P[0-9]{4})/$',url(r'^articles/(?P[0-9]{4})/(?P[0-9]{2})/$',url(r'^articles/(?P[0-9]{4})/(?P[0-9]{2})/(?P[0-9]{2})/$',]

  

This accomplishes exactly the same thing as the previous example,with one subtle difference: The captured values are passed to view functions as keyword arguments rather than positional arguments. For example:

    A request to??would call the function?,instead of?.
  • A request to??would call the function?.

In practice,this means your URLconfs are slightly more explicit and less prone to argument-order bugs – and you can reorder the arguments in your views’ function definitions. Of course,these benefits come at the cost of brevity; some developers find the named-group syntax ugly and too verbose.

<div id="s-what-the-urlconf-searches-against" class="section">

What the URLconf searches against

The URLconf searches against the requested URL,as a normal Python string. This does not include GET or POST parameters,or the domain name.

For example,in a request to?,the URLconf will look for?.

In a request to?,the URLconf will look for?.

The URLconf doesn’t look at the request method. In other words,all request methods –?,?,?,etc. – will be routed to the same function for the same URL.

Captured arguments are always strings

Each captured argument is sent to the view as a plain Python string,regardless of what sort of match the regular expression makes. For example,in this URLconf line:

[0-9]{4})/$',
...the??argument passed to??will be a string,
not an integer,even though the??will only match integer strings.

<h2 style="text-align: left;">Including other URLconfs<a class="headerlink" title="Permalink to this headline" href="https://docs.djangoproject.com/en/1.9/topics/http/urls/#including-other-urlconfs"&gt;?

At any point,your??can “include” other URLconf modules. This essentially “roots” a set of URLs below other ones.

For example,here’s an excerpt of the URLconf for the??itself. It includes a number of other URLconfs:

urlpatterns = [

... snip ...

url(r'^community/',include('django_website.aggregator.urls')),url(r'^contact/',include('django_website.contact.urls')),# ... snip ...

]

  

Note that the regular expressions in this example don’t have a??(end-of-string match character) but do include a trailing slash. Whenever Django encounters??(),it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.

Another possibility is to include additional URL patterns by using a list of??instances. For example,consider this URLconf:

from apps.main import views as main_views
from credit import views as credit_views

extra_patterns = [
url(r'^reports/$',credit_views.report),url(r'^reports/(?P[0-9]+)/$',url(r'^charge/$',credit_views.charge),]

urlpatterns = [
url(r'^$',main_views.homepage),url(r'^help/',include('apps.help.urls')),url(r'^credit/',include(extra_patterns)),]

  

In this example,the??URL will be handled by the??Django view.

This can be used to remove redundancy from URLconfs where a single pattern prefix is used repeatedly. For example,consider this URLconf:

urlpatterns = [
url(r'^(?P[w-]+)-(?Pw+)/history/$',views.history),url(r'^(?P[w-]+)-(?Pw+)/edit/$',views.edit),url(r'^(?P[w-]+)-(?Pw+)/discuss/$',views.discuss),url(r'^(?P[w-]+)-(?Pw+)/permissions/$',views.permissions),]

  

We can improve this by stating the common path prefix only once and grouping the suffixes that differ:

urlpatterns = [
url(r'^(?P[w-]+)-(?Pw+)/',include([
url(r'^history/$',url(r'^edit/$',url(r'^discuss/$',url(r'^permissions/$',])),]

Passing extra options to view functions

URLconfs have a hook that lets you pass extra arguments to your view functions,as a Python dictionary.

The??function can take an optional third argument which should be a dictionary of extra keyword arguments to pass to the view function.

For example:

urlpatterns = [
url(r'^blog/(?P[0-9]{4})/$',views.year_archive,{'foo': 'bar'}),for a request to?<code class="docutils literal">/blog/2005/
,Django will call?<code class="docutils literal"><span class="pre">views.year_archive(request,<span class="pre">foo='bar')
.

This technique is used in the??to pass metadata and options to views.

Passing extra options to?

Similarly,you can pass extra options to?. When you pass extra options to?,?each?line in the included URLconf will be passed the extra options.

For example,these two URLconf sets are functionally identical:

Set one:

urlpatterns = [
url(r'^blog/',include('inner'),{'blogid': 3}),]

inner.py

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

urlpatterns = [
url(r'^archive/$',views.archive),url(r'^about/$',views.about),]

  

urlpatterns = [
url(r'^blog/',include('inner')),]

inner.py

from django.conf.urls import url

urlpatterns = [
url(r'^archive/$',views.archive,views.about,]

  

Note that extra options will?always?be passed to?every?line in the included URLconf,regardless of whether the line’s view actually accepts those options as valid. For this reason,this technique is only useful if you’re certain that every view in the included URLconf accepts the extra options you’re passing.

Django Views

最简单的返回一个字符串形式的view

def my_view(request):
if request.method == 'GET':

    return HttpResponse('result')

如果想直接返回一个html文档

Create your views here.

def test_view(request):
return render(request,'index.html')

  

  

Django Models  

django 本身提供了非常强大易使用的ORM组件,并且支持多种数据库,如sqllite,mysql,progressSql,Oracle等,当然最常用的搭配还是mysql,要启用orm,先要配置好连接数据 的信息

在你创建的project目录下编辑settings.py?

下面要开始学习Django ORM语法了,为了更好的理解,我们来做一个基本的 书籍/作者/出版商 数据库结构。 我们这样做是因为 这是一个众所周知的例子,很多SQL有关的书籍也常用这个举例。

class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()

class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()

class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()

?)相当于数据库的字段类型 (例如??)。例如,??模块等同于下面这张表(用PostgreSQL的??语法描述):

激活这些模型。 将上面的模型所在的app (此例子app是?添加到配置文件的已安装应用列表中即可完成此步骤。

?文件, 找到??设置。??告诉 Django 项目哪些 app 处于激活状态。 缺省情况下如下所示:

使数据库按照模型的配置生成表结构

?并输入下面的内容试试看:

>> from books.models import Publisher >>> p1 = Publisher(name='Apress',address='2855 Telegraph Avenue',... city='Berkeley',state_province='CA',country='U.S.A.',... website='http://www.apress.com/') >>> p1.save() >>> p2 = Publisher(name="O'Reilly",address='10 Fawcett St.',... city='Cambridge',state_province='MA',... website='http://www.oreilly.com/') >>> p2.save() >>> publisher_list = Publisher.objects.all() >>> publisher_list [,]

>> p1 = Publisher.objects.create(name='Apress',... address='2855 Telegraph Avenue',... website='http://www.apress.com/') >>> p2 = Publisher.objects.create(name="O'Reilly",... address='10 Fawcett St.',city='Cambridge',... state_province='MA',... website='http://www.oreilly.com/') >>> publisher_list = Publisher.objects.all() >>> publisher_list

  

?  

当我们打印整个publisher列表时,我们没有得到想要的有用信息,无法把对象区分开来:

,]

我们可以简单解决这个问题,只需要为?对象添加一个方法??。??方法告诉Python如何将对象以unicode的方式显示出来。 为以上三个模型添加方法后,就可以看到效果了。

对__unicode__()的唯一要求就是它要返回一个unicode对象 如果`` __unicode__()`` 方法未返回一个Unicode对象,而返回比如说一个整型数字,那么Python将抛出一个`` TypeError`` 错误,并提示:”coercing to Unicode: need string or buffer,int found” 。  

<h3 id="cn187" class="cn">插入和更新数据
<p id="cn188" class="cn">你已经知道怎么做了: 先使用一些关键参数创建对象实例,如下:


<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">>>> p = Publisher(name='Apress',... address='2855 Telegraph Ave.',... city='Berkeley',... state_province='CA',... country='U.S.A.',... website='http://www.apress.com/')

没有?对数据库做修改。 在调用`` save()`` 方法之前,记录并没有保存至数据库,像这样:

>> p.save()

?模型有一个自动增加的主键??,所以第一次调用??还多做了一件事: 计算这个主键的值并把它赋值给这个对象实例:

>> p.id 52 # this will differ based on your own data

?将不会创建新的记录,而只是修改记录内容(也就是 执行??SQL语句,而不是?语句):

>> p.name = 'Apress Publishing' >>> p.save()

?相当于下面的SQL语句:

>> Publisher.objects.all() [,]

?,而是显式列出了所有字段。 设计的时候就是这样:?会更慢,而且最重要的是列出所有字段遵循了Python 界的一个信条: 明言胜于暗示。

>> Publisher.objects.filter(name='Apress') []

?根据关键字参数来转换成??SQL语句。 前面这个例子 相当于这样:

?来缩小选取范围:

>> Publisher.objects.filter(country="U.S.A.",state_province="CA") []

?SQL从句, 因此上面的代码可以转化成这样:

?操作符是精确匹配的, 其他类型的查找也可以使用:

>> Publisher.objects.filter(name__contains="press") []

name?和??之间有双下划线。和Python一样,Django也使用双下划线来表明会进行一些魔术般的操作。这里,部分会被Django翻译成语句:

(大小写不敏感的),,还有

<h3 id="cn245" class="cn">获取单个对象


<p id="cn246" class="cn">上面的例子中filter() 函数返回一个记录集,这个记录集是一个列表。 相对列表来说,有些时候我们更需要获取单个的对象, get() 方法就是在此时使用的:


<div class="cnblogs_Highlighter">
<pre class="brush:python;gutter:true;">>>> Publisher.objects.get(name="Apress")

>> Publisher.objects.get(country="U.S.A.") Traceback (most recent call last): ... MultipleObjectsReturned: get() returned more than one Publisher -- it returned 2! Lookup parameters were {'country': 'U.S.A.'}

>> Publisher.objects.get(name="Penguin") Traceback (most recent call last): ... DoesNotExist: Publisher matching query does not exist.

?异常 是 Publisher 这个 model 类的一个属性,即?。在你的应用中,你可以捕获并处理这个异常,像这样:

?这个方法就可以搞定了。

>> Publisher.objects.order_by("name") [,]

?例子差不多,SQL语句里多了指定排序的部分:


>> Publisher.objects.order_by("address") [,]

Publisher.objects.order_by("state_province")
[,<Publisher: O'Reilly>] 

>> Publisher.objects.order_by("state_province","address") [,]

?前缀:

>> Publisher.objects.order_by("-name") [,]

?显得有点啰嗦。 大多数时间你通常只会对某些 字段进行排序。 在这种情况下,Django让你可以指定模型的缺省排序方式:

def __unicode__(self):
    return self.name

class Meta:
    ordering = ['name']</pre>

,内嵌于??这个类的定义中(如果??是顶格的,那么??在它之下要缩进4个空格--按 Python 的传统 )。你可以在任意一个 模型 类中使用?类,来设置一些与特定模型相关的选项。?还可设置很多其它选项,现在,我们关注?这个选项就够了。 如果你设置了这个选项,那么除非你检索时特意额外地使用了?,否则,当你使用 Django 的数据库 API 去检索时,对象的相关返回值默认地都会按??字段排序。

>> Publisher.objects.filter(country="U.S.A.").order_by("-name") [,]

?和??的组合:

>> Publisher.objects.order_by('name')[0]

>> Publisher.objects.order_by('name')[0:2]

>> Publisher.objects.order_by('name')[-1] Traceback (most recent call last): ... AssertionError: Negative indexing is not supported.

>> Publisher.objects.order_by('-name')[0]

>> p = Publisher.objects.get(name='Apress') >>> p.name = 'Apress Publishing' >>> p.save()

UPDATE books_publisher SET
name = 'Apress Publishing',website = 'http://www.apress.com'
WHERE id = 52;

>> Publisher.objects.filter(id=52).update(name='Apress Publishing')

>> Publisher.objects.all().update(country='USA') 2

>> p = Publisher.objects.get(name="O'Reilly") >>> p.delete() >>> Publisher.objects.all() []

>> Publisher.objects.filter(country='USA').delete() >>> Publisher.objects.all().delete() >>> Publisher.objects.all() []

>> Publisher.objects.delete() Traceback (most recent call last): File "",line 1,in AttributeError: 'Manager' object has no attribute 'delete' 

>> Publisher.objects.all().delete()

>> Publisher.objects.filter(country='USA').delete()

模板系统?(Template System)来实现这种模式,这就是本章要具体讨论的问题。

Django 模版基本语法

>> from django.template import Context,Template >>> t = Template('My name is {{ name }}.') >>> c = Context({'name': 'Stephane'}) >>> t.render(c) u'My name is Stephane.'

?对象,你就可以通过它渲染多个context, 例如:

>> from django.template import Template,Context >>> t = Template('Hello,{{ name }}') >>> print t.render(Context({'name': 'John'})) Hello,John >>> print t.render(Context({'name': 'Julie'})) Hello,Julie >>> print t.render(Context({'name': 'Pat'})) Hello,Pat

模板创建然后多次调用render()方法渲染会更为高效:

Good

t = Template('Hello,{{ name }}')
for name in ('John','Pat'):
print t.render(Context({'name': name}))

)。

>> from django.template import Template,Context >>> person = {'name': 'Sally','age': '43'} >>> t = Template('{{ person.name }} is {{ person.age }} years old.') >>> c = Context({'person': person}) >>> t.render(c) u'Sally is 43 years old.'

?对象有??、??和??几个属性,你同样可以在模板中使用句点来访问这些属性:

>> from django.template import Template,Context >>> import datetime >>> d = datetime.date(1993,5,2) >>> d.year 1993 >>> d.month 5 >>> d.day 2 >>> t = Template('The month is {{ date.month }} and the year is {{ date.year }}.') >>> c = Context({'date': d}) >>> t.render(c) u'The month is 5 and the year is 1993.'

>> from django.template import Template,Context >>> class Person(object): ... def __init__(self,first_name,last_name): ... self.first_name,self.last_name = first_name,last_name >>> t = Template('Hello,{{ person.first_name }} {{ person.last_name }}.') >>> c = Context({'person': Person('John','Smith')}) >>> t.render(c) u'Hello,John Smith.'

?和??方法,你在模板中可以使用同样的句点语法来调用它们:

>> from django.template import Template,Context >>> t = Template('{{ var }} -- {{ var.upper }} -- {{ var.isdigit }}') >>> t.render(Context({'var': 'hello'})) u'hello -- HELLO -- False' >>> t.render(Context({'var': '123'})) u'123 -- 123 -- True'

>> from django.template import Template,Context >>> t = Template('Item 2 is {{ items.2 }}.') >>> c = Context({'items': ['apples','bananas','carrots']}) >>> t.render(c) u'Item 2 is carrots.'

  

?模板标签

?。该标签允许在(模板中)包含其它的模板的内容。 标签的参数是所要包含的模板名称,可以是一个变量,也可以是用单/双引号硬编码的字符串。 每当在多个模板中出现相同的代码时,就应该考虑是否要使用??来减少重复。

?模板。这两个例子是等价的,它们证明单/双引号都是允许的。

?模板的内容:

服务器端的 includes?,你可以在 HTML 页面中使用该指令将一个网页嵌入到另一个中。 事实上, Django 通过刚才讲述的??支持了这种方法。 但是用 Django 解决此类问题的首选方法是使用更加优雅的策略——?模板继承?。

?文件,为??创建一个更加完整的模板来体会一下这种做法:

The current time

My helpful timestamp site

It is now {{ current_date }}.

<hr>
<p>Thanks for visiting my site.</p>

?视图创建另一个模板会发生什么事情呢?

Future time

My helpful timestamp site

In {{ hour_offset }} hour(s),it will be {{ next_time }}.

<hr>
<p>Thanks for visiting my site.</p>

?文件:

?:

Thanks for visiting my site.

My??标题,但是这个标题不能放在??中,因为每个页面的??是不同的。 如果我们将??包含在头部,我们就不得不包含??,但这样又不允许在每个页面对它进行定制。 何去何从呢?

不同?的代码段进行定义,而不是?共同?代码段。

基础模板?, 该框架之后将由?子模板?所继承。 以下是我们目前所讲述范例的基础模板:

{% block title %}{% endblock %}

My helpful timestamp site

{% block content %}{% endblock %} {% block footer %}

Thanks for visiting my site.

{% endblock %}

?的模板定义了一个简单的 HTML 框架文档,我们将在本站点的所有页面中使用。 子模板的作用就是重载、添加或保留那些块的内容。 (如果你一直按顺序学习到这里,保存这个文件到你的template目录下,命名为??.)

?。 所有的??标签告诉模板引擎,子模板可以重载这些部分。 每个标签所要做的是告诉模板引擎,该模板下的这一块内容将有可能被子模板覆盖。

?模板来 使用它:

{% block title %}The current time{% endblock %}

{% block content %}

It is now {{ current_date }}.

{% endblock %}

?视图创建一个模板,看起来是这样的:

{% block title %}Future time{% endblock %}

{% block content %}

In {{ hour_offset }} hour(s),it will be {{ next_time }}.

{% endblock %}

独一无二?的代码。 无需多余的部分。 如果想进行站点级的设计修改,仅需修改??,所有其它模板会立即反映出所作修改。

?模板时,模板引擎发现了??标签, 注意到该模板是一个子模板。 模板引擎立即装载其父模板,即本例中的??。

?中的三个??标签,并用子模板的内容替换这些 block 。因此,引擎将会使用我们在??中定义的标题,对??也是如此。 所以,网页标题一块将由替换,同样地,网页的内容一块将由?替换。

?块,模板系统将使用在父模板中定义的值。 父模板??标签中的内容总是被当作一条退路。

    ?模板,在其中定义站点的主要外观感受。 这些都是不常修改甚至从不修改的部分。

    ?模板(例如,??和??)。这些模板对?进行拓展,并包含区域特定的风格与设计。

    ?,必须保证其为模板中的第一个模板标记。 否则,模板继承将不起作用。

    ?标签越多越好。 记住,子模板不必定义父模板中所有的代码块,因此你可以用合理的缺省值对一些代码块进行填充,然后只对子模板所需的代码块进行(重)定义。 俗话说,钩子越多越好。

    ?中。

    这个标签吧,这一个魔法变量将会表现出父模板中的内容。 如果只想在上级代码块基础上添加内容,而不是全部重载,该变量就显得非常有用了。

    ?。 存在这样的限制是因为block 标签的工作方式是双向的。 也就是说,block 标签不仅挖了一个要填的坑,也定义了在模板中这个坑所填充的内容。如果模板中出现了两个相同名称的?{% block %}?标签,父模板将无从得知要使用哪个块的内容。

django中的Form一般有两种功能:

  • 输入html
  • 验证用户输入
django django.core.exceptions <span style="color: #0000ff;">def<span style="color: #000000;"> mobile_validate(value):
mobile_re
= re.compile(r<span style="color: #800000;">'
<span style="color: #800000;">^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$
<span style="color: #800000;">'
<span style="color: #000000;">)
<span style="color: #0000ff;">if
<span style="color: #0000ff;">not
<span style="color: #000000;"> mobile_re.match(value):
<span style="color: #0000ff;">raise
ValidationError(<span style="color: #800000;">'
<span style="color: #800000;">手机号码格式错误<span style="color: #800000;">'<span style="color: #000000;">)

<span style="color: #0000ff;">class<span style="color: #000000;"> PublishForm(forms.Form):

user_type_choice </span>=<span style="color: #000000;"&gt; (
    (0,u</span><span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;普通用户</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;),(</span>1,u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;高级用户</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;),)

user_type </span>= forms.IntegerField(widget=forms.widgets.Select(choices=<span style="color: #000000;"&gt;user_type_choice,attrs</span>={<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;class</span><span style="color: #800000;"&gt;'</span>: <span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;form-control</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;}))

title </span>= forms.CharField(max_length=20<span style="color: #000000;"&gt;,min_length</span>=5<span style="color: #000000;"&gt;,error_messages</span>={<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;required</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;标题不能为空</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;,</span><span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;min_length</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;标题最少为5个字符</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;,</span><span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;max_length</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;标题最多为20个字符</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;},widget</span>=forms.TextInput(attrs={<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;class</span><span style="color: #800000;"&gt;'</span>: <span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;form-control</span><span style="color: #800000;"&gt;"</span><span style="color: #000000;"&gt;,</span><span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;placeholder</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;标题5-20个字符</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;}))

memo </span>= forms.CharField(required=<span style="color: #000000;"&gt;False,max_length</span>=256<span style="color: #000000;"&gt;,widget</span>=forms.widgets.Textarea(attrs={<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;class</span><span style="color: #800000;"&gt;'</span>: <span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;form-control no-radius</span><span style="color: #800000;"&gt;"</span>,<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;placeholder</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;详细描述</span><span style="color: #800000;"&gt;'</span>,<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;rows</span><span style="color: #800000;"&gt;'</span>: 3<span style="color: #000000;"&gt;}))

phone </span>= forms.CharField(validators=<span style="color: #000000;"&gt;[mobile_validate,],error_messages</span>={<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;required</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;手机不能为空</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;},</span><span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;placeholder</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;手机号码</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;}))

email </span>= forms.EmailField(required=<span style="color: #000000;"&gt;False,error_messages</span>={<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;required</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;邮箱不能为空</span><span style="color: #800000;"&gt;'</span>,<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;invalid</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;邮箱格式错误</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;},widget</span>=forms.TextInput(attrs={<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;class</span><span style="color: #800000;"&gt;'</span>: <span style="color: #800000;"&gt;"</span><span style="color: #800000;"&gt;form-control</span><span style="color: #800000;"&gt;"</span>,<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;placeholder</span><span style="color: #800000;"&gt;'</span>: u<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;邮箱</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;}))

<span style="color: #800000;">'''<span style="color: #800000;">
def init(self,*args,*kwargs):
super(SampleImportForm,self).init(
args,**kwargs)

self.fields['idc'].widget.choices = models.IDC.objects.all().order_by('id').values_list('id','display')
self.fields['business_unit'].widget.choices = models.BusinessUnit.objects.all().order_by('id').values_list('id','name')

Forms
<span style="color: #800000;">'''

request.method == request_form = request_dict = render(request,,{ pub_form = render(request,{:pub_form})
</span><span style="color: #0000ff;"&gt;<</span><span style="color: #800000;"&gt;div</span><span style="color: #0000ff;"&gt;></span>{{ pub_form.user_type }} {{ pub_form.errors.title }}<span style="color: #0000ff;"&gt;</</span><span style="color: #800000;"&gt;div</span><span style="color: #0000ff;"&gt;></span> <span style="color: #0000ff;"&gt;<</span><span style="color: #800000;"&gt;div</span><span style="color: #0000ff;"&gt;></span>{{ pub_form.title }}<span style="color: #0000ff;"&gt;</</span><span style="color: #800000;"&gt;div</span><span style="color: #0000ff;"&gt;></span> <span style="color: #0000ff;"&gt;<</span><span style="color: #800000;"&gt;div</span><span style="color: #0000ff;"&gt;></span>{{ pub_form.email }}<span style="color: #0000ff;"&gt;</</span><span style="color: #800000;"&gt;div</span><span style="color: #0000ff;"&gt;></span> <span style="color: #0000ff;"&gt;<</span><span style="color: #800000;"&gt;div</span><span style="color: #0000ff;"&gt;></span>{{ pub_form.phone }}<span style="color: #0000ff;"&gt;</</span><span style="color: #800000;"&gt;div</span><span style="color: #0000ff;"&gt;></span> <span style="color: #0000ff;"&gt;<</span><span style="color: #800000;"&gt;div</span><span style="color: #0000ff;"&gt;></span>{{ pub_form.memo }}<span style="color: #0000ff;"&gt;</</span><span style="color: #800000;"&gt;div</span><span style="color: #0000ff;"&gt;></span><span style="color: #000000;"&gt; {% if pub_form.errors %} {{ pub_form.errors }} {% endif %} </span><span style="color: #0000ff;"&gt;<</span><span style="color: #800000;"&gt;input </span><span style="color: #ff0000;"&gt;type</span><span style="color: #0000ff;"&gt;="submit"</span><span style="color: #ff0000;"&gt; value</span><span style="color: #0000ff;"&gt;="提交"</span><span style="color: #0000ff;"&gt;></span> <span style="color: #0000ff;"&gt;</</span><span style="color: #800000;"&gt;form</span><span style="color: #0000ff;"&gt;></span>

<span style="color: #0000ff;"></<span style="color: #800000;">div<span style="color: #0000ff;">>

扩展:ModelForm

在使用Model和Form时,都需要对字段进行定义并指定类型,通过ModelForm则可以省去From中字段的定义

class Meta: model = models.Admin #fields = '__all__' fields = ('username','email') widgets = { 'email' : forms.PasswordInput(attrs={'class':"alex"}),}

  

Django Admin

django amdin是django提供的一个后台管理页面,改管理页面提供完善的html和css,使得你在通过Model创建完数据库表之后,就可以对数据进行增删改查,而使用django admin 则需要以下步骤:

  • 创建后台管理员
  • 配置url
  • 注册和配置django admin后台管理页面

1、创建后台管理员

2、配置后台管理url

3、注册和配置django admin 后台管理页面

a、在admin中执行如下配置

from app01 import models

admin.site.register(models.UserType)
admin.site.register(models.UserInfo)
admin.site.register(models.UserGroup)
admin.site.register(models.Asset)

b、设置数据表名称

class Meta: verbose_name = '用户类型' verbose_name_plural = '用户类型'

c、自定义页面展示

admin.site.register(models.UserType)
admin.site.register(models.UserInfo,UserInfoAdmin)
admin.site.register(models.UserGroup)

d、添加页面搜索过滤等功能

from app01 import models

class UserInfoAdmin(admin.ModelAdmin):
list_display = ('username','email')
search_fields = ('username','email')
list_filter = ('username','email')

admin.site.register(models.UserType)
admin.site.register(models.UserInfo,UserInfoAdmin)
admin.site.register(models.UserGroup)
admin.site.register(models.Asset)

  

  

  

  

  

  

  

  

  

  

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读