Create profile Urls in django

时间:2015-07-08 15:48:34

标签: django url-redirection custom-url

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您需要确保以下内容:

  • 您的表单实际上是在创建个人资料记录
  • 生成表单的视图也会验证其输入并保存模型记录
  • 您的个人资料模型设置了绝对网址,因此您可以重定向到其网页
  • 处理表单的视图然后将用户重定向到创建的模型的绝对URL
  • 您已设置相应的urlpattern以便请求 /<username>/指向您为个人资料模型设置的详细信息视图

如果您对这些步骤感到困惑,我强烈认为您找到了一个吸引您并完全遵循它的Django教程。它将指导您执行上述所有步骤。