【问题标题】:Include template form to django admin将模板表单包含到 django admin
【发布时间】:2014-05-13 04:15:31
【问题描述】:

是否可以在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 脚本进行进一步处理。非常感谢任何帮助。

【问题讨论】:

    标签: python django forms django-templates


    【解决方案1】:

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

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

    然后在你的 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 %}
    

    就是这样。管理员登录后点击该新网址。注意未测试 :) .

    【讨论】:

    • 是的,这在其他网址中也可以正常工作。我的要求是我在管理页面中有其他模型,我需要在添加页面中嵌入上述内容。
    猜你喜欢
    • 2013-12-16
    • 2017-12-04
    • 2013-04-26
    • 2011-03-12
    • 2017-03-18
    • 2018-02-02
    • 2012-03-16
    • 1970-01-01
    • 2021-09-10
    相关资源
    最近更新 更多