Add object to ManyToMany field using CreateModelMixin.create() - python

I use mixins.CreateModelMixin.create to create object, but also I need to add request.user to m2m fields in it. So my idea is to catch the object from self.create() and than filally make obj.users.add(user). But CreateModelMixin return only responce. How can I get an object from .create? Is it a better way to add user? Can I user super (not good in it)? Thanks!
ADDED:
I can use perform_create() and catch object here, but it makes code bigger and repeat .create() mostly, so I don't think that is a right way.
ADDED:
Code I user now:
#action(detail=False, methods=['POST'], serializer_class=CompanyAdminSerializer)
def create_company(self, request):
user = self.request.user
if user.user_of_company.exists():
raise NotAcceptable(detail='Only one company allowed')
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
company = serializer.save()
company.users.add(user)
company.admin_users.add(user)
return Response(serializer.data)

To catch the instance from create you will have to override the create method.
The simplest way would be to override the perform_create method.
.save() returns the instance of the created object. source
Your code will look like the following:
#Assuming you're using CreateAPIView
class New_Create(CreateAPIView):
def perform_create(self, serializer):
obj = serializer.save()
#Adding to M2M
obj.users.add(self.request.user)
DRF Serializers do not support M2M create/update out of the box.
EDIT:
I do not recommend overriding the create method. The perform_create method has been created to serve exactly this purpose. You can access the instance only after .save() has been called. So, after calling .save() on the serializer you can update the instance however you want. Two ways to access the instance are:
1) Use the object being returned by the .save method (as shown above)
2) You can use serializer.instance. (Again you can only access the instance after .save has been called. )

Related

do we need query set in CreateAPIView?

My question is quite straight forward. I'm actually not sure that queryset is required need for CreateAPIView or not.. ?
class CreateNotificationAPIView(generics.CreateAPIView):
"""This endpoint allows for creation of a notification"""
queryset = Notification.objects.all() #can we remove it, if we do so, will we face any issue in future ?
serializer_class = serializers.NotificationSerializer
No. The only HTTP method the CreateAPIView [drf-doc] offers is the POST method, and it implements this by making a call to the create method. The .create(…) method is implemented as [GitHub]:
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
These methods only work with the serializer, or with self.perform_create and self.get_success_headers that by default only work with the data of the serializer.
If you thus not override the methods of the CreateAPIView to use the queryset somehow, you can define a CreateAPIView without defining a queryset or override get_queryset.
according to REST_docs
queryset - The queryset that should be used for returning objects from
this view. Typically, you must either set this attribute, or override
the get_queryset() method. If you are overriding a view method, it is
important that you call get_queryset() instead of accessing this
property directly, as queryset will get evaluated once, and those
results will be cached for all subsequent requests.

rest api - Abort object creation in serializer create method

I'm wondering whether serializer create method is a good place for aborting object(model) creation. Let consider following code:
class TestSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Test
fields = ('url', ...)
def create(self, validated_data):
if everything_is_ok:
return super().create(validated_data)
else: #if something is wrong with data abort object creation and rise exception that will led to 400 or sth
???
From my perspective it looks ok, because I'm using many serializers and here I have code only related to that particular one. Nevertheless I'm not sure if this is correct way (maybe create method of ModelViewSet would be better?)
If serializer create method is ok, how should I do it properly (raise exception or rather return 400 Response directly)
Thank you in advance

Django Class Based View UpdateView Restricted User

I am trying to use a Django UpdateView to display an update form for the user. https://docs.djangoproject.com/en/1.8/ref/class-based-views/generic-editing/
I only want the user to be able to edit their own form.
How can I filter or restrict the the objects in the model to only show objects belonging to the authenticated user?
When the user only has one object I can use this:
def get_object(self, queryset=None):
return self.request.user.profile.researcher
However, I now need the user to be able to edit multiple objects.
UPDATE:
class ExperimentList(ListView):
model = Experiment
template_name = 'part_finder/experiment_list.html'
def get_queryset(self):
self.researcher = get_object_or_404(Researcher, id=self.args[0])
return Experiment.objects.filter(researcher=self.researcher)
class ExperimentUpdate(UpdateView):
model = Experiment
template_name = 'part_finder/experiment_update.html'
success_url='/part_finder/'
fields = ['name','short_description','long_description','duration', 'city','address', 'url']
def get_queryset(self):
qs = super(ExperimentUpdate, self).get_queryset()
return qs.filter(researcher=self.request.user.profile.researcher)
URL:
url(r'^experiment/update/(?P<pk>[\w\-]+)/$', login_required(ExperimentUpdate.as_view()), name='update_experiment'),
UpdateView is only for one object; you'd need to implement a ListView that is filtered for objects belonging to that user, and then provide edit links appropriately.
To prevent someone from simply putting the URL for an edit view explicitly, you can override get_object (as you are doing in your question) and return an appropriate response.
I have successfully been able to generate the list view and can get
the update view to work by passing a PK. However, when trying to
override the UpdateView get_object, I'm still running into problems.
Simply override the get_queryset method:
def get_queryset(self):
qs = super(ExperimentUpdate, self).get_queryset()
# replace this with whatever makes sense for your application
return qs.filter(user=self.request.user)
If you do the above, then you don't need to override get_object.
The other (more complicated) option is to use custom form classes in your UpdateView; one for each of the objects - or simply use a normal method-based-view with multiple objects.
As the previous answer has indicated, act on the list to show only the elements belonging to the user.
Then in the update view you can limit the queryset which is used to pick the object by overriding
def get_queryset(self):
qs = super(YourUpdateView, self).get_queryset()
return qs.filter(user=self.request.user)

