最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

自定義django admin model表單提交的例子

 更新時(shí)間:2019年08月23日 14:51:57   作者:jingxindeyi  
今天小編就為大家分享一篇自定義django admin model表單提交的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

如下所示:

希望可以從對(duì)admin提交的密碼加密,并驗(yàn)證電話號(hào)碼均為數(shù)字。

查看admin.py

from django.contrib import admin
class courseAdmin(admin.ModelAdmin)

我們自定義的管理類,繼承與admin.ModelAdmin

查看對(duì)應(yīng)admin模塊對(duì)應(yīng)源碼

__init__.py

from django.contrib.admin.options import (
 HORIZONTAL, VERTICAL, ModelAdmin, StackedInline, TabularInline,FaultyAdmin,
)

從django.contrib.admin.options導(dǎo)入 ModelAdmin



options.py ModelAdmin源碼比較長(zhǎng),就不全部列出了,看比較關(guān)鍵的地方

def get_urls(self):
  from django.conf.urls import url

  def wrap(view):
   def wrapper(*args, **kwargs):
    return self.admin_site.admin_view(view)(*args, **kwargs)
   wrapper.model_admin = self
   return update_wrapper(wrapper, view)

  info = self.model._meta.app_label, self.model._meta.model_name

  urlpatterns = [
   url(r'^$', wrap(self.changelist_view), name='%s_%s_changelist' % info),
   url(r'^add/$', wrap(self.add_view), name='%s_%s_add' % info),
   url(r'^(.+)/history/$', wrap(self.history_view), name='%s_%s_history' % info),
   url(r'^(.+)/delete/$', wrap(self.delete_view), name='%s_%s_delete' % info),
   url(r'^(.+)/change/$', wrap(self.change_view), name='%s_%s_change' % info),
   # For backwards compatibility (was the change url before 1.9)
   url(r'^(.+)/$', wrap(RedirectView.as_view(
    pattern_name='%s:%s_%s_change' % ((self.admin_site.name,) + info)
   ))),
  ]
  return urlpatterns

可以看到add操作,交由add_view函數(shù)

 def add_view(self, request, form_url='', extra_context=None):
  return self.changeform_view(request, None, form_url, extra_context)
@csrf_protect_m
 def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
  with transaction.atomic(using=router.db_for_write(self.model)):
   return self._changeform_view(request, object_id, form_url, extra_context)

 def _changeform_view(self, request, object_id, form_url, extra_context):
  to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR))
  if to_field and not self.to_field_allowed(request, to_field):
   raise DisallowedModelAdminToField("The field %s cannot be referenced." % to_field)

  model = self.model
  opts = model._meta

  if request.method == 'POST' and '_saveasnew' in request.POST:
   object_id = None

  add = object_id is None

  if add:
   if not self.has_add_permission(request):
    raise PermissionDenied
   obj = None

  else:
   obj = self.get_object(request, unquote(object_id), to_field)

   if not self.has_change_permission(request, obj):
    raise PermissionDenied

   if obj is None:
    return self._get_obj_does_not_exist_redirect(request, opts, object_id)

  ModelForm = self.get_form(request, obj)
  if request.method == 'POST':
   form = ModelForm(request.POST, request.FILES, instance=obj)
   if form.is_valid():
    form_validated = True
    new_object = self.save_form(request, form, change=not add)
   else:
    form_validated = False
    new_object = form.instance
   formsets, inline_instances = self._create_formsets(request, new_object, change=not add)
   if all_valid(formsets) and form_validated:
    self.save_model(request, new_object, form, not add)
    self.save_related(request, form, formsets, not add)
    change_message = self.construct_change_message(request, form, formsets, add)
    if add:
     self.log_addition(request, new_object, change_message)
     return self.response_add(request, new_object)
    else:
     self.log_change(request, new_object, change_message)
     return self.response_change(request, new_object)
   else:
    form_validated = False
  else:
   if add:
    initial = self.get_changeform_initial_data(request)
    form = ModelForm(initial=initial)
    formsets, inline_instances = self._create_formsets(request, form.instance, change=False)
   else:
    form = ModelForm(instance=obj)
    formsets, inline_instances = self._create_formsets(request, obj, change=True)

  adminForm = helpers.AdminForm(
   form,
   list(self.get_fieldsets(request, obj)),
   self.get_prepopulated_fields(request, obj),
   self.get_readonly_fields(request, obj),
   model_admin=self)
  media = self.media + adminForm.media

  inline_formsets = self.get_inline_formsets(request, formsets, inline_instances, obj)
  for inline_formset in inline_formsets:
   media = media + inline_formset.media

  context = dict(
   self.admin_site.each_context(request),
   title=(_('Add %s') if add else _('Change %s')) % force_text(opts.verbose_name),
   adminform=adminForm,
   object_id=object_id,
   original=obj,
   is_popup=(IS_POPUP_VAR in request.POST or
      IS_POPUP_VAR in request.GET),
   to_field=to_field,
   media=media,
   inline_admin_formsets=inline_formsets,
   errors=helpers.AdminErrorList(form, formsets),
   preserved_filters=self.get_preserved_filters(request),
  )

  # Hide the "Save" and "Save and continue" buttons if "Save as New" was
  # previously chosen to prevent the interface from getting confusing.
  if request.method == 'POST' and not form_validated and "_saveasnew" in request.POST:
   context['show_save'] = False
   context['show_save_and_continue'] = False
   # Use the change template instead of the add template.
   add = False

  context.update(extra_context or {})




