Skip to content

Instantly share code, notes, and snippets.

@riajulkashem
Last active February 19, 2020 19:09
Show Gist options
  • Save riajulkashem/0e6f2871b15437a06f78e2c79d65d8be to your computer and use it in GitHub Desktop.
Save riajulkashem/0e6f2871b15437a06f78e2c79d65d8be to your computer and use it in GitHub Desktop.
Reusable Code Snippets For Django
Settings.py
----------------------------------------------------------------------------------
os.path.join(BASE_DIR, 'templates')
# STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
LOGIN_REDIRECT_URL = 'dashboard:dashboard'
LOGOUT_REDIRECT_URL = 'accounts:sign_in'
LOGIN_URL = 'accounts:sign_in'
LOGOUT_URL = 'accounts:sign_out'
-------------------------------------------------------------------------------------
root urls.py
-------------------------------------------------------------------------------------
# for staticfiles
from django.urls import path, include, re_path
from django.conf.urls.static import static
from django.conf import settings
from django.views.static import serve
urlpatterns = [
re_path(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
re_path(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
------------------------------------------------------------------------------------------------
Django CRUD Snippets
------------------------------------------------------------------------------------------------
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
class ModelNameListView(ListView):
pass
class ModelNameDetailView(DetailView):
pass
class ModelNameCreateView(CreateView):
pass
class ModelNameUpdateView(UpdateView):
pass
class ModelNameDeleteView(DeleteView):
pass
----------------------------------------------------------------------------
Active Model Item
----------------------------------------------------------------------------
class OnlyActiveManager(models.Manager):
def get_queryset(self):
return super(OnlyActiveManager, self).get_queryset().filter(status='active')
objects = models.Manager()
active = OnlyActiveManager()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment