parsenz
parsenz

Reputation: 409

Django URL/Views extra parameters

In Django1.6, is there a way to pass a dynamic parameter to my view or URL without parsing the URL?

Ideally I would want a urls.py that looks like:

url(r'^dash/$',
    dash_view.account_modify,
    {'account': **dynamic_account_identifier_here**}
    name='dash_account_modiy')

And in views.py:

def account_modify(request, account, 
                   template_name='profile.html, 
                   change_form=AccountModifyForm):
    ...

:param account:
comes from model:

class Dash(models.Model):
    name = models.Charfield()
    account = models.IntegerField()
    ....

Basically, I would really like to avoid a urls.py with the account identifier as part of the string, like:

url(r'^dash/(?P<account>\w+)/$',
    dash_view.account_modify,
    name='dash_account_modiy')

Any suggestions on how I can pass these values from the a template to the processing view for use in the AccountModifyForm (which expects that 'account' parameter)?

Upvotes: 1

Views: 3412

Answers (2)

parsenz
parsenz

Reputation: 409

If anyone cares...figured it out...

In the template:

{% for dash in dashes %}
     blah blah blah
     <form action="..." method="POST">
         <input type="hidden" name="id" value="{{ dash.account }}">
         {{ form.as_ul }}
         <input type="submit" value="Do stuff">
     </form>
{% endfor %}

In the views:

if request.method == 'POST'
    account = request.POST['id']
    # be sure to include checks for the validity of the POST information
    # e.g. confirm that the account does indeed belong to whats-his-face
    form = AccountModifyForm(request.POST, account,
                             user=request.user)
    ....

Upvotes: 1

Alasdair
Alasdair

Reputation: 309069

url(r'^dash/$',
    dash_view.account_modify,
    {'account': **dynamic_account_identifier_here**}
    name='dash_account_modify')

You can't dynamically evaluate anything there, because the dictionary is evaluated only once, when the URL conf is loaded.

If you want to pass information from one view to another your three options are:

  • in the URL, which you don't seem to want to do
  • as GET or POST data
  • store it in the session in one view and retrieve it from the session in the next

Upvotes: 3

Related Questions