form = ModelForm(request.POST, request.FILES, instance=obj)

這里找到form表單的內(nèi)容

form.is_valid()

驗(yàn)證表單內(nèi)容是否合法,查看這個(gè)函數(shù)

首先找到ModelForm類

django\forms\models.py

class ModelForm(six.with_metaclass(ModelFormMetaclass, BaseModelForm)):
 pass

查看BaseModelForm

class BaseModelForm(BaseForm):



django\forms\forms.py
class BaseForm(object):
 def is_valid(self):
  """
  Returns True if the form has no errors. Otherwise, False. If errors are
  being ignored, returns False.
  """

  return self.is_bound and not self.errors
  @property
 def errors(self):
  "Returns an ErrorDict for the data provided for the form"
  if self._errors is None:
   self.full_clean()
  return self._errors

def full_clean(self):
  """
  Cleans all of self.data and populates self._errors and
  self.cleaned_data.
  """
  self._errors = ErrorDict()
  if not self.is_bound: # Stop further processing.
   return
  self.cleaned_data = {}
  # If the form is permitted to be empty, and none of the form data has
  # changed from the initial data, short circuit any validation.
  if self.empty_permitted and not self.has_changed():
   return

  self._clean_fields()
  self._clean_form()
  self._post_clean()
 def _clean_fields(self):
  for name, field in self.fields.items():
   # value_from_datadict() gets the data from the data dictionaries.
   # Each widget type knows how to retrieve its own data, because some
   # widgets split data over several HTML fields.
   #print(type(name))
   print(name,field)
   if field.disabled:
    value = self.get_initial_for_field(field, name)
   else:
    value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
   try:
    if isinstance(field, FileField):
     initial = self.get_initial_for_field(field, name)
     value = field.clean(value, initial)
    else:
     value = field.clean(value)
    self.cleaned_data[name] = value
    if hasattr(self, 'clean_%s' % name):
     value = getattr(self, 'clean_%s' % name)()
     self.cleaned_data[name] = value
   except ValidationError as e:
    #print(e)
    self.add_error(name, e)

上面列出函數(shù)在表單驗(yàn)證的過(guò)程中,順序調(diào)用,可以看到添加錯(cuò)誤的主要函數(shù)為_(kāi)clean_fields,雖然沒(méi)有繼續(xù)仔細(xì)查看,但感覺(jué)關(guān)鍵在于field.clean(value),對(duì)應(yīng)的field在我們聲明對(duì)應(yīng)model類時(shí)會(huì)保存相應(yīng)字段的信息,這里做檢查,如果不符合,則raise ValidationError,符合的haul就把新的數(shù)據(jù)放入到表單的cleaned_data中。

這一段來(lái)自官網(wǎng)的教程,這里指出錯(cuò)誤信息的關(guān)鍵字包括,null, blank, invalid, invalid_choice, unique, and unique_for_date。剛才的clean函數(shù)應(yīng)該就是檢查這些地方。

The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override. Error message keys include null, blank, invalid, invalid_choice, unique, and unique_for_date. Additional error message keys are specified for each field in the Field types section below.

到了這一部,基本已經(jīng)可以達(dá)到目的了,我們可以看到 self.add_error函數(shù)。

然后回到options.py的ModelAdmin,我們可以寫(xiě)一個(gè)類繼承ModelAdmin,然后重寫(xiě)新類的_changeform_view函數(shù),避免對(duì)其它部分造成影響。

重寫(xiě)部分如下:

if form.is_valid():
    form_validated = True
    if not re.match('\d+',form.data['tel']):
     form_validated=False
     form.add_error('tel','電話號(hào)碼必須為純數(shù)字')
    if not re.match('\d+',form.data['number']):
     form_validated=False
     form.add_error('number','學(xué)工號(hào)必須為純數(shù)字')
    if not form_validated:
     new_object=form.instance
    else:
     passw=form.data['password']
     m=md5()
     m.update(passw.encode('utf-8'))
     form.data['password']=m.hexdigest()
     new_object = self.save_form(request, form, change=not add)

