私は現在Djangoを学んでいますが、それを使ってaddメソッドと同等の構造を作ります。私は、URL短縮サービスを作成していると私は、短縮URLを作成する際に実施するには、次の方法の間だ:サブミットされたフォームがデータを持っているかどうかを調べる最もpythonicな方法
def shorten(request):
if request.method == 'POST':
http_url = request.POST.get("http_url","")
if http_url: # test if not blank
short_id = get_short_code()
new_url = Urls(http_url=http_url, short_id=short_id)
new_url.save()
return HttpResponseRedirect(reverse('url_shortener:index'))
else:
error_message = "You didn't provide a valid url"
return render(request, 'url_shortener/shorten.html', { 'error_message' : error_message })
return render(request, 'url_shortener/shorten.html')
対
def shorten(request):
http_url = request.POST["http_url"]
if http_url:
short_id = get_short_code()
new_url = Urls(http_url=http_url, short_id=short_id)
new_url.save()
return HttpResponseRedirect(reverse('url_shortener:index'))
else:
error_message = "You didn't provide a valid url"
return render(request, 'url_shortener/shorten.html', { 'error_message' : error_message })
return render(request, 'url_shortener/shorten.html')
は具体的に、私は上のベストプラクティスを知りたいです次
- 方法は郵便または
http_url = request.POST["http_url"]
であれば、それは明示的にテストすることをお勧めしますが - 十分です
http_url = request.POST.get("http_url","")
を使用することをお勧めしますか、これは単にエラーを抑制していますか? (2)が推奨されない場合、どうすれば
http_url
を必須にしてエラーをスローすることができますか?私はまた、次のことを試してみましたが、私はkey
が辞書に存在しない場合、空白のフォームdef shorten(request): if request.method == 'POST': try: http_url = request.POST["http_url"] short_id = get_short_code() new_url = Urls(http_url=http_url, short_id=short_id) new_url.save() return HttpResponseRedirect(reverse('url_shortener:index')) except KeyError: error_message = "You didn't provide a valid url" return render(request, 'url_shortener/shorten.html', { 'error_message' : error_message }) return render(request, 'url_shortener/shorten.html')
CBVを使用https://docs.djangoproject.com/en/1.10/topics/class-based-views/intro/ –
Djangoには、**正確に**これを意味する完全なフォームフレームワークがあります。あなたはそれを使用しているはずです。 –
ええ、私はクラスベースのビューがこれにふさわしいと思いますが、簡単にするために 'request.POST.get(" key ")'に固執することに決めました。私はCBVを実装するための非常に複雑なプロジェクトを考えています。ありがとう! – KenJhim