I am hoping this is a simple tweak. I've been reading through various threads here but I am missing a very basic step -- how do I grab the argument from the URL request?
For instance, the URL is http://127.0.0.1:8000/registration/student/item/create/8
URL definition is path('student/item/create/<int:pk>',views.CreateStudentBehaviorItem.as_view(),name='student_item_create'),
My class view is as follows:
class CreateStudentBehaviorItem(LoginRequiredMixin, generic.CreateView):
model = StudentItem
form_class = StudentItemForm
success_url = reverse_lazy('registration:student_item_list')
def get_form_kwargs(self):
kwargs = super(CreateStudentBehaviorItem, self).get_form_kwargs()
kwargs['pk'] = self.request.GET.get('pk')
return kwargs
The form is:
class StudentItemForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.course = kwargs.pop('pk', 'all')
super().__init__(*args, **kwargs)
# Begin filtering by course ID
class Meta:
model = StudentItem
fields = ("item_student","behavior_category","behavior_item","response","internal_comments")
widgets = {
'item_student': forms.Select(attrs={'class': 'form-control'}),
'behavior_category': forms.Select(attrs={'class': 'form-control'}),
'behavior_item': forms.Select(attrs={'class': 'form-control'}),
'response': forms.Select(attrs={'class': 'form-control'}),
'internal_comments': forms.Textarea(attrs={'class': 'form-control', 'rows':5}),
}
I haven't even gotten to the point to filter because I can't seem to get the PK from the request URL. My minimal Django experience is with get_context_data to grab request URL details. I hope this is a simple correction to grab the value.
I appreciate it.
CodePudding user response:
try this
https://docs.djangoproject.com/en/4.0/ref/urls/#path
def get_form_kwargs(self):
kwargs = super(CreateStudentBehaviorItem, self).get_form_kwargs()
kwargs['pk'] = self.kwargs.get('pk')
return kwargs