Skip to content

Instantly share code, notes, and snippets.

@deepanshumehtaa
Last active March 6, 2024 17:39
Show Gist options
  • Save deepanshumehtaa/4fa29d752b3a6e85d82b27a5068730b3 to your computer and use it in GitHub Desktop.
Save deepanshumehtaa/4fa29d752b3a6e85d82b27a5068730b3 to your computer and use it in GitHub Desktop.
Django-template-view
m2m
class Post(models.Model):
slug = models.SlugField(max_length=200, unique=True)
likes = models.ManyToManyField(User, related_name='blogpost_like', blank=True)
post = get_object_or_404(Post, slug=slug)
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
else:
post.likes.add(request.user)
.....................................................................................
Group By >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.
q = Bank.objects.filter(status="no").values("month").annotate(duration_count=Count("duration"))
>> <QuerySet [
{'month': 'may', 'duration_count': 1305},
{'month': 'apr', 'duration_count': 237},
{'month': 'aug', 'duration_count': 554},
{'month': 'jan', 'duration_count': 132}, ...]
>> q.query.__str__()
>>
SELECT month, COUNT(duration) AS `duration_count`
FROM bank
WHERE status = no
GROUP BY month
ORDER BY NULL'
......................................................................................
select coalesce(age/id, 0) from bank;
`coalesce(age/id, 0)` --> will return default value if the calculation is null (divide by zero also gives Null)
age/null --> null
null/id --> null
id/null --> null
..........................................................................................
Round(1.732, 2) ---> 1.73
>> select Round(1.732, 2) from bank;
..........................................................................................
from django.db.models import Model, Count, Max, Min
Bank.objects.values("month").annotate(max_age=Max("age"), min_age=Min("age"))
>>
[{'month': 'may', 'max_age': 84, 'min_age': 20},
{'month': 'apr', 'max_age': 80, 'min_age': 20},
{'month': 'aug', 'max_age': 81, 'min_age': 21}, ...]
>>
SELECT month, MAX(age) AS `max_age`, MIN(age) AS `min_age`
FROM `bank`
GROUP BY month
ORDER BY NULL
...........................................................................................
Bank.objects.values("month").annotate(
max_age=Max("age"), min_age=Min("age")
).filter(max_age__gt=70)
>>
SELECT month, MAX(age) AS `max_age`, MIN(age) AS `min_age`
FROM bank
GROUP BY month
HAVING MAX(age) > 70 ORDER BY NULL
............................................................................................
Function Based View
------------------------------------------------------------------------------------------
from django.shortcuts import render, redirect, reverse
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
class UploadCsvPartsView(View):
'''
View that handles the upload csv feature of the admin interface.
'''
template_view = 'admin/base_upload_page.html'
template_view_erros = 'admin/upload_page.html'
insertion_method = 'insert_only'
error_message = 'Errors were found, Please fix them.'
@method_decorator([csrf_exempt, login_required])
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def get(self, request):
"""
this method returns the rendered html for upload page
"""
data = request.GET
extra_params = dict()
model_name = data['model_name']
app_label = data['app_label']
if not object_id and role not in [Utils.ROLE_CENTRAL_INV_MANAGER,
Utils.ID_SUPERADMIN]:
return HttpResponseForbidden()
for key, value in data.items():
if key not in ('model_name', 'app_label'):
extra_params[key] = value
return render(request, self.template_view, {'extra_params': extra_params,
'url_back': 'admin:%s_%s_changelist' % (app_label, model_name)})
def post(self, request):
'''
This HTTP method gets the csv as a file object.
It then created temp table to store the data with errors
and other validation logic such as
check if the file is not empty and there are some error free rows.
It also returns a sample csv to download.
'''
data = request.POST
model_name = data['model_name']
app_label = data['app_label']
if data.get('back'):
try:
obj.delete_temp_table(data['table'])
except:
pass
return HttpResponseRedirect(
reverse('admin:%s_%s_changelist' % (app_label, model_name)))
else:
print(request.path) // gives you the URL in Browser
return render(request=request,
template_name=self.template_view_erros,
context={'errors': errors, 'data': data, 'total': total_count,
'url_back': 'admin:%s_%s_changelist' % (app_label, model_name),
'url_save': reverse('save_upload_data')})
Now with some more Beauty
---------------------------------------------------------------------------------------------
from django.http import HttpRequest, HttpResponse
from django.shortcuts import redirect, render
from django.views.generic.base import TemplateView, View
class LogoutUserView(View):
"""GET requests to this view delete session data."""
def get(self: View, request: HttpRequest) -> HttpResponse:
"""Logout a user, and delete their associated chatroom."""
slug = request.session.get('slug')
if slug:
room = Room.objects.filter(slug=slug)
if room is not None:
room.delete()
request.session.flush()
return redirect('/')
class ChatRoomView(TemplateView):
"""Render a room if it exists, otherwise return a 404 page."""
def get(self: View, request: HttpRequest, slug: str) -> HttpResponse:
"""Find a room that matches the provided slug."""
room = Room.objects.filter(slug=slug).first()
if room is not None:
return render(request, 'room.html', context=dict(room=room))
else:
return render(request, '404.html', status=404, context=dict(room=slug))
Similarly Api as Decent Look
===============================================================================
from django.http import HttpRequest, JsonResponse
from django.views.generic import View
from humanhash import humanize
class RegisterUserView(View):
"""POST to this endpoint to register a user."""
def post(self: View, request: HttpRequest) -> JsonResponse:
"""Create a user, provided the username."""
try:
payload = json.loads(request.body.decode())
except json.JSONDecodeError:
return error('You supplied incorrect data.')
username = str(payload.get('username', ''))
if request.session.get('registered'):
return error('You are already registered.')
if not 1 <= len(username) <= 100:
return error('Username length must be between 1 and 100.')
digest = uuid4().hex
slug = humanize(digest)
request.session['slug'] = slug
request.session['registered'] = True
request.session['username'] = username
room = Room(uuid=digest, slug=slug)
room.save()
return JsonResponse({
'success': True,
'slug': slug
})
-------------------------------------------------------------------------------------------
Updating the Only Fields that is really need to change
if change:
obj.updated_at = datetime.datetime.now()
obj.updated_by = request.user.first_name
obj.save(update_fields=['updated_at', 'updated_by'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment