سؤال

I want to save URLs in my database and to do so I implemented the following call:

http://myapp.com/save/url_to_be_saved

The parameter url_to_be_saved can be any URL, as:

http://myapp.com/save/http://stackoverflow.com/questions/ask
http://myapp.com/save/http://getbootstrap.com/css/#forms

How can I make Django accept these patterns? My current myapp.urls is the following:

urlpatterns = patterns(
    '',
    url(r'^$', views.index, name='index'),
    url(r'^a/signup/$', views.signup, name='signup'),
    url(r'^a/login/$', views.login, name='login'),
    url(r'^a/logout/$', views.logout, name='logout'),
    url(r'^a/search/(?P<term>.{1,50})/$', views.search, name='search'),
    url(r'^save/(?P<url>([^a/]){1,50})/$', views.save_url, name='save_url'),
)
هل كانت مفيدة؟

المحلول

I'd allow anything to be passed in the url, then I would validate the url in the view:

url(r'^save/(?P<url>.*)/$', views.save_url, name='save_url'),

Then, the view needs to validate the url:

from django.core.validators import URLValidator
from django.core.exceptions import ValidationError

def save_url(request, url):
    url_validator = URLValidator(verify_exists=False)
    try:
        url_validator(url)
    except ValidationError:
        print 'Not a valid URL'

You would also probably need to unquote the url before validating it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top