Reputation: 46178
Let's consider this template part
<form class="form-horizontal" action="{% if client_id %}
{% url client_edit client_id=client_id %}{% else %}
{% url client_edit %}
{% endif %}" method="post">{% csrf_token %}
{{ client_form }}
</form>
As you can see the parameter client_id
is optional.
Is there a way to avoid this repetition (url client_edit
) ?
Url pattern:
url('^client/edit$', client_edit, name='client_edit'),
url('^client/edit/(?P<client_id>\d+)$', client_edit, name='client_edit'),
Upvotes: 2
Views: 278
Reputation: 174622
urls don't have optional parameters. You can have multiple patterns point to the same view (as you have done), and then check for the defaults in the view. In your template, {% url client_edit client_id=client_id|default_if_none:-1 %}
, then depending on what you want to happen on the view end filter appropriately:
def client_edit(request, client_id = None):
if client_id:
client = get_object_or_404(Client, pk=client_id)
else:
# Default value for client
client = Client.objects.filter(active=True) # for example
# your normal logic here
Upvotes: 1
Reputation: 291
It's not repetition of using
{% url client_edit %}
since you actualy define two urls. If you really want to make it shorter (not necessary simplier) you could create some filter like
{{client_id|make_url}}
and inside filter you can resolve to proper url
Upvotes: 1