Sanitize input in Django Rest Framework - python

If I send something like
{
"description": "Hello World <script>alert('hacked');</script>"
}
to my django rest framework view, I want to get rid of the the script tags.
Is there a convenient way to do this, that does not involve overwriting all the things and add strip_tags?
What else is to do to sanitize input?
Did I really overread that section in the drf docs or isn't that covered?

Ignore the answers here, they are terrible.
Use bleach. You won't get every edge case. This is the situation to use a library in. Your client has control of the client side by definition.

You can override the view's perform_create method and with a bit of regular expression do something like so
import re
class MyView(generics.CreateAPIView):
......
......
def perform_create(self, serializer):
replacement=re.sub('</*script>','',serializer.validated_data.get('description'))
serializer.save(description=replacement)
This is assuming you are using CreateAPIView or one of its mixins.
Or you could create a custom serializer field,
class MyCustomField(serializers.CharField):
def to_internal_value(self, data):
data=re.sub('</*script>','',data)
return super(MyCustomField,self).to_internal_value(data)
and
class MySerializer(serializer.ModelSerializer):
description=MyCustomField()
class Meta:
model= MyModel

Related

Python, bad practice to have same name on classes

I have multiple files like this in a django app.
django-app
----views
-------app_one.py
-------app_two.py
-------app_three.py
Inside app_one.py i have code similar to this
class AppOne:
... some methods ...
class Data(AppOne, APIView):
def post(request):
class History(AppOne, APIView):
def get(request):
In app_two.py I would like to name my classes like this (Note the sub_classes have the same names as in app_one):
class AppTwo:
... some methods ...
class Data(AppTwo, APIView):
def post(request):
class History(AppTwo, APIView):
def get(request):
So, my question is this: This works fine, I can run the server etc. But is this a bad practice? Could I run into unexpected results because of this?
The reason I want these specific names is because I use them inside Django admin for a permissions thing.
Views don't matter in the admin at all, so that's beside the point.
No, you shouldn't bump into any trouble; after all Django doesn't really care about your view classes' naming, it just cares about how they're hooked up in your urls (or if you're using DRF, based on APIView, your API router).
There's also nothing stopping you from inheriting things cross-app (after all, apps are just Python packages that are registered with Django) if that leads to less code and/or makes sense for you.

create custom methods in django class base views

I want to use generic class base views using django 1.9
What i am trying to understand that
from django.views.generic import CreateView
from braces.views import LoginRequiredMixin
from .models import Invoice
class InvoiceCreateView(LoginRequiredMixin,CreateView):
model = Invoice
def generate_invoice(self):
...
return invoice
now i want to bind this custom method to url. How can i achive this?
I know using function base view its simple but i want to do this using class base views.
Help will be appreciated.
Yes, this is the main issue to grasp in CBV: when things run, what is the order of execution (see http://lukeplant.me.uk/blog/posts/djangos-cbvs-were-a-mistake/).
In a nutshell, every class based view has an order of running things, each with it's own method.
CBV have a dedicated method for each step of execution.
You would call your custom method from the method that runs the step where you want to call your custom method from. If you, say, want to run your method after the view found that the form is valid, you do something like this:
Class InvoiceCreateView(LoginRequiredMixin,CreateView):
model = Invoice
def generate_invoice(self):
... do something with self.object
return invoice
def form_valid(self,form):
self.object = form.save()
self.generate_invoice()
return super(InvoiceCreateView,self).form_valid(form)
So you have to decide where your custom method should run, and define your own method on top of the view generic method for this step.
How do you know what generic method is used for each step of executing the view? That the method the view calls when it gets the initial data for the form is def get_initial? From the django docs, and https://ccbv.co.uk/.
It looks complex, but you actually have to write very few methods, just where you need to add your own behaviour.

Swagger not working with Django BaseSerializer object

I'm using django-rest-swagger to document and test an API and it has been working very well up to now but the following error has occured:
AttributeError at /docs/api-docs/app
'PeriodSerializer' object has no attribute 'get_fields'
'PeriodSerializer' inherits from serializers.BaseSerializer:
class PeriodSerializer(serializers.BaseSerializer):
def to_representation(self, instance):
return {
'lower': instance.lower,
'upper': instance.upper
}
def to_internal_value(self, data):
data = json.loads(data)
date_lower = self.date_from_str(data["lower"])
date_upper = self.date_from_str(data["upper"])
# some code omitted for brevity
return DateTimeTZRange(lower=date_lower, upper=date_upper)
#staticmethod
def date_from_str(datestr):
# code omitted for brevity
The code itself works fine, it's just that django-rest-swagger appears to have a problem with it. I'm using:
Python 3.4.0
Django 1.8.2
DRF 3.1.3
django-rest-swagger 0.3.2
Any help would be much appreciated.
Django Rest Framework's BaseSerializer doesn't have a get_fields function. You can see that in that in the source.
Short answer: Use Serializer, not BaseSerializer. Your code will work the same, and you won't have to worry about it. If for some reason you need to use BaseSerializer and django-rest-swagger together, you'll have to implement get_fields yourself.
If you look at the implementation of get_fields in a higher-level serializer (like Serializer) you'll see get_fields is defined like so:
def get_fields(self):
"""
Returns a dictionary of {field_name: field_instance}.
"""
# Every new serializer is created with a clone of the field instances.
# This allows users to dynamically modify the fields on a serializer
# instance without affecting every other serializer class.
return copy.deepcopy(self._declared_fields)
Using BaseSerializer, you won't have access to self._declared_fields either. You can see how that works in the linked source above, but the gist of it is that it returns a dictionary of attributes of the Field type.
Any instances of Field included as attributes on either the class
or on any of its superclasses will be include in the
_declared_fields dictionary.
I hope this helps answer your question!
Though late to the party but what works for me is something like this:
#six.add_metaclass(serializers.SerializerMetaclass)
class PeriodSerializer(serializers.BaseSerializer):
def get_fields(self):
"""
Returns a dictionary of {field_name: field_instance}.
"""
# Every new serializer is created with a clone of the field instances.
# This allows users to dynamically modify the fields on a serializer
# instance without affecting every other serializer class.
return copy.deepcopy(self._declared_fields)
i.e you need to decorate the class with a meta class which provides for _declared_field and then you can implement this method.
You could also try out drf-yasg. It is another swagger generator with support for the newer versions of Django Rest Framework.

Django ORM: wrapper for model objects

I am looking for some way to define some wrapper that is called before i call to Model.objects.all().
I want whenever i call, Model.objects it call my method (wrapper) and then return the objects back to the query.
Lets take an example:
MyModel.objcts.filter(name="Jack")
Wrapper:
def mymodelWrapper(self):
return self.objects.annotate(size=Sum('id', field='order_size_weight*requested_selling_price'))
I want to run annotate in the background and also want to apply the filter.
I Know what i want to achieve, its the code i am looking for how to do that.
What you are talking about is perfectly doable with Django by using a custom model manager:
class MyModelManager(models.Manager):
def get_query_set(self):
return super(MyModelManager, self).get_query_set().annotate(size=Sum('id', field='order_size_weight*requested_selling_price'))
class MyModel(models.Model):
objects = MyModelManager()
# fields
Also see other similar topics:
Is it possible to override .objects on a django model?
Override djangos's object.all() with the request data
Django custom model managers

How to create a django User using DRF's ModelSerializer

In django, creating a User has a different and unique flow from the usual Model instance creation. You need to call create_user() which is a method of BaseUserManager.
Since django REST framework's flow is to do restore_object() and then save_object(), it's not possible to simply create Users using a ModelSerializer in a generic create API endpoint, without hacking you way through.
What would be a clean way to solve this? or at least get it working using django's built-in piping?
Edit:
Important to note that what's specifically not working is that once you try to authenticate the created user instance using django.contrib.auth.authenticate it fails if the instance was simply created using User.objects.create() and not .create_user().
Eventually I've overridden the serializer's restore_object method and made sure that the password being sent is then processes using instance.set_password(password), like so:
def restore_object(self, attrs, instance=None):
if not instance:
instance = super(RegisterationSerializer, self).restore_object(attrs, instance)
instance.set_password(attrs.get('password'))
return instance
Thanks everyone for help!
Another way to fix this is to overwrite pre_save(self, obj) method in your extension of viewsets.GenericViewSet like so:
def pre_save(self, obj):
""" We have to encode the password in the user object that will be
saved before saving it.
"""
viewsets.GenericViewSet.pre_save(self, obj)
# Password is raw right now, so set it properly (encoded password will
# overwrite the raw one then).
obj.user.set_password(obj.user.password)
Edit:
Note that the obj in the code above contains the instance of User class. If you use Django's user model class directly, replace obj.user with obj in the code (the last line in 2 places).
I'm working with DRF. And here is how I create users:
I have a Serializer with overrided save method:
def save(self, **kwargs ):
try:
user = create_new_user(self.init_data)
except UserDataValidationError as e:
raise FormValidationFailed(e.form)
self.object = user.user_profile
return self.object
create_new_user is just my function for user creation and in the view, I just have:
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
It seems like you should be overriding restore_object() in your serializer, not save(). This will allow you to create your object correctly.
However, it looks like you are trying to abuse the framework -- you are trying to make a single create() create two objects (the user and the profile). I am no DRF expert, but I suspect this may cause some problems.
You would probably do better by using a custom user model (which would also include the profile in the same object).

Categories