request.data.get getting None in patch method - python-3.x

I am trying to get the id of user but request.get.data is not getting when i tried to print staff_user its showing None.but when use json.loads its working fine but reguest.data.get is showing None.
class MyDetailsAPIView(RetrieveUpdateDestroyAPIView):
permission_classes = [IsAuthenticated]
parser_classes = [MyMultiPartParser]
serializer_class = Myserializer
model = Document
lookup_url_kwarg = 'file_id'
def patch(self, request, *args, **kwargs):
staff_user_pk = request.data.get('staff_user_pk')
if staff_user_pk:
try:
staffuser = Staffuser.objects.get(id=staff_user_pk)
except Staffuser.DoesNotExist as exc:
raise ValidationError({'detail': exc})
file = self.get_object()
file.staffusers.add(staffuser)
return super().patch(request, *args, **kwargs)

Related

staticmethod in python is causing misleading execution

I implemented two versions of the same program. The difference between them is that the first uses class variable direct access while the second the #classmethod decorator to return the class variable value.
Version 1:
class Singleton2:
obj = None
def __new__(cls, *args, **kwargs):
if getattr(cls, 'obj') is None:
cls.obj = object.__new__(cls)
return cls.obj
else:
return cls.obj
def __init__(self):
pass
singleton2 = Singleton2()
singleton3 = Singleton2()
print(singleton2 == singleton3)
Version 2
class Singleton2:
obj = None
def __new__(cls, *args, **kwargs):
if getattr(cls, 'obj') is None:
cls.obj = object.__new__(cls)
cls.obj()
else:
cls.obj()
def __init__(self):
pass
#classmethod
def obj(cls):
return cls.obj
singleton2 = Singleton2()
singleton3 = Singleton2()
print(singleton2 == singleton3)
When I debugged the first version, the if statement is executed. That's correct.
When I debugged the second version, the else statement is executed because the statement if getattr(cls, 'obj') is None is returning false. How come?

How could I create a docstring decorator in the presence of properties?

I have a collection of ever more specialized classes which correspond to collections of the same kind of data (temperature, density, etc) but for different drifts, for example, one subclass has dimensions (nx, ny) and a different suclass has dimensions (ncv), and I want to reflect that in the docstrings, for having a better documentation using Sphinx.
After reading many very useful threads here in Stack Overflow, I have arrived to this model:
import numpy as np
from functools import wraps
def class_decorator(cls):
import ipdb; ipdb.set_trace()
clsdict = {}
mro = cls.mro()
mro.reverse()
for tmp in mro[1:]: ##Ignore object class parent.
clsdict.update(tmp.__dict__)
for name, method in clsdict.items():
if hasattr(method, '__og_doc__'):
try:
method.__doc__ = method.__og_doc__.format(**clsdict)
except:
pass
else:
try:
method.__og_doc__ = method.__doc__
method.__doc__ = method.__doc__.format(**clsdict)
except:
pass
return cls
def mark_documentation(fn):
if not hasattr(fn, '__og_doc__'):
try:
fn.__og_doc__ = fn.__doc__
except:
pass
#wraps(fn)
def wrapped(*args, **kwargs):
return fn(*args, **kwargs)
return wrapped
def documented_property(fn):
if not hasattr(fn, '__og_doc__'):
try:
fn.__og_doc__ = fn.__doc__
except:
pass
#wraps(fn)
def wrapped(*args, **kwargs):
return fn(*args, **kwargs)
prp= property(wrapped)
prp.__og_doc__ = fn.__og_doc__
return prp
#class_decorator
class Base(object):
_GRID_DIM = 'nx, ny'
_TYPE = 'BaseData'
def __init__(self, name):
self.name = name
def shape(self):
""" This docstring contains the type '{_TYPE}' of class."""
print('Simple')
def operation(self, a, b, oper=np.sum, **kwargs):
""" Test for functions with args and kwargs in {_TYPE}"""
return oper([a,b])
#classmethod
def help(cls, var):
try:
print(get(cls, var).__doc__)
except:
print("No docstring yet.")
#class_decorator
class Advanced(Base):
_GRID_DIM = 'ncv'
_TYPE = 'AdvancedData'
def __init__(self,name):
super().__init__(name)
#property
#mark_documentation
# #documented_property
def arkansas(self):
"""({_GRID_DIM}, ns): Size of Arkansaw."""
return 'Yeah'
I am aiming to get the correctly formatted docstring when I call the help method or I use Sphinx, so that:
> adv = Advanced('ADV')
> adv.help("arkansas")
(ncv, ns): Size of Arkansaw.
> adv.help("operation")
Test for functions with args and kwargs in AdvancedData
I have managed to make it work so far, except for properties, because I assigned __og_doc__ to the function, but the property does not have that attribute. My last attempt at monkeypatching this, documented_property, fails because property is inmutable (as expected), and I cannot come up with any way to avoid this roadblock.
Is there any way around this problem?

overwrite save django method

I need to override Django's method save so when the purchase is made by a certain cpf, it is saved with "Approved" status. Can someone help me?
Follow the models.py
class Purchases(TimeStampedModel):
APROVADO = "AP"
EM_VALIDACAO = "VA"
STATUS_CHOICHES = (
(APROVADO, "Aprovado"),
(EM_VALIDACAO, "Em validação"),
)
values = models.DecimalField(decimal_places=2, max_digits=10, default=0)
cpf = BRCPFField("CPF")
status = models.CharField(max_length=20, choices=STATUS_CHOICHES, default=EM_VALIDACAO)
You just need to add a new method
def save(self, *args, **kwargs):
#your business logic
super().save(*args, **kwargs)
def save(self, *args, **kwargs):
if self.cpf == "15350946056":
self.status = "AP"
super(Purchases, self).save(*args, **kwargs)
else:
self.status = "VA"
super(Purchases, self).save(*args, **kwargs)
The CPF is between " " because the BRCPFField deals with charfild, we need to transform the cpf into a string so that there is a comparison

"'Request' object has no attribute 'learner'": Django Restframework

There is an error in my code "'Request' object has no attribute 'learner'". Here, My requirement is "request.learner" is empty then call "CDetailsSerializer" otherwise call "CourseDetailsSerializer".
def list(self, request, **kwargs):
try:
queryset = self.get_queryset()
queryset = self.filter_queryset(queryset)
if not request.learner:
serializer = CDetailsSerializer(queryset, many=True)
else:
serializer = CourseDetailsSerializer(queryset, many=True)
print('s', serializer.data)
response_data = {'course': serializer.data}
return self.jp_response(s_code='HTTP_200_OK', data=response_data)
except Exception as e:
print(e)
return self.jp_error_response('HTTP_500_INTERNAL_SERVER_ERROR', 'EXCEPTION', [str(e), ])
Here always calling (else part) CourseDetailsSerializer, but in some situations, I also want to call (if part) CDetailsSerializer.Give me a solution to fix this.

django __init__() takes 1 positional argument but 6 were given

My model class:
class Campaign(models.Model):
name = models.CharField(max_length=255)
campaign_id = models.CharField(max_length=8, null=False, blank=False, unique=True)
def __init__(self):
super(Campaign, self).__init__(self)
self.campaign_id = generate_random_id(8) # it generates just random string
class Meta:
ordering = ["name"]
def __str__(self):
return self.name
My view class:
def campaign_list(request):
campaigns = Campaign.objects.order_by('name').all()
return render(request, 'mp/campaign/list.html', {'campaigns': campaigns})
I got error
init() takes 1 positional argument but 6 were given
Before creating init in my model everything were working fine. But i assume that now Campaing.object.all() is using constructor and not str. How can i omit this and in .all still use just referring to name, not creating an object again?
why this is happening
I was getting the Below Error:
Response.__init__() take one positional argument but 2 were given
consider the example below having a function in views.py and returning the Response
but when I used the auto import extension in visual studio
Accidently I Imported the Response class from the requests module instead of rest_framework
# example
from requests import Response
#from rest_framework.response import Response
def hello_world_view(request):
return Response('ok')
Response class from request module
having 1 position argument
Response class from rest_framework
can have many position argument
It may work to pass *args, **kwargs as arguments in the init.
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs) # dont have to pass self
self.campaign_id = generate_random_id(8) # it generates just random string
You can also override the save method
def save(self, *args, **kwargs):
self.campaign_id = generate_random_id(8)
super().save(*args, **kwargs)
Override save method instead of the initializer:
class Campaign(models.Model):
name = models.CharField(max_length=255)
campaign_id = models.CharField(max_length=8, unique=True)
def save(self, *args, **kwargs):
self.campaign_id = generate_random_id(8)
super().save(*args, **kwargs)
class Meta:
ordering = ["name"]
def __str__(self):
return self.name

Resources