以上這篇自定義django admin model表單提交的例子就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python設(shè)計(jì)模式之橋接模式原理與用法實(shí)例分析

    Python設(shè)計(jì)模式之橋接模式原理與用法實(shí)例分析

    這篇文章主要介紹了Python設(shè)計(jì)模式之橋接模式原理與用法,結(jié)合具體實(shí)例形式分析了Python橋接模式的相關(guān)概念、原理、定義及使用方法,需要的朋友可以參考下
    2019-01-01
  • python tensorflow學(xué)習(xí)之識(shí)別單張圖片的實(shí)現(xiàn)的示例

    python tensorflow學(xué)習(xí)之識(shí)別單張圖片的實(shí)現(xiàn)的示例

    本篇文章主要介紹了python tensorflow學(xué)習(xí)之識(shí)別單張圖片的實(shí)現(xiàn)的示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-02-02
  • 詳解 Python 讀寫(xiě)XML文件的實(shí)例

    詳解 Python 讀寫(xiě)XML文件的實(shí)例

    這篇文章主要介紹了詳解 Python 讀寫(xiě)XML文件的實(shí)例的相關(guān)資料,Python 生成XML文件和Python 讀取XML 的實(shí)例,需要的朋友可以參考下
    2017-08-08
  • Django中的Signal代碼詳解

    Django中的Signal代碼詳解

    這篇文章主要介紹了Django中的Signal代碼詳解,分享了相關(guān)代碼示例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下
    2018-02-02
  • 利用python求解物理學(xué)中的雙彈簧質(zhì)能系統(tǒng)詳解

    利用python求解物理學(xué)中的雙彈簧質(zhì)能系統(tǒng)詳解

    這篇文章主要給大家介紹了關(guān)于利用python如何求解物理學(xué)中的雙彈簧質(zhì)能系統(tǒng)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。
    2017-09-09
  • Python爬蟲(chóng)之模擬知乎登錄的方法教程

    Python爬蟲(chóng)之模擬知乎登錄的方法教程

    在爬蟲(chóng)過(guò)程中,有些頁(yè)面在登錄之前是被禁止抓取的,這個(gè)時(shí)候就需要模擬登陸了,下面這篇文章主要給大家介紹了利用Python爬蟲(chóng)模擬知乎登錄的方法教程,文中介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來(lái)一起看看吧。
    2017-05-05
  • Python+ChatGPT實(shí)現(xiàn)5分鐘快速上手編程

    Python+ChatGPT實(shí)現(xiàn)5分鐘快速上手編程

    最近一段時(shí)間chatGPT火爆出圈!無(wú)論是在互聯(lián)網(wǎng)行業(yè),還是其他各行業(yè)都賺足了話題。俗話說(shuō):“外行看笑話,內(nèi)行看門(mén)道”,今天從chatGPT個(gè)人體驗(yàn)感受以及如何用的角度來(lái)分享一下
    2023-02-02
  • 基于Python實(shí)現(xiàn)批量縮放圖片(視頻)尺寸

    基于Python實(shí)現(xiàn)批量縮放圖片(視頻)尺寸

    這篇文章主要為大家詳細(xì)介紹了如何通過(guò)Python語(yǔ)言實(shí)現(xiàn)批量縮放圖片(視頻)尺寸的功能,文中的示例代碼簡(jiǎn)潔易懂,感興趣的小伙伴可以跟隨小編一起了解一下
    2023-03-03
  • Python協(xié)程操作之gevent(yield阻塞,greenlet),協(xié)程實(shí)現(xiàn)多任務(wù)(有規(guī)律的交替協(xié)作執(zhí)行)用法詳解

    Python協(xié)程操作之gevent(yield阻塞,greenlet),協(xié)程實(shí)現(xiàn)多任務(wù)(有規(guī)律的交替協(xié)作執(zhí)行)用法詳解

    這篇文章主要介紹了Python協(xié)程操作之gevent(yield阻塞,greenlet),協(xié)程實(shí)現(xiàn)多任務(wù)(有規(guī)律的交替協(xié)作執(zhí)行)用法,結(jié)合實(shí)例形式較為詳細(xì)的分析了協(xié)程的功能、原理及gevent、greenlet實(shí)現(xiàn)協(xié)程,以及協(xié)程實(shí)現(xiàn)多任務(wù)相關(guān)操作技巧,需要的朋友可以參考下
    2019-10-10
  • 使用python生成楊輝三角形的示例代碼

    使用python生成楊輝三角形的示例代碼

    這篇文章主要介紹了使用python生成楊輝三角形的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-08-08

最新評(píng)論

怀宁县| 江孜县| 镇沅| 香格里拉县| 临潭县| 汶川县| 石河子市| 织金县| 金溪县| 柞水县| 青神县| 镶黄旗| 睢宁县| 伊春市| 锦州市| 通州区| 涿鹿县| 务川| 陇南市| 广水市| 弋阳县| 西峡县| 泰兴市| 吴桥县| 内江市| 岳池县| 密山市| 黔西县| 莱西市| 松阳县| 名山县| 贵溪市| 绿春县| 利辛县| 大丰市| 宣化县| 丰顺县| 日照市| 长宁区| 安塞县| 长兴县|