[Solved]-Passing Parameters to Django CreateView

26👍

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'])

1👍

urls.py

path('submit/request/<str:tracking_id>',      OrderCancellationRequest.as_view(),                name="cancel_my_order"),

Template

  <form method="POST">
    {% csrf_token %}
    {{form | crispy}}
    <button class="btn" type="submit">Submit</button>
  </form>  

View

class MyView(CreateView):
    template_name   = 'submit_request.html'
    form_class      = MyForm
    model           = MyModel

    def form_valid(self, form, **kwargs):
        self.object = form.save(commit=False)
        self.object.created_at = datetime.datetime.now()
        self.object.created_for = self.kwargs.get('order_id')
        self.object.submitted_by = self.request.user.email

        super(MyView, self).form_valid(form)
        return HttpResponse("iam submitted")

    def get_context_data(self, **kwargs):
        context = super(MyView, self).get_context_data(**kwargs)
        context['header_text'] = "My Form"
        context['tracking_id'] = self.kwargs.get('order_id') 
        return context

Leave a comment