创建django管理员喜欢非管理员前端用户的操作 - 如何 [英] creating django admin like actions for non-admin front-end users - how to

查看:97
本文介绍了创建django管理员喜欢非管理员前端用户的操作 - 如何的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在管理员之外创建一个管理类动作。因此,用户应该能够使用复选框来选择对象,并且在所有选定对象上选择所选操作的下拉列表选择操作后。



我想到了以下方法。



为.html模板中的每个对象创建一个复选框。结果将是(我从管理员那里获取):

 < td>< input type =checkboxclass =action-selectvalue =24name =_ selected_action/>< / td> 

然后创建操作下拉菜单(也从管理员那里):

 < div class =actions> 
< label>动作:< select name =action>
< option value =selected =selected> ---------< / option>
< option value =delete_selected>删除所选联系人< / option>
< / select>< / label>
< button type =submitclass =buttontitle =运行所选动作name =indexvalue =0> Go< / button>
< / div>

现在我问自己如何将此操作下拉列表映射到python函数。可能是一个函数,我将放在我想要应用此操作的模型对象内。



我希望有人能告诉我。



下一个点将是如何检查这个函数哪些对象被选中。
当我发现这是如何工作的,我可以使用这个对象并返回一个HttpResponse。



我认为应该是创建一个行为的一切行为。这是正确的还是缺少的东西?



编辑:我的解决方案



最后我想出了以下解决方案:



我创建了一个名为action_handler的函数,该函数接收请求及其将执行的模型。从post querydicts我得到所选动作(request.POST。 getitem ('action'))和所选对象(request.POST.getlist('_ selected_for_action'))。



根据输入和进程,函数返回一些值,它告诉调用视图在action_handler中发生了什么。

  @login_required 
def action_handler(request,model):

PARAMETERS
model =执行操作的django模型

返回值
0 - POST参数动作不可用
- 没有定义POST参数selected_action
- selected_ids为空
- object_list为空
1 - 成功执行delete_selected操作
2 - 成功执行new_selection操作

描述
处理任意模型的所有操作
操作:
删除选择 - 调用通用删除m方法,delete_objects(request,model,selected_ids)

try:
selected_action = request.POST .__ getitem __('action')
selected_ids = request.POST.getlist ('_selected_for_action')
object_list = model.objects.filter(pk__in = selected_ids)
如果object_list.count()< 1:
request.user.message_set.create(message ='请至少选择一个项目!')
返回0
如果selected_action =='delete_selected':
try:
action_approved = request.POST .__ getitem __('action_approved')
如果action_approved =='1':
delete_objects(request,model,selected_ids)
return 1

除了KeyError:
#action_approved param不可用
#show对象检查页面删除批准
context = {
'action_name':selected_action,
'object_list':object_list,
}
return render_to_response(crm / object_delete_check.html,context,
context_instance = RequestContext(request))

如果选择_action =='new_selection':
#将所选对象添加到新的cs选择
now = datetime.now()
stamp = now.strftime(%Y-%m-% d /%H:%M)
cs_name ='cs_auto_created_'+ str(stamp)
cs = ContactSelection(id = None,name = cs_name)
cs.created_by = request.user
cs.save()
object_list中的对象:
cs.contacts.add(object)
request.user.message_set.create(message ='成功创建%s选择'%cs.name)
return 2

request.user.message_set.create(message ='此操作不可用!')
返回0

除了KeyError:
request.user.message_set.create(message ='请选择一个动作!')
返回0

删除delete_objects(请求,模型,selected_ids)如下所示:

 $ b $ delete 




