Reputation: 2784
I've a single View, that can be called with or without the label_rif attribute, based on this I can switch the form_class and template?
class LabelCreateView(CreateView):
model = models.Label
if self.kwargs['label_rif'] > 0:
form_class = LabelForm
template_name = 'AUTO_form.html'
else:
form_class = LabelManForm
template_name = 'MAN_form.html'
I've tried to insert the form_class without success in the method
def get_form_kwargs(self):
kwargs = super(LabelCreateView, self).get_form_kwargs()
if self.kwargs['label_rif']:
form_class = LabelForm
Or should I define another separate view? I want to keep it DRY, is it possible?
Upvotes: 0
Views: 73
Reputation: 308799
You can do this in one view by overriding get_form_class
and get_template_names
:
class LabelCreateView(CreateView):
model = models.Label
def get_form_class(self):
if self.kwargs['label_rif'] > 0:
return LabelForm
else:
return LabelManForm
def get_template_names(self):
# Note this returns a list, not a string
if self.kwargs['label_rif'] > 0:
return ['AUTO_form.html']
else:
return ['MAN_form.html']
Depending on your url config, I think that two views might be more readable in this case. You only need to override the attributes that differ, so it is still DRY.
class LabelCreateView(CreateView):
model = models.Label
form_class = LabelForm
template_name = 'AUTO_form.html'
class ManLabelCreateView(LabelCreateView):
form_class = LabelManForm
template_name = 'MAN_form.html'
Upvotes: 1