2017-05-01 6 views
0

id(トークン)とid(トークン)のないコンテンツを表示するためにビューにURLを1つだけ使用する方法はありますか?例えば、トークンが提供されない場合、ユーザのプロファイルのリストを表示するビューがあり、そうでない場合、渡されたトークンを特定のユーザに示す。ここでidがあり、idがないビューのURLが1つ

は、URLがこの

url(
     r'^users/$', 
     views.UserList.as_view(), 
     name="user_list" 
), 
url(
    r'^users/(?P<token>[0-9a-z]+)$', 
    views.UserList.as_view(), 
    name="user_profile" 
), 

ようなものになるウィルビュー

def get(self, request, token=None, format=None): 
     """ 
     Returns a list of profile of user or single user if token is provided 
     """ 
     reply={} 
     try: 
      profile_instance = Profile.objects.filter(user=self.request.user) 
      if token: 
       profile = profile_instance.get(token=token) 
       reply['data'] = self.serializer_class(profile).data 
      else: 
       reply['data'] = self.serializer_class(profile_instance, many=True).data 
     except: 
      reply['data']=[] 
     return Response(reply, status.HTTP_200_OK) 

だけ1つのURLを持ってする方法はありますか?

+0

あなたはそのためのdjango restフレームワークでビューセットを使用する必要があります –

答えて

1

確かに、方法があります。 tokenのurlパラメータをオプションにするだけです。 tokenの0または1の一致を意味

url(r'^users/(?P<token>[0-9a-z]+)?$', views.UserList.as_view(), name='user_profile'), 

お知らせ末尾?、:このように。 tokenが指定されている場合は、それは指定された値になります(明らかに!)。そうでない場合はNoneになります。

+0

貴重な情報ありがとうございます。 – Serenity

+0

あなたはhttp://stackoverflow.com/questions/43702531/confusion-on-which-serializer-to-use-to-update-user-profile/43702673?noredirect=1質問をご覧ください。私はhttps://pastebin.com/Bepe9fFdにuser_nameのlast_nameとuserのユーザ名と共にユーザプロファイルを更新するための完全なコードを持っています。 – Serenity

関連する問題