删除所有给定的对象的所有对象模型
默认地失败,因为model.delete()总是静默失败
'''
object_list = model.objects.filter(pk__in = selected_ids)
count = object_list.count()
如果count == 1:
name = model._meta.verbose_name.title()
else:
name = model._meta.verbose_name_plural.title()
object_list.delete()
request.user.message_set.create(message ='成功删除%s%s'%(count,name))
return

以这种方式,我可以为不同的视图包含这个action_handler,并且封装了一个独立于该函数所执行的模型的删除函数。 p>

解决方案

这是动态表单的完美之地。一般的想法是制作一个表单,列出用户的所有项目和操作的下拉菜单。所以这很容易映射到一个 ModelMultipleChoiceField ChoiceField

 从django导入表单

def action_formset(qset,actions):
一个表单工厂,返回一个允许用户选择一个特定的动作到
对从查询器中选定的项目子集执行

class _ActionForm(forms.Form):
items = forms.ModelMultipleChoiceField(queryset = qset)
actions = forms.ChoiceField(choices = zip(actions,actions))

返回_ActionForm

#在你的views.py

def action_view(request):

qset = Item.objects.all()#some方式获取你的项目
actions =('tuple','of',' action','names')

formclass = action_formset(qset,actions)

if request.method =='POST':
#deal with selected items
form = formclass(request.POST)
selected_acti on = form.cleaned_data ['action']
selected_qset = form.cleaned_data ['items']
#do与项目有关的东西
return ...

#处理GET请求
form = formclass()

return ...

然后只需像其他任何一样在一个模板中显示此表单。希望有帮助。


I`m thinking of creating an admin action-like behaviour outside the admin. Thus the user should be able to select objects with a checkbox and after selecting an action with the dropdown the selected action is conducted on all selected objects.

I thought of the following approach.

Create a checkbox for each object in the .html template. Result would be this (i took it from the admin):

<td><input type="checkbox" class="action-select" value="24" name="_selected_action" /></td> 

Then create the action dropdown (took it also from the admin):

<div class="actions"> 
            <label>Action: <select name="action"> 
                <option value="" selected="selected">---------</option> 
                <option value="delete_selected">Delete selected contacts</option> 
            </select></label> 
            <button type="submit" class="button" title="Run the selected action" name="index" value="0">Go</button> 
        </div> 

Now i m asking myself how i can map this action dropdown to a python function. Probably a function which i would place inside the model object which i want to apply this action to.

I hope somebody can tell it to me.

The next point would be how i can check in this function which objects have been selected. When i found out how this works, i can work with this objects and return a HttpResponse.

I think that should be everything to create an action like behaviour. Is this correct or is something missing?

Edit: My Solution

Finally I came up with the following solution:

I created a function called action_handler, which takes the request and the model it will act upon. From the post querydicts I get the selected action (request.POST.getitem('action')) and the selected objects (request.POST.getlist('_selected_for_action')).

Based on the input and the process the function returns some values, which tells the calling view what happened in the action_handler.

@login_required
def action_handler(request, model):
    """
    PARAMETERS
    model = the django model upon which the actions are executed

    RETURN VALUES
    0 - POST param action is not available
      - POST param selected_action is not defined
      - selected_ids is empty
      - object_list is empty
    1 - Successfully conducted the delete_selected action
    2 - Successfully conducted the new_selection action

    DESCRIPTION
    handles all actions for arbitrary models
    Action:
        "delete selected" - calls the generic delete method, delete_objects(request, model, selected_ids)
    """
    try:
        selected_action = request.POST.__getitem__('action')
        selected_ids = request.POST.getlist('_selected_for_action')
        object_list = model.objects.filter(pk__in=selected_ids)
        if object_list.count() < 1:
            request.user.message_set.create(message='Please select at least one item!')
            return 0
        if selected_action == 'delete_selected':
            try:
                action_approved = request.POST.__getitem__('action_approved')
                if action_approved == '1':
                    delete_objects(request, model, selected_ids)
                    return 1

            except KeyError:
                #action_approved param is not available
                #show the objects check page for delete approval
                context = {
                    'action_name' : selected_action,
                    'object_list' : object_list,
                }
                return render_to_response("crm/object_delete_check.html", context,
                                       context_instance=RequestContext(request))

        if selected_action == 'new_selection':
            #add the selected objects to a new cs selection
            now = datetime.now()
            stamp = now.strftime("%Y-%m-%d/%H:%M")
            cs_name = 'cs_auto_created_' + str(stamp)
            cs = ContactSelection(id=None, name=cs_name)
            cs.created_by = request.user
            cs.save()
            for object in object_list:
                cs.contacts.add(object)
            request.user.message_set.create(message='Successfully created the %s selection' % cs.name)
            return 2

        request.user.message_set.create(message='This action is not available!')
        return 0

    except KeyError:
        request.user.message_set.create(message='Please select an action!')
        return 0

The delete delete_objects(request, model, selected_ids) looks like this:

@login_required
def delete_objects(request, model, selected_ids):
    '''
    capsulate a bulk delete method
    delete all objects found for the given model
    fails silently since model.delete() always fails silently
    '''
    object_list = model.objects.filter(pk__in=selected_ids)
    count = object_list.count()
    if count == 1:
        name = model._meta.verbose_name.title()
    else:
        name = model._meta.verbose_name_plural.title()
    object_list.delete()
    request.user.message_set.create(message='Successfully deleted %s %s' % (count,name))
    return

This way I'm able to include this action_handler for different views and encapsulate a delete function independend from the model on which the function is acting upon.

解决方案

This is a perfect spot for a dynamic form. The general idea is to make a form which lists all of the items to the user and a dropdown menu of actions. So this easily maps to a ModelMultipleChoiceField and a ChoiceField.

from django import forms

def action_formset(qset, actions):
    """A form factory which returns a form which allows the user to pick a specific action to 
    perform on a chosen subset of items from a queryset.
    """
    class _ActionForm(forms.Form):
        items = forms.ModelMultipleChoiceField(queryset = qset)
        actions = forms.ChoiceField(choices = zip(actions, actions))

    return _ActionForm

#in your views.py

def action_view(request):

    qset = Item.objects.all() #some way to get your items
    actions = ('tuple', 'of', 'action', 'names')

    formclass = action_formset(qset, actions)

    if request.method == 'POST':
        #deal with chosen items
        form = formclass(request.POST)
        chosen_action = form.cleaned_data['action']
        chosen_qset = form.cleaned_data['items']
        #do something with items
        return ...

    #deal with a GET request
    form = formclass()

    return ...

Then just display this form in a template like you would any other. Hope that helps.

这篇关于创建django管理员喜欢非管理员前端用户的操作 - 如何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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