dpbklyn
dpbklyn

Reputation: 791

Django retrieve data from db to complete a url pattern

I know this is an easy question, I am just not getting something...so thank you for your patience and advice.

I have a view that asks a user to register to use our app. The data he/she submits is stored in a database and he is sent off to another page to set up the application:

#views.py

def regPage(request, id=None):
    form = RegForm(request.POST or None,
                       instance=id and UserRegistration.objects.get(id=id))

    # Save new/edited pick
    if request.method == 'POST' and form.is_valid():
        form.save()
        return HttpResponseRedirect('/dev/leaguepage/')
    user_info = UserRegistration.objects.all()
    context = {
        'form':form,
        'user_info' :user_info,
    }

    return render(request, 'regpage.html', context)

Rather than sending ALL users to the same page '/dev/leaguepage/', I need to send each user to his own page based on the PK in the database like: '/dev/PrimaryKey/' I am not sure how to make this happen either on the views file or in the URLs.py file:

#urls.py

from django.conf.urls.defaults import patterns, include, url
from acme.dc_django import views

urlpatterns = patterns('',

    url(r'^leaguepage/$','acme.dc_django.views.leaguePage'),




    url(r'^$', 'acme.dc_django.views.regPage'),
)

Thank you for your help!

dp

Updated code:

#url
  url(r'^user/(?P<id>\d+)/$','acme.dc_django.views.leaguePage', name="league_page"),

#view
  def regPage(request, id):
    form = RegForm(request.POST)

    # Save new/edited pick
    if request.method == 'POST' and form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse('league_page', kwargs={'id' :id}))
        #return HttpResponseRedirect('/dev/leaguepage/')
    user_info = UserRegistration.objects.all()
    context = {
        'form':form,
        'user_info' :user_info,
    }

    return render(request, 'regpage.html', context)

Upvotes: 1

Views: 850

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34583

You can do a reverse lookup on your leaguePage to do your redirect, passing in the values you need to resolve the pattern. You'll need to add a name to the URL pattern you want to reverse, but basically the syntax is:

return HttpResponseRedirect(reverse('my_detail', args=(), kwargs={'id' : id}))

Example URL pattern and view:

urlpatterns = patterns('my_app.views',
    url(r'^my-pattern/(?P<id>\d+)/$', 'my_action', name='my_detail'),
)

def my_action(request, id):
    #do something

Hope that helps you out.

Upvotes: 2

Related Questions