Reputation: 69
I am working on a project which bases operations on the session_key parameter.
I would like to fetch data from the database and add the variables into a choicefield in forms. Using the ModelChoiceField(queryset=..., empty_label="(Nothing)") could be an option, but i still cant take in the session_key as a parameter to filter the queryset.
so my question, how can i fetch the session_key from the request in views and pass it to the queryset in the forms class?
Thx!
UPDATE:
FORM:
class CreateChartForm(forms.Form): def init(self, var_list, *args, **kwargs): super(CreateChartForm, self).init(*args, **kwargs) self.fields['x'] = forms.ChoiceField(choices=tuple([(name, name) for name in var_list])) self.fields['y'] = forms.ChoiceField(choices=tuple([(name, name) for name in var_list]))
But now i cannot pass REQUEST.POST to the form...
form = CreateChartForm(var_list=df.columns.to_list())
Upvotes: 0
Views: 41
Reputation: 69
Okay now i have been using the "trial and error" methods and a big selection of questions here on Stack.
IF you want to dynamically create choicefields from a django model without using the modelform you can get it via *args and *kwargs.
I modified my Form as below in FORMS.py:
class CreateChartForm(forms.Form):
def __init__(self, *args, **kwargs):
super(CreateChartForm, self).__init__(*args, **kwargs)
req, cols = args
self.fields['x'] = forms.ChoiceField(choices=tuple([(name, name) for name in cols]))
self.fields['y'] = forms.ChoiceField(choices=tuple([(name, name) for name in cols]))
CHART_CHOICES = (
("Linjediagram", "Linjediagram"),
("Stapeldiagram", "Stapeldiagram"),
("Korrelationsgraf", "Korrelationsgraf"),
("Kaka", "Kaka"),
)
chart = forms.ChoiceField(choices=CHART_CHOICES)
titel = forms.CharField(max_length=255)
Then i passed both the request.POST and the dataframe.columns.to_list() in the VIEWS.py file:
form = CreateChartForm(request.POST, df.columns.to_list())
Now i have a form which can access dynamic variable names through a Pandas Dataframe and adding them to a drop down style choice field in a form :-)
Upvotes: 0
Reputation: 8192
The terms you probably want to search are "Django" and "dynamic ChoiceField".
I don't have an example to hand, but this question seems to have answers pretty much as I would have guessed.
Upvotes: 0