在Django管理后台中包含模板表单
在Django的管理后台中,能不能像下面这样包含模型表单模板呢?
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 个回答
1
好吧,这个事情是做不到的。不过你可以这样实现:
你需要在你的应用 customer
里创建一个叫 admin_views.py
的文件。
然后在你的 urls.py 文件里添加一个网址,像这样:
(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 %}
就这样。登录管理员后,访问那个新网址。注意,这个方法没有测试过 :)。