问题
I understand that the standard way of accessing named url parameters in a custom get_context_data()
method is through self.kwargs
.
However, the self.kwargs
syntax becomes awkward, especially when handling a significant number of parameters. So, I've been resorting to something like this at the top of every get_context_data()
method -- just to get easy-to-handle local variables:
def get_context_data(self, **kwargs):
var1, var2, var3, var4, var5 = [self.kwargs[x] for x in ['var1', 'var2', 'var3', 'var4', 'var5']]
# do stuff with var1, var2, ...
# instead of self.kwargs['var1'], self.kwargs['var2'], ...
This is ugly and a pain, but it ultimately makes things a lot easier to work with and read.
Is there a simple way to clean it up and get named parameters into local variables? Short of overriding the get()
method, subclassing Django's generic views, etc.? I suspect I'm just missing some extremely basic, fundamental python concept here.
Here is the default get()
method that calls get_context_data()
in case it's helpful to reference here:
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
UPDATE:
My mistake, the calling get()
method is actually as follows (The generic FormView
is being subclassed in this case). Unfortunately the kwargs that are passed into get_context_data()
are not the same as self.kwargs
:
def get(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
return self.render_to_response(self.get_context_data(form=form))
Many thanks!
回答1:
If kwargs passed to get_context_data
is the same as self.kwargs
, You could do this:
def get_context_data(self, var1, var2, var3, var4, var5, **kwargs):
# do stuff with var1, var2, ...
EDIT: you could override the get method to pass the kwargs in. I know its not elegant, but it would work. You could make a mixin to use in multiple classes.
def get(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
return self.render_to_response(self.get_context_data(form=form, **kwargs))
Other than that, I really can't think of a better way. Your original solution might be best. I usually just access self.kwargs['...']
directly.
来源:https://stackoverflow.com/questions/19941969/django-cbv-easy-access-to-url-parameters-in-get-context-data