1. 程式人生 > 實用技巧 >9-crm專案-kingadmin,修改和新增頁面---動態modelform生成

9-crm專案-kingadmin,修改和新增頁面---動態modelform生成

修改功能實現

(1)給第一列新增一個a標籤

(2)kingadmin/urls.py

urlpatterns = [
        #修改頁面
    url(r'^(\w+)/(\w+)/(\d+)/change/$', views.table_obj_change,name='table_obj_change'),
]

(3)kingamdin/views.py

@login_required
def table_obj_change(request,app_name,model_name,obj_id):
    '''kingadmin 資料修改頁'''

    return render(request,'
kingadmin/table_obj_change.html')

(4)table_obj_change.html

{#kingadmin/templates/kingadmin/table_obj_change.html#}

{% extends 'kingadmin/index.html' %}
{% load kingadmin_tags %}

{% block right-content-container %}
<h2 class="page-header">app</h2>

<div>
change
</div>

{% endblock %}

(5)動態modelform生成

# kingadmin/formhandle.py

from django.forms import ModelForm

def create_dynamic_model_form(admin_class):
    '''動態生成modelform'''

    class Meta:
        model = admin_class.model
        fields = "__all__"
        
    #動態生成ModelForm
    dynamic_form = type("DynamicModelForm",(ModelForm,),{'
Meta':Meta}) return dynamic_form

新增功能實現

(1)kingadmin/url.py

#增加
    url(r'^(\w+)/(\w+)/add/$', views.table_obj_add,name='table_obj_add'),

(2)kingadmin/views.py

@login_required
def table_obj_add(request,app_name,model_name):
    '''kingadmin 資料新增'''

    admin_class = site.enable_admins[app_name][model_name]
    model_form = form_handle.create_dynamic_model_form(admin_class)

    if request.method == 'GET':
        form_obj = model_form()
    elif request.method == 'POST':
        form_obj = model_form(data=request.POST)
        if form_obj.is_valid():
            form_obj.save()
            #跳轉到的頁面
            return redirect("/kingadmin/%s/%s/"%(app_name,model_name))
    return render(request, 'kingadmin/table_obj_add.html', locals())

(3)前端頁面

##########################