I have created two url paths.
path('addhours/<int:jobNr>/', views.AddHoursView.as_view(), name='addhours'),
path('addhours/', views.AddHoursView.as_view(), name='addhours'),
And a CreateView for these paths.
class AddHoursView(generic.CreateView):
template_name = "worktime/addhours.html"
form_class = AddHoursForm
success_url = reverse_lazy('worktime:myjobs')
def get_form_kwargs(self):
# pass "jobNr" keyword argument from the current url to form
kwargs = super(AddHoursView, self).get_form_kwargs()
kwargs['jobNr'] = self.kwargs.pop(JOB_PARAM, None)
return kwargs
And a form, where the number of fields depends on if the parameter exists in the URL.
class AddHoursForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
#Add jobworker field to from Worktime model if any jobNr pass in url
#When in url will be parameter. Job foreignkey will be set by automat.
self.jobNr = kwargs.pop('jobNr', None)
super(AddHoursForm, self).__init__(*args, **kwargs)
if not self.jobNr:
self.fields['jobWorker'] = forms.ModelChoiceField(queryset=Job.objects.all())
class Meta:
model = WorkTime
fields = ['date', 'hours', 'description']
widgets = {
'date': forms.SelectDateWidget(empty_label=("Choose Year",
"Choose Month",
"Choose Day"))
}
Now I want to have in AddHoursView context["jobNr"] = "bar" where the URL is /url/bar
In AddHoursView's def context_data(self, **kwargs) I tried:
self.request.GET gives me empty QueryDictself.kwargs['jobNr'] give me a key errorI need access to the url parameter if it exist, to pass this jobNr to template, so override form_valid is not what I need.
At the moment you are popping the value from self.kwargs, which removes it. That means it is no longer there when you try to access it in get_context_data. Since the argument is optional, you can use get() instead.
Change the method to:
def get_form_kwargs(self):
kwargs = super(AddHoursView, self).get_form_kwargs()
kwargs['jobNr'] = self.kwargs.get('JOB_PARAM')
return kwargs
Then in get_context_data you can do:
def get_context_data(self, **kwargs):
kwargs = super(AddHoursView, self).get_context_data(**kwargs)
kwargs['jobNr'] = self.kwargs.get('JOB_PARAM')
return kwargs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With