如何使用HyperlinkedIdentityField在URL中显示波斯语单词

时间:2019-08-09 09:38:11

标签: python-3.x django-rest-framework django-1.11

我有一个省份清单,每个省份都有其城市。我使用HyperlinkedIdentityField方法定义了一个URL,通过该URL可以列出每个省的已定义城市。输入的省份是波斯语,我需要波斯语为省份,以获取url。 喜欢: “ CrateDB” 但网址显示如下: “ http://127.0.0.1:8000/system/provinces/فارس/

Models.py:

    class Provinces(models.Model):
        province_name = models.CharField(max_length=100)
        slug_name = models.SlugField(unique=True, max_length=100, allow_unicode=True)

        def __unicode__(self):
            return self.province_name

        def __str__(self):
            return self.province_name

        def save(self, *args, **kwargs):
            self.slug_name = slugify(self.province_name)
            return super(Provinces, self).save(*args, **kwargs)

    def create_slug(instance, new_slug=None):
        slug_name = slugify(instance.province_name, allow_unicode=True)
        if new_slug is not None:
            slug_name = new_slug
        qs = Provinces.objects.filter(slug_name=slug_name)
        exists = qs.exists()
        if exists:
            new_slug = "%s-%s" % (slug_name, qs.first().id)
            return create_slug(instance, new_slug=new_slug)
        return slug_name


    def pre_save_province_name(sender, instance, *args, **kwargs):
        if not instance.slug_name:
            instance.slug_name = create_slug(instance)



    pre_save.connect(pre_save_province_name, sender=Provinces)

class Cities(models.Model):
     province = models.ForeignKey(Provinces, on_delete=models.CASCADE)
        name = models.CharField(max_length=120)
        def __unicode__(self):
            return self.name

        def __str__(self):
            return self.name

views.py:

class ProvinceCreateView(viewsets.ModelViewSet):
    queryset = Provinces.objects.all()
    serializer_class = provinceSerializer

class ProvinceWithCitiesView(mixins.ListModelMixin,
                              generics.GenericAPIView,):
    queryset = Cities.objects.all()
    serializer_class = ProvinceWithCitiesSerializer
    def get_queryset(self):
        return Cities.objects.filter(province__province_name=self.kwargs['slug_name'])
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

urls.py:

url(r'^provinces/(?P<slug_name>[\w-]+)/$', ProvinceWithCitiesView.as_view(), name='province-including-cities'),

serializers.py:

class provinceSerializer(serializers.HyperlinkedModelSerializer):
    url = HyperlinkedIdentityField(
        view_name='system-api:province-update-delete',

    )
    url_province_with_cities = HyperlinkedIdentityField(
        view_name='system-api:province-including-cities',
        lookup_field='slug_name',

    )
    class Meta:
        model = Provinces
        fields = (
            'url',
            'province_name',
            'url_province_with_cities',
                  )

0 个答案:

没有答案