我在Django应用程序中有一个表单,其中一个字段名为url。用户可以添加youtube的url。 提交时,我只想保存视频id
我的视图.py像这样:
import re
def video_new(request):
if request.user.is_authenticated():
if request.method == "POST":
form = VideoForm(request.POST)
if form.is_valid():
video = form.save(commit=False)
fullURL = video.url
youtubeId = re.sub(r'\shttps://www.youtube.com/watch?v=\s', '',fullURL)
video.url = youtubeId
video.created_by = request.user
video.save()
return redirect('videos:video_detail', video_id=video.pk)
else:
form = VideoForm()
else:
#if user isn't logged in
return redirect('login')
return render(request, 'videos/video_edit.html', {'form': form})
当我在控制台中输出youtubeId时,我实际上看到了完整的Url。在
所以我想我没用re.sub公司对的。 如何正确使用它?在
您的模式中不需要前导和尾随
\s
。除此之外,YouTube的url不能用一种模式进行三层解析,因为对于https://youtu.be/...
形式的每个url都有一个简短的形式。在最好使用^{} 解析url:
在python2中,您将使用
from urlparse import urlparse
。在您可以使用此函数从复杂的youtube url获取id。在
来源:https://gist.github.com/kmonsoor/2a1afba4ee127cce50a0
在你的情况下
^{pr2}$相关问题 更多 >
编程相关推荐