In this tutorial we will learn some of the concept that are need while we writing the login in view file.
1.Updating the data while coming from form data
#method-1
_mutable = data._mutable
data._mutable = True
data['task']=task.uuid
data._mutable = _mutable
#method-2
data = request.data
request.POST._mutable = True
peaks = json.loads(data["peak"])
data["peak"] = peaks[0]
data["added_by"] = request.user.uuid
request.POST._mutable = False
closing_stock = obj.inventorystock_set.order_by('created_at').last()
item = InventoryItem.objects.get(Q(sku=sku) | Q(upc=sku))
inventry_group = InventoryGroup.objects.filter(company=company
).values_list("brand", flat=True).distinct()
If list of image is coming from the fronend then used this concept to handle it.
#if more than one files is comes
new_image_list=[]
image_list = request.FILES.getlist("image")
if image_list:
if len(image_list) > 0:
for image in image_list:
new_image_list.append({
"image": image
})
item_gallery = ItemGallerySerializer(
data=new_image_list, many=True, context={"request": request})
item_gallery.is_valid(raise_exception=True)
item_gallery.save()
when you need the recently saved object to be used
inv_group = inventory_group_ser.save(added_by=request.user)
inv_group_obj = InventoryGroup.objects.get(uuid=inv_group.uuid)
for i in inventory_list_ser.data:
item_uuid = i.get("uuid")
inv_item = InventoryItem.objects.get(uuid=item_uuid)
quantity = i.get('opening_stock')
InventoryStock(item_uuid=inv_item, opening_stock=0,
closing_stock=quantity, added_by=request.user).save()
Exception Handling
from django.core.exceptions import ObjectDoesNotExist
try:
user = User.objects.get(pk=1337)
phone = Team.objects.get(pk=1337)
except ObjectDoesNotExist:
logging.error("User or Team does not exist")
except model_name.DoesNotExist:
return Responser('error message')
except ValueError as e:
return Response(str(e))
except Exception as e:
return Response(str(e))
Important concept in views.py
ip=request.META.get('REMOTE_ADDR') # to get the ip address of web browser
last_url=request.META.get('HTTP_REFERER')
return HttpResponseRedirect(last_url)
remove=request.GET.get('remove','off')
file=request.FILES['notefile']
file=request.FILES.get('notefile')
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
#for functional view
@login_required
@staff_member_required
@permission_required('appname.can_add')
#for class view
@method_decorator(login_required,name='dispatch')
Additional
"photo": base64.b64encode(product.photo).decode("utf-8") if product.photo else None
province_id = request.query_params.get("data", None)
"category": product.category.name if product.category else None,
"subcategory": product.sub_category.name if product.sub_category else None
"photo": request.build_absolute_uri(product.photo.url),
image_list = request.FILES.getlist("image")
inventry_group = InventoryGroup.objects.all().values_list("brand", flat=True).distinct()
data.update({"cover_image": request.data.get('cover_image')})if 'cover_image' in data.keys() else data.update({"cover_image": request.data.get('new_image')}
data = json.loads(request.data["success"])
image = request.FILES.getlist('icon')
for idx, data_obj in enumerate(data):
data_obj["icon"] = image[idx]
data_obj["added_by"] = request.user.uuid
email = str(data['email']).strip() if 'email' in data else ''
if not email:
json_error.append('Email can not be blank')
else:
if User.objects.filter(email=email).exists():
pass
else:
json_error.append("Please send correct email.")
Amanda Martines 5 days ago
Exercitation photo booth stumptown tote bag Banksy, elit small batch freegan sed. Craft beer elit seitan exercitation, photo booth et 8-bit kale chips proident chillwave deep v laborum. Aliquip veniam delectus, Marfa eiusmod Pinterest in do umami readymade swag. Selfies iPhone Kickstarter, drinking vinegar jean.
ReplyBaltej Singh 5 days ago
Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.
ReplyMarie Johnson 5 days ago
Kickstarter seitan retro. Drinking vinegar stumptown yr pop-up artisan sunt. Deep v cliche lomo biodiesel Neutra selfies. Shorts fixie consequat flexitarian four loko tempor duis single-origin coffee. Banksy, elit small.
Reply