Django REST Framework: creating hierarchical objects using URL arguments

I have a django-rest-framework REST API with hierarchical resources. I want to be able to create subobjects by POSTing to /v1/objects/<pk>/subobjects/ and have it automatically set the foreign key on the new subobject to the pk kwarg from the URL without having to put it in the payload. Currently, the serializer is causing a 400 error, because it expects the object foreign key to be in the payload, but it shouldn't be considered optional either. The URL of the subobjects is /v1/subobjects/<pk>/ (since the key of the parent isn't necessary to identify it), so it is still required if I want to PUT an existing resource.
Should I just make it so that you POST to /v1/subobjects/ with the parent in the payload to add subobjects, or is there a clean way to pass the pk kwarg from the URL to the serializer? I'm using HyperlinkedModelSerializer and ModelViewSet as my respective base classes. Is there some recommended way of doing this? So far the only idea I had was to completely re-implement the ViewSets and make a custom Serializer class whose get_default_fields() comes from a dictionary that is passed in from the ViewSet, populated by its kwargs. This seems quite involved for something that I would have thought is completely run-of-the-mill, so I can't help but think I'm missing something. Every REST API I've ever seen that has writable endpoints has this kind of URL-based argument inference, so the fact that django-rest-framework doesn't seem to be able to do it at all seems strange.
Make the parent object serializer field read_only. It's not optional but it's not coming from the request data either. Instead you pull the pk/slug from the URL in pre_save()...
# Assuming list and detail URLs like:
# /v1/objects/<parent_pk>/subobjects/
# /v1/objects/<parent_pk>/subobjects/<pk>/
def pre_save(self, obj):
parent = models.MainObject.objects.get(pk=self.kwargs['parent_pk'])
obj.parent = parent
Here's what I've done to solve it, although it would be nice if there was a more general way to do it, since it's such a common URL pattern. First I created a mixin for my ViewSets that redefined the create method:
class CreatePartialModelMixin(object):
def initial_instance(self, request):
return None
def create(self, request, *args, **kwargs):
instance = self.initial_instance(request)
serializer = self.get_serializer(
instance=instance, data=request.DATA, files=request.FILES,
partial=True)
if serializer.is_valid():
self.pre_save(serializer.object)
self.object = serializer.save(force_insert=True)
self.post_save(self.object, created=True)
headers = self.get_success_headers(serializer.data)
return Response(
serializer.data, status=status.HTTP_201_CREATED,
headers=headers)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Mostly it is copied and pasted from CreateModelMixin, but it defines an initial_instance method that we can override in subclasses to provide a starting point for the serializer, which is set up to do a partial deserialization. Then I can do, for example,
class SubObjectViewSet(CreatePartialModelMixin, viewsets.ModelViewSet):
# ....
def initial_instance(self, request):
instance = models.SubObject(owner=request.user)
if 'pk' in self.kwargs:
parent = models.MainObject.objects.get(pk=self.kwargs['pk'])
instance.parent = parent
return instance
(I realize I don't actually need to do a .get on the pk to associate it on the model, but in my case I'm exposing the slug rather than the primary key in the public API)
If you're using ModelSerializer (which is implemented by HyperlinkedModelSerializer) it's as easy as implementing the restore_object() method:
class MySerializer(serializers.ModelSerializer):
def restore_object(self, attrs, instance=None):
if instance is None:
# If `instance` is `None`, it means we're creating
# a new object, so we set the `parent_id` field.
attrs['parent_id'] = self.context['view'].kwargs['parent_pk']
return super(MySerializer, self).restore_object(attrs, instance)
# ...
restore_object() is used to deserialize a dictionary of attributes into an object instance. ModelSerializer implements this method and creates/updates the instance for the model you specified in the Meta class. If the given instance is None it means the object still has to be created, so you just add the parent_id attribute on the attrs argument and call super().
So this way you don't have to specify a read-only field, or have a custom view/serializer.
More information:
http://www.django-rest-framework.org/api-guide/serializers#declaring-serializers
Maybe a bit late, but i guess this drf nested routers library could be helpful for that operation.

How to access REMOTE_ADDR in a model's save() method

I have a model (UserProfile) with which I want to record a user's IP address when new user accounts are created.
I've begin the process of overriding the Django model's save() method, but I am totally uncertain how to properly access HttpRequest attributes from within a model. Can any of you guys help? Google was unable to provide a specific answer for me.
You can get to the request from within the admin, but you can't do it in general code. If you need it then you'll have to assign it manually in the view.
You always need to pass on request information from the view to your save-method.
Consider that saving an instance doesn't always have to be invoked from a http request (for a simple example think of calling save in the python shell).
If you need to access the request object within the admin while saving, you can override it's save_model method:
def save_model(self, request, obj, form, change):
# do something with obj and request here....
obj.save()
But otherwise you always have to pass it on from the view:
def my_view(request):
obj = MyClass(ip_address = request.META['REMOTE_ADDR'])
Or to make this easier to re-use, make a method on the model like:
def foo(self, request):
self.ip_address = request.META['REMOTE_ADDR']
self..... = request.....
and call it from your view with obj.foo(request).

Categories

Resources