Home > Mobile >  accessing url parameters of django template url tag in createView Class
accessing url parameters of django template url tag in createView Class

Time:11-17

I want to prepopulate (initial) a certain form field in the django createView class according to the url parameter passed in the {% url %} tag. I don't know ho to pick the passed url parameter in the get_initial(self) method on the createView class. When I hardcode certain value, it's working.

The html is like that:

{% for object in model.objects_set.all %}
  {% subobject in objectmodel.subobjects_set.all%}
    <a href="{% url 'url_name' object.id %}">Create SubObject</a>
  {% endfor %}
{% endfor %}

and the views.py is like that (i am missing the ??? part):

class SubObjectCreateView(generic.CreateView):
model = SubObject
...

def get_initial(self):
    return {'object': ???}

urls.py is like:

path('subobject/<int:something>', views.SubObjectCreateView.as_view(), name='url_name')

CodePudding user response:

The url parameters are accessible through the kwargs property, so you can write:

class SubObjectCreateView(generic.CreateView):
   model = SubObject
   ...

   def get_initial(self):
      return {'object': self.kwargs['something']}  # Replace 'something' with the name of the url parameter

CodePudding user response:

You can access url params with

print(self.kwargs)

So, I recommended to you just print self.kwargs and look what you have.

And after that, you can use that kwargs like this

class SubObjectCreateView(generic.CreateView):
model = SubObject
...

def get_initial(self):
    my_param = self.kwargs["something"]
    return {'object': my_param}
  • Related