Skip to content

Instantly share code, notes, and snippets.

@openhubdev
Last active March 9, 2021 17:25
Show Gist options
  • Save openhubdev/6ad197ab526a8b674c85b1e09882690a to your computer and use it in GitHub Desktop.
Save openhubdev/6ad197ab526a8b674c85b1e09882690a to your computer and use it in GitHub Desktop.

Django More in-depth

Internationalization:

Once all strings are marked for translation, generate the message files:

Generate message files for a desired language

python manage.py makemessages -l kr

After adding translations to the .po files, compile the messages

python manage.py compilemessages

This link was really helpful!

output the data & fields of a specific model into a serialized JSON format :

> python manage.py dumpdata <app-class> --indent=2

for more: python manage.py dumpdata

**Save it to a file:

> mkdir courses/fixtures
> python manage.py dumpdata courses --indent=2 --output=courses/fixtures/subjects.json

Then load back to the database OMG

> python manage.py loaddata subjects.json

By default, Django looks for files in the fixtures/ directory of each app, but you CAN specify the complete path to the ficture file in the command above

##Permission

class OwnerCourseMixin(OwnerMixin,
                       LoginRequiredMixin,
                       PermissionRequiredMixin):
                       .. 

PermissionRequiredMixin checks permission_required attributes in the view!

Reordering!

#courses/views.py
class ModuleOrderView(CsrfExemptMixin,
                      JsonRequestResponseMixin,
                      View):
    def post(self, request):
        for id, order in self.request_json.items():
            Module.objects.filter(id=id,
                                  course__owner=request.user).update(order=order)
        return self.render_json_response({'saved': 'OK'})
        ...

then set this @url.py:

path('module/order/',
         views.ModuleOrderView.as_view(),
         name='module_order'),

     path('content/order/',
          views.ContentOrderView.as_view(),
          name='content_order'),

Adding jQuery

add the jquery script @ templates/base.html of the app

REST API

"Serializer" for "Subject" model :

from rest_framework import serializers
from ..models import Subject
from ..models import Course, Module, Content

class SubjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Subject
        fields = ['id', 'title', 'slug']

You can run the api url @ Postman or curl http://127.0.0.1:8000/api/subjects/ | json_pp in the termial

Handling Authentications

  • BasicAuth
  • TokenAuth
  • SessionAuth
  • RemoteUserAuth

You can build a custom authentication backend by subclassing the BaseAuthentication class provided by REST and overriding the authnticate() method.

Authentication only "indentifies" the user performing the request. You need to use permissions to restrct acecss to views!

built-on permissions of REST framework:

  • AllowAny: unrestricted
  • InAuthenticated: allow access to authenticated users ONLY
  • InAuthenticatedOrReadOnly: Complete acces to authenticated users; anonymous users-> only read
  • DjangoModelPermission: permissions tied to django.contrib.auth. The view requires a queryset attribute; only authenticated users w model permissions get granted the permission
    • DjangoObjectPermissions: per-object based auth

.. more

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment