Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Parameters to Django CreateView

I am trying to implement an appointment-making application where users can create sessions that are associated with pre-existing classes. What I am trying to do is use a django CreateView to create a session without asking the user for an associated class, while under the hood assigning a class to the session. I am trying to do this by passing in the pk of the class in the url, so that I can look up the class within the CreateView and assign the class to the session.

What I can't figure out is how exactly to do this. I'm guessing that in the template I want to have something like <a href="{% url create_sessions %}?class={{ object.pk }}>Create Session</a> within a DetailView for the class, and a url in my urls.py file containing the line url(r'^create-sessions?class=(\d+)/$', CreateSessionsView.as_view(), name = 'create_sessions'), but I'm pretty new to django and don't exactly understand where this parameter is sent to my CBV and how to make use of it.

My plan for saving the class to the session is by overriding form_valid in my CBV to be:

def form_valid(self, form): form.instance.event = event return super(CreateSessionsView, self).form_valid(form)

If this is blatantly incorrect please let me know, as well.

Thank you!

like image 414
rfj001 Avatar asked Oct 16 '14 15:10

rfj001


Video Answer


1 Answers

GET parameters (those after ?) are not part of the URL and aren't matched in urls.py: you would get that from the request.GET dict. But it's much better to make that parameter part of the URL itself, so it would have the format "/create-sessions/1/".

So the urlconf would be:

url(r'^create-sessions/(?P<class>\d+)/$', CreateSessionsView.as_view(), name='create_sessions')

and the link can now be:

<a href="{% url create_sessions class=object.pk %}">Create Session</a>

and now in form_valid you can do:

event = Event.objects.get(pk=self.kwargs['class'])
like image 67
Daniel Roseman Avatar answered Oct 21 '22 13:10

Daniel Roseman