├── 1- Page permission ├── decorators.py └── views.py ├── 2- Django Rest Accounts ├── 1- Login │ ├── serializers.py │ └── views.py └── 2- Register │ ├── serializers.py │ └── views.py ├── 3- Pagination ├── index.html └── views.py ├── 4- Advanced Models Query └── adv_query_1.md ├── 5- Django Rest Status codes └── README.md ├── LICENSE └── README.md /1- Page permission/decorators.py: -------------------------------------------------------------------------------- 1 | from django.http import HttpResponse 2 | 3 | def allowed_editors(list_users): 4 | def decorator(func): #it can be of any name. 5 | def wrapper_func(request,*args,**kwargs): 6 | group = None 7 | if request.user.groups.exists(): 8 | group = request.user.groups.all()[0].name 9 | if group in list_users: 10 | return func(request,*args,**kwargs) 11 | else: 12 | return HttpResponse("not allowed", status=405) #you can you render/redirect 13 | return func(request,*args,**kwargs) 14 | return wrapper_func 15 | return decorator 16 | -------------------------------------------------------------------------------- /1- Page permission/views.py: -------------------------------------------------------------------------------- 1 | from .decorators import allowed_editors 2 | 3 | @allowed_editors(list_users=['admin','editor']) #allowed groups 4 | def your_view(request): 5 | pass 6 | -------------------------------------------------------------------------------- /2- Django Rest Accounts/1- Login/serializers.py: -------------------------------------------------------------------------------- 1 | class LoginSerializer(serializers.Serializer): 2 | username = serializers.CharField(max_length=25, required=True) 3 | password = serializers.CharField(max_length=128, required=True) 4 | -------------------------------------------------------------------------------- /2- Django Rest Accounts/1- Login/views.py: -------------------------------------------------------------------------------- 1 | from rest_framework.response import Response 2 | from rest_framework import status 3 | from rest_framework.decorators import api_view 4 | from django.contrib.auth.models import User 5 | from rest_framework.authtoken.models import Token 6 | from restapi.serializers import LoginSerializer 7 | 8 | from django.contrib import auth 9 | 10 | @api_view(['POST']) 11 | def user_login(request): 12 | if request.method == "POST": 13 | 14 | serializer = LoginSerializer(data=request.data) 15 | if serializer.is_valid(): 16 | print(serializer.data) 17 | data = {} 18 | username = serializer.data.get("username", None) 19 | password = serializer.data.get("password", None) 20 | user = auth.authenticate(username=username, password=password) 21 | if user is not None: 22 | token = Token.objects.get(user=user) 23 | data['username']=user.username 24 | data['email']=user.email 25 | data['token']=token.key 26 | return Response(data, status=status.HTTP_200_OK) 27 | else: 28 | return Response({"ERROR":"User not found"}, status=status.HTTP_200_OK) 29 | return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 30 | -------------------------------------------------------------------------------- /2- Django Rest Accounts/2- Register/serializers.py: -------------------------------------------------------------------------------- 1 | class UserSerializer(serializers.ModelSerializer): 2 | email = serializers.EmailField(max_length=75, required=True) 3 | class Meta: 4 | model = User 5 | #fields ="__all__" #change to requred fields 6 | fields = ['username', 'password', 'email'] #change to requred fields 7 | -------------------------------------------------------------------------------- /2- Django Rest Accounts/2- Register/views.py: -------------------------------------------------------------------------------- 1 | from rest_framework.response import Response 2 | from rest_framework import status 3 | from rest_framework.decorators import api_view 4 | from django.contrib.auth.models import User 5 | from rest_framework.authtoken.models import Token 6 | from restapi.serializers import UserSerializer 7 | 8 | @api_view(['POST']) 9 | def user_register(request): 10 | if request.method == 'POST': 11 | serializer = UserSerializer(data=request.data) 12 | data={} 13 | if serializer.is_valid(): 14 | user = serializer.save() 15 | token=Token.objects.create(user=user) 16 | data['username']=user.username 17 | data['email']=user.email 18 | data['token']=token.key 19 | return Response(data, status=status.HTTP_201_CREATED) 20 | return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 21 | -------------------------------------------------------------------------------- /3- Pagination/index.html: -------------------------------------------------------------------------------- 1 |
2 | {% if listings.has_other_pages %} 3 | 37 | {% endif %} 38 |
39 | -------------------------------------------------------------------------------- /3- Pagination/views.py: -------------------------------------------------------------------------------- 1 | from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator 2 | 3 | def properties(request): 4 | page_property=Listing.objects.all() #import your model 5 | 6 | paginator=Paginator(page_property,3) # 3 here is number of item per page,inshort 7 | page_number = request.GET.get('page') # checks for page number clicked. 8 | page_property = paginator.get_page(page_number) #load item according to page number 9 | 10 | context = { 11 | 'listings':page_property, 12 | } 13 | return render(request,'listings/listings.html',context) 14 | -------------------------------------------------------------------------------- /4- Advanced Models Query/adv_query_1.md: -------------------------------------------------------------------------------- 1 | **1-Methods That Return QuerySets**\ 2 | _i will keeping updating these_ 3 | 4 | Method | Description 5 | ------------- | ------------- 6 | **filter()**|Filter by the given lookup parameters. Multiple parameters are joined by SQL AND statements 7 | **exclude()**| Filter by objects that don’t match the given lookup parameters 8 | **annotate()**| Annotate each object in the QuerySet. Annotations can be simple values, a field reference or an aggregate expression 9 | **order_by()**| Change the default ordering of the QuerySet 10 | **reverse()**| Reverse the default ordering of the QuerySet 11 | **distinct()**| Perform an SQL SELECT DISTINCT query to eliminate duplicate rows 12 | **values()**| Returns dictionaries instead of model instances 13 | **values_list()**| Returns tuples instead of model instances 14 | **dates()**| Returns a QuerySet containing all available dates in the specified date range 15 | **datetimes()**| Returns a QuerySet containing all available dates in the specified date and time range 16 | **none()**| Create an empty QuerySet 17 | **all()**| Return a copy of the current QuerySet 18 | **union()**| Use the SQL UNION operator to combine two or more QuerySets 19 | **intersection()**| Use the SQL INTERSECT operator to return the shared elements of two or more QuerySets 20 | **difference()**| Use the SQL EXCEPT operator to return elements in the first QuerySet that are not in the others 21 | **select_related()**| Select all related data when executing the query (except many-to-many relationships) 22 | **prefetch_related()**| Select all related data when executing the query (including many-to-many relationships) 23 | **defer()**| Do not retrieve the named fields from the database. Used to improve query performance on complex datasets 24 | **only()**| Opposite of defer()—return only the named fields 25 | **using()**| Select which database the QuerySet will be evaluated against (when using multiple databases) 26 | **select_for_update()**| Return a QuerySet and lock table rows until the end of the transaction 27 | **raw()**| Execute a raw SQL statement 28 | **AND (&)**| Combine two QuerySets with the SQL AND operator. Using AND (&) is functionally equivalent to using filter() with multiple parameters 29 | **OR (\|)**| Combine two QuerySets with the SQL OR operator 30 | 31 | **2- Methods That Don’t Return QuerySets** 32 | Method | Description 33 | ------------- | ------------- 34 | **get()**| Returns a single object. Throws an error if lookup returns multiple objects 35 | **create()**| Shortcut method to create and save an object in one step 36 | **get_or_create()**| Returns a single object. If the object doesn’t exist, it creates one 37 | **update_or_create()**| Updates a single object. If the object doesn’t exist, it creates one 38 | **bulk_create()**| Insert a list of objects in the database 39 | **bulk_update()**| Update given fields in the listed model instances 40 | **count()**| Count the number of objects in the returned QuerySet. Returns an integer 41 | **in_bulk()**| Return a QuerySet containing all objects with the listed IDs 42 | **iterator()**| Evaluate a QuerySet and return an iterator over the results. Can improve performance and memory use for queries that return a large number of objects 43 | **latest()**| Return the latest object in the database table based on the given field(s) 44 | **earliest()**| Return the earliest object in the database table based on the given field(s) 45 | **first()**| Return the first object matched by the QuerySet 46 | **last()**| Return the last object matched by the QuerySet 47 | aggregate()| Return a dictionary of aggregate values calculated over the QuerySet 48 | **exists()**| Returns True if the QuerySet contains any results 49 | **update()**| Performs an SQL UPDATE on the specified field(s) 50 | **delete()**| Performs an SQL DELETE that deletes all rows in the QuerySet 51 | **as_manager()**| Return a Manager class instance containing a copy of the QuerySet’s methods 52 | **explain()**| Returns a string of the QuerySet’s execution plan. Used for analyzing query performance 53 | -------------------------------------------------------------------------------- /5- Django Rest Status codes/README.md: -------------------------------------------------------------------------------- 1 | # views.py 2 | ``` 3 | from rest_framework import status 4 | from rest_framework.response import Response 5 | 6 | def empty_view(self): 7 | content = {'please move along': 'nothing to see here'} 8 | return Response({"Error":'Not Found'}, status=status.HTTP_404_NOT_FOUND) 9 | ``` 10 | **Or** 11 | ``` 12 | return Response({"Error":'Not Found'},status='404') 13 | ``` 14 | 15 | ## Informational - 1xx 16 | This class of status code indicates a provisional response. There are no 1xx status codes used in REST framework by default.\ 17 | 18 | HTTP_100_CONTINUE\ 19 | HTTP_101_SWITCHING_PROTOCOLS 20 | ## Successful - 2xx 21 | This class of status code indicates that the client's request was successfully received, understood, and accepted.\ 22 | 23 | HTTP_200_OK\ 24 | HTTP_201_CREATED\ 25 | HTTP_202_ACCEPTED\ 26 | HTTP_203_NON_AUTHORITATIVE_INFORMATION\ 27 | HTTP_204_NO_CONTENT\ 28 | HTTP_205_RESET_CONTENT\ 29 | HTTP_206_PARTIAL_CONTENT\ 30 | HTTP_207_MULTI_STATUS\ 31 | HTTP_208_ALREADY_REPORTED\ 32 | HTTP_226_IM_USED 33 | 34 | ## Redirection - 3xx 35 | This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.\ 36 | 37 | HTTP_300_MULTIPLE_CHOICES\ 38 | HTTP_301_MOVED_PERMANENTLY\ 39 | HTTP_302_FOUND\ 40 | HTTP_303_SEE_OTHER\ 41 | HTTP_304_NOT_MODIFIED\ 42 | HTTP_305_USE_PROXY\ 43 | HTTP_306_RESERVED\ 44 | HTTP_307_TEMPORARY_REDIRECT\ 45 | HTTP_308_PERMANENT_REDIRECT 46 | 47 | ## Client Error - 4xx 48 | The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. 49 | 50 | HTTP_400_BAD_REQUEST\ 51 | HTTP_401_UNAUTHORIZED\ 52 | HTTP_402_PAYMENT_REQUIRED\ 53 | HTTP_403_FORBIDDEN\ 54 | HTTP_404_NOT_FOUND\ 55 | HTTP_405_METHOD_NOT_ALLOWED\ 56 | HTTP_406_NOT_ACCEPTABLE\ 57 | HTTP_407_PROXY_AUTHENTICATION_REQUIRED\ 58 | HTTP_408_REQUEST_TIMEOUT\ 59 | HTTP_409_CONFLICT\ 60 | HTTP_410_GONE\ 61 | HTTP_411_LENGTH_REQUIRED\ 62 | HTTP_412_PRECONDITION_FAILED\ 63 | HTTP_413_REQUEST_ENTITY_TOO_LARGE\ 64 | HTTP_414_REQUEST_URI_TOO_LONG\ 65 | HTTP_415_UNSUPPORTED_MEDIA_TYPE\ 66 | HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE\ 67 | HTTP_417_EXPECTATION_FAILED\ 68 | HTTP_422_UNPROCESSABLE_ENTITY\ 69 | HTTP_423_LOCKED\ 70 | HTTP_424_FAILED_DEPENDENCY\ 71 | HTTP_426_UPGRADE_REQUIRED\ 72 | HTTP_428_PRECONDITION_REQUIRED\ 73 | HTTP_429_TOO_MANY_REQUESTS\ 74 | HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE\ 75 | HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS 76 | 77 | ## Server Error - 5xx 78 | Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. 79 | 80 | HTTP_500_INTERNAL_SERVER_ERROR\ 81 | HTTP_501_NOT_IMPLEMENTED\ 82 | HTTP_502_BAD_GATEWAY\ 83 | HTTP_503_SERVICE_UNAVAILABLE\ 84 | HTTP_504_GATEWAY_TIMEOUT\ 85 | HTTP_505_HTTP_VERSION_NOT_SUPPORTED\ 86 | HTTP_506_VARIANT_ALSO_NEGOTIATES\ 87 | HTTP_507_INSUFFICIENT_STORAGE\ 88 | HTTP_508_LOOP_DETECTED\ 89 | HTTP_509_BANDWIDTH_LIMIT_EXCEEDED\ 90 | HTTP_510_NOT_EXTENDED\ 91 | HTTP_511_NETWORK_AUTHENTICATION_REQUIRED 92 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Salah Ud Din 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # django-snippets 2 | Important codes 3 | These snippets includes FBV and CBV, i will codes in both ways. 4 | * Function based views 5 | * Class based views 6 | --------------------------------------------------------------------------------