Reputation: 199
I am using Django 1.11 and I'm struggling to understand how I can pass URL parameters to a ModelForm using CreateView Class. I have 4 parameters in the URL (start_date, end_date, start_time, end_time) that i'm trying to pass to their relevant fields in the form. I'd really appreciate if anyone can point me in the right direction to figuring out how to solve this!
The URL is created with the following function in my html file:
window.location.assign("/calendar/create?start_date="+start.format("YYYY-MM-DD")+"&end_date="+end.format("YYYY-MM-DD")+"start_time="+start.format("h:mm A")+"&end_time="+end.format("h:mm A"));
This opens from urls.py:
url(r'^calendar/create',views.CalendarCreate.as_view(),name='calendar_create'),
from views.py:
class CalendarCreate(CreateView):
model = Event
form_class = EventForm
from forms.py:
class EventForm(ModelForm):
class Meta:
model = Event
So far so good, my event_form.html opens with the form:
and an example URL generated is: http://127.0.0.1:8000/calendar/create?start_date=2017-10-25&end_date=2017-10-25start_time=4:00%20PM&end_time=5:00%20PM
This is where I am stuck. From spending a number of days here in stackoverflow, googling, and trying numerous things I believe the solution involves get_form_kwargs
or get_context_data
or form_valid
in views.py
but it is possible I have just confused myself trying to work this out. Any help to get me on the right track will be greatly appreciated!
Upvotes: 4
Views: 1703
Reputation: 7717
class CalendarCreate(CreateView):
model = Event
form_class = EventForm
def get_initial(self):
initial = {}
for x in self.request.GET:
initial[x] = self.request.GET[x]
print(initial)
return initial
notice if 'start_date'
in request.GET
you must have same field 'start_date'
in your Event
model,and notice the time format is vaild.
Upvotes: 4