2017-03-04 4 views
-1

私は現在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') 

は具体的に、私は上のベストプラクティスを知りたいです次

  1. 方法は郵便またはhttp_url = request.POST["http_url"]であれば、それは明示的にテストすることをお勧めしますが
  2. 十分ですhttp_url = request.POST.get("http_url","")を使用することをお勧めしますか、これは単にエラーを抑制していますか?
  3. (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') 
    
+0

CBVを使用https://docs.djangoproject.com/en/1.10/topics/class-based-views/intro/ –

+0

Djangoには、**正確に**これを意味する完全なフォームフレームワークがあります。あなたはそれを使用しているはずです。 –

+0

ええ、私はクラスベースのビューがこれにふさわしいと思いますが、簡単にするために 'request.POST.get(" key ")'に固執することに決めました。私はCBVを実装するための非常に複雑なプロジェクトを考えています。ありがとう! – KenJhim

答えて

0
request.POST["key"] 

KeyErrorをスローします提出する場合を除き、ブロックがトリガーされません。 try...catch句を使用してエラーを処理できます。

行うことが一般的に、しかし、その慣用と完全に正常:

request.POST.get("key") 

の詳細はhereを取得します。

+0

ありがとう!これは単純なプロジェクトなので、 'request.POST.get(" key ")'を使うことに決めました。私は一度私は非常に複雑なプロジェクトを扱う必要があるクラスベースのビューを実装します:) – KenJhim

関連する問題