ModelForm access slug from url

35 views
Skip to first unread message

David

unread,
Feb 6, 2017, 11:17:22 AM2/6/17
to Django users
I have a modelform something like this:

class EventContactForm(ModelForm):
def __init__(self, *args, **kwargs):
super(EventContactForm, self).__init__(*args, **kwargs)
self.fields['event'].queryset = Event.objects.filter(category__slug=SLUGFROMURLHERE).filter(active=True).filter(start_date__gt=datetime.date.today())
self.helper = FormHelper()
self.helper.attrs = {'id': 'id-eventForm',
'class': 'form-vertical',
'autocomplete': 'off'}
self.helper.html5_required = True
self.helper.layout = Layout(
'event',
'first_name',
'last_name',
'company',
'telephone',
'email_address',
'message',
Submit('submit', 'Submit', css_class='btn btn-primary'), 
)

I am having trouble accessing the slug from the url in order to perform the queryset filter (SLUGFROMURLHERE). I am trying to avoid having multiple forms for different category scenarios, because apart from the "event" field, the rest of the forms are identical.

Many thanks for any help.

David

unread,
Feb 6, 2017, 11:44:15 AM2/6/17
to Django users
I should add that this is in conjunction with a CreateView CBV.

David

unread,
Feb 6, 2017, 11:54:45 AM2/6/17
to Django users
Sorted by using

    def get_form_kwargs(self):
        kwargs = super(EventForm, self).get_form_kwargs()
        kwargs.update({'category_slug': self.kwargs['category_slug']})
        return kwargs
Reply all
Reply to author
Forward
0 new messages