django:如何使用两个模型的通用视图

时间:2013-03-12 09:27:59

标签: django django-models django-templates django-views

我有两个名为customerbuilding的模型。如何使用这两个模型在一个模板中使用基于类的通用视图进行一般查看。

以下是我的 urls.py 来查看我的客户

urlpatterns = patterns('',
 url(r'^customer/', customerView.as_view(), name= "customer_view"),
)

以下是客户

view.py
class customerView(UpdateView):
    template_name="customer.html"
    model = customer
    form_class = customerForm

    def get_context_data(self, **kwargs):
        context = super(customerView, self).get_context_data(**kwargs)  
        context['pk'] = 1
        context['numberOfObjects'] = customer.objects.all().count()
        return context

    def get_object(self, queryset = None):
        try: 
            obj = customer.objects.get(id = 1)
        except: 
            obj = customer.objects.create(id = 1)
        return obj

    def form_valid(self, form):

        form.save()
        return HttpResponseRedirect(reverse("customer_view", kwargs={'pk': self.kwargs['pk']}))

以下是customer.html查看customerbuilding

的一些代码
<form action="" method="post">  
{% csrf_token %}

 {{ form.id }}  
    <div class="text_label"  >FIRST NAME</div>
    <div class="text_input">{{ form.FIRST_NAME }}</div>     
    <div class="text_label" >LAST NAME</div>
    <div class="text_input">{{ form.LAST_NAME }}</div>      

    <div class="text_label" >BUILDING USE</div>
    <div class="text_input3">{{ form.BUILDING_USE }}</div></td>     
    <div class="text_label" >BUILDING FLOORSPACE</div>
    <div class="text_input3">{{ form.BUILDING_FLOORSPACE }}</div></td>      
    <div class="text_label">BUILDING YEAR</div> 
    <div class="text_input3" >{{ form.BUILDING_YEAR }}</div></td></tr>

rest of the code....//the first part is from the class customer and the second part is from the class building.

我的问题是我可以通用查看班级客户而不是班级建设。我怎么做到这一点...我仍然是django的业余爱好者,仍然是一个很好的方式。如果我问一个菜鸟问题,请原谅我。办理登机手续How can I pass two models to a class based generic view但仍然空白。非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

get_context_data()中,您可以添加新对象。

context['building'] = building.objects.get(name="Building name")

然后你可以在你的模板中调用它

{{ building.name }}

如果你想在一个表单中使用它,那么同时正确编辑两个模型将会非常棘手。

a great SO post explaining why this is