开发者

Django - Accessing object fields and names from class-based view

I'm trying to write a class-based view for Django which will utilise the same template each time, regardless of model. The intention is that I can then add a urls.py entry for each model, and not have to bother about a view or a template.

This will be used to display a form, and as the form field names are dependant on model type, the model needs to be examined and field names extracted at the view level, so they can be passed to the generic template. The template then generates the form based on field names and values of the object.

I've been really struggling with this. At the moment I'm working on overriding get_context_data as follows

def get_context_data(self, **kwargs):
    context = kwargs
    context_object_name = self.get_context_object_name(self.object)
    if context_object_name:
        context[context_object_name] = self.object
    #add some custom stuff on too
    tempdict = [(field, field.value_to_string(self)) for field in self.object._meta.fields]
    #context.update({'datafields' : tempdict})
    context.upda开发者_StackOverflow社区te({ 'blarg': 'tester!!'})
    return context

The self.object._meta.fields bit is where I'm haivng the problems. I just can't get my head around how to access the current model. I'm doing this in a view, woud I have aany more luck in a mixin?

Thanks for your time.

O


I think you're going about this the wrong way. Django already knows how to create a form from a model, and forms know how to output themselves. So you can create a standard generic view using ModelFormMixin, there's no need to do anything clever to get form fields for a model's fields.

The only difficult bit is that you want one view to work for multiple models. So, rather than declaring the model explicitly on the view class, you'll need to work out some way of passing it dynamically - perhaps by overriding get_object.


If you're using django 1.3, class based views are included... Just use them and set the 'template_name' attribute to be your "common" name.

https://docs.djangoproject.com/en/1.3/topics/class-based-views/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