将模板表单包含到django admin中

时间:2014-04-02 05:03:25

标签: python django forms django-templates

是否可以在django admin中包含模型表单模板,如下所示?

models.py

class Customer(models.Model):
     name = models.CharField(max_length=20)
     designation = models.CharField(max_length=20)
     gender = models.BooleanField()

forms.py

class CustomerForm(forms.ModelForm)
    gender = forms.TypedChoiceField(
            choices=GENDER_CHOICES, widget=forms.RadioSelect(renderer=HorizontalRadioRenderer), coerce=int, )
    class Meta:
        model = Customer

template.html

<form action="{% url 'verinc.views.customerView' %}" method="POST">{% csrf_token %}
{{ form.as_p }} 
    <input id="submit" type="button" value="Click" /></form>

views.py

def customerView(request):
    if request.method == 'POST':
        form = CustomerForm(request.POST)
    else:
        form = CustomerForm()
return render_to_response('myapp/template.html', {'form' : form,})

admin.py

class CustomerInline(admin.StackedInline)
    model= Customer
    form = CustomerForm
    template = 'myapp/template.html

当我在url (localhost/myapp/customer)中查看表单时,它会正确显示所有字段。但是当我在管理页面中查看它时,它只显示块中的提交按钮。我的要求是在管理页面中使用模板查看表单,以便我可以使用一些AJAX脚本进行进一步的处理。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

嗯,这是不可能的。但你可以像这样实现:

您应该在应用admin_views.py中创建名为customer的文件。

然后在你的urls.py中添加url

(r'^admin/customer/customerView/$', 'myapp.customer.admin_views.customerView'),

在admin_views.py中编写您的视图实现,如:

from myapp.customer.models import Customer
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.admin.views.decorators import staff_member_required


def customerView(request):
    return render_to_response(
        "admin/customer/template.html",
        {'custom_context' : {}},
        RequestContext(request, {}),
    )
customerView = staff_member_required(customerView)

在你的管理模板中扩展base_site.html,如下所示:

{% extends "admin/base_site.html" %}

{% block title %}Custmer admin view{% endblock %}

{% block content %}
<div id="content-main">
     your content from context or static / dynamic...
</div>
{% endblock %}

多数民众赞成。管理员登录后点击该新网址。注意未经测试 :)。