2016-01-11 44 views
0

這裏獲取URL是我的urls.py:從請求

from django.conf.urls import include, url 
from django.contrib import admin 
from stories.views import check, post 

urlpatterns = [ 
    url(r'^admin/', admin.site.urls), 
    url('^.*/$', check), 
] 

這是我的views.py:

from django.http import HttpResponse 
from django.shortcuts import render 
from datetime import datetime 
from models import Story 

from .forms import StoryForm 

def check(request): 
    try: 
     existing_story = Story.objects.get(name=?URLRequested?) 
    except Story.DoesNotExist: 
     return HttpResponse(post(request)) 

    HttpResponse(existing_story.text) 

我想轉換輸入的網址重定向404,並用它作爲新對象的名稱。如何才能做到這一點?

回答

0

最簡單,最常用的方法是使你的URL參數,雖然.*是一個非常廣泛的正則表達式

url('^(?P<parameter_name>.*)/$', check), 

def check(request, parameter_name):  
    try: 
     existing_story = Story.objects.get(name=parameter_name) 

更常見的是尋找一個特定的匹配,例如\w+尋找一串名字或類似的文字。

查看documentation的更多信息