使用api_key生成url并使用Tastypie(Django)生成slug

时间:2015-11-09 16:23:31

标签: python django django-models tastypie django-urls

我想为一个slug生成一个url,其中包含由Tastypie创建的http://localhost:8000/api/v1/ url模式+ api_key为一个用户生成Tastypies ApiKey +从标题字段生成带有Slugify的slug。我想匹配http://localhost:8000/api/v1/api_key/slug(请参阅网址 - 部分)。我不确定如何将views-function与api.py中的ModelResource类SlugResource连接并定义url。非常感谢任何帮助。

在模型中,我添加了为函数save()和get_absolute_url()中的每个新对象生成新的slug对象的方法,该方法返回字段slug(self.slug)作为模型的链接.permalink - 装饰器和在url中使用的名称,slug_。

in models.py 
class Myclass(models.Model):
    title = models.CharField(max_length=500,null=True)
    slug = models.SlugField(unique=True,null=True)
    def __unicode__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.id:
            # Newly created object, so set slug
            self.slug = slugify(self.title)

            super(Myclass, self).save(*args, **kwargs)

    @models.permalink
    def get_absolute_url(self):
        return 'slug_', (self.slug,)

在视图中,我从SlugForm形式的标题字段中提取了一个slug,并为当前经过身份验证的用户提取了api_key。

from tastypie.models import ApiKey
from django.template.defaultfilters import slugify

in views.py 
one_slugpost(request, postID, slug):
    one_session = Myclass.objects.get(id=postID)
    one_slug = Myclass.objects.get(slug=slug)
    if request.method == "POST":
        form = SlugForm(request.POST)
        if form.is_valid():
          # get title  
          title = request.POST["title"]
          # create a slug of title
          slug = slugify(title)
          # get the username for the current authenticated user
          user = request.user
          # get the user id
          user_id = user.id
          # get or generate a new api key with Tastypie ApiKey for user with id user_id
          api_key = ApiKey.objects.get_or_create(user=user_id)[0].key

   else:
        form = SlugForm()

    c = {"one_one_session":one_one_session,"one_slug":slug,"form":form}
    c.update(csrf(request))

    template = 'test_index.html'
    return render_to_response(template, c,context_instance=RequestContext(request)) 

in api.py
from myapp.models import Myclass

# ModelResource draws all resource (content) from a class, in this case Myclass
# and makes it a webbservice-resource
class SlugResource(ModelResource):
    class Meta:
        # provide  webbservice-resource features to all instances of  Myclass
        queryset = Myclass.objects.all()
        # the name of the resource, same as for url- patterns
        # e.g api/v1/
        resource_name = "slug_resource"

在网址中,http://localhost:8000/api/v1/的模式适用于Api但不适用于postid和slug的url测试,我希望将其扩展为api - url模式http://localhost:8000/api/v1/

in urls.py 
# get api for urls from Tastypie - webbservice class SlugResource
# and set api_name to v1 
from tastypie.api import Api
from myapp.api import SlugResource
v1_api = Api(api_name = 'v1')
v1_api.register(SlugResource())

urlpatterns = patterns('',



 # include all api instance urls in SlugResource in myapp api.py model

   url(r'^api/', include(v1_api.urls)),

 # define url matching postid and slug- not working
 # here's where I want to match ...localhost/api/v1/api_key/slug

 url(r'^test(?P<postID>\d+)/(?P<slug>\w+)/$',one_slugpost, name='slug_'),

1 个答案:

答案 0 :(得分:0)

我会尝试使用prepend_urls。这样的事情应该这样做:

class ArticleResource(ModelResource):
    class Meta:
        queryset = MyClass.objects.all()
        detail_uri_name = 'slug'

    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/(?P<slug>[\w\d_.-]+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
        ]