Neel
Neel

Reputation: 369

Create profile Urls in django

I am trying to make my first ever Django app. I have made a simple form where a user can enter a username. When the user clicks on submit, I want to redirect him to the url containing that username.

For example, Lets say my form is in the url www.mydomain.com/form

if the user enters the username = 'myname, I want to take him to the url www.mydomain.com/myname and display Hello myname, Welcome to www.mydomain.com.

Any idea how can I achieve that?

Edit

here is what i am currently doing

urls.py

from django.conf.urls import include, url

urlpatterns = [
    url(r'^$', 'temp.views.home',name='home'),
    url(r'^temp/$', 'temp.views.temp',name='temp'),
    url(r'^entry/(?P<entry>[A-Za-z0-9_.\-~]+)','temp.views.mimic',name='mimic'),
]

views.py

    from django.shortcuts import render
    from django.http import HttpResponseRedirect,HttpResponse
    def home(request):
        return render(request,'home.html',{})

    def temp(request):
        entry=request.POST['entry']
        print entry
        return HttpResponseRedirect("/entry/"+entry)

    def mimic(request,entry):
        return HttpResponse(entry)

home.html

<form method="POST" action="/temp/">{% csrf_token %}
<INPUT name='entry'>
<input type='submit' text='done'>
</form>

Now my question is can i somehow avoid this temp part in both urls and views n do the whole redirection in one step?

P.S. i know that i need to define a few checks on the form. I will add them later. currently lets assume that the entry made by the user matches with the regex defined in the url

Upvotes: 0

Views: 297

Answers (2)

Jordan Reiter
Jordan Reiter

Reputation: 21032

You need to make sure of the following:

  • that your form is actually creating a profile record
  • that the view that generates the form also verifies its input and saves the model record
  • that your profile model is set up with an absolute url, so you can redirect to its page
  • that the view that processes the form then redirects the user to the absolute url for the created model
  • that you have set up the corresponding urlpattern so that requests to /<username>/ points to a detail view you have set up for the profile model

If you are confused by any of these steps, I strongly consider that you find a Django tutorial that appeals to you and follow it exactly. It will instruct you on performing all of the steps above.

Upvotes: 1

allo
allo

Reputation: 4236

What you need:

  • a Form Class for input of the profile name
    • name = forms.CharField(...)
    • a clean_name(self) method raising ValidationError for unknown profiles
  • a view myformview
    • with displays the form for GET-Requests
    • validates the form for POST-Requests and then uses django.shortcuts.redirect with your profile view and the name.
  • your profile view of course

Upvotes: 1

Related Questions