How to sanitize Django Rest Framework inputs - django

How to sanitize the charfield in Django Rest Framework Using Serializer Or Django models itself. No idea how to secure
This value can be makes my app vulnerable.... Like XSS
<script>alert('Hacked')</script>
Check the serializer code
class Meta:
model = MyDB
fields = ['id','name','price','isAvailable','isVeg','hotelID']
read_only_fields = ['id']
I Have seen Bleach. But it feels like not dynamic, i.e cant be applied to all input field at same time.
Is any option that can be used dynamic. I'm not pro in Django so please suggest me

Related

How to connect a ReactJS Form to a Django model to automatically obtain fields (foreignkeys, choices etc.)

I have a quite complex Django model that is connected to my ReactJS frontend through a DRF API. Inside this model, many instances are ForeignKey or CharFields that include an array of options to be selected. Can you please tell me if there's a way I can have my React form to inherit the information of all the fields, instead of writing out the form manually?
I'd need the frontend form in React to "read" through the right API call and get all the fields from there. How can I achieve this?Thank you very much in advance!
you can achieve that by using RetrieveUpdateAPIView from DRF
class GetDateAndUpdate(RetrieveUpdateAPIView):
queryset = YOURMODEL.objects.all()
serializer_class = YOURMODELSerializer
permission_classes = [IsAuthenticated,IsOwner]
# in urls.py
url(r'^(?P<pk>[-\w]+)/update/$',
GetDateAndUpdate.as_view(),
name='update',
),
you can find more here
http://www.django-rest-framework.org/api-guide/generic-views/#retrieveupdateapiview

Django - How to get the max_length of a field

How do I access the max_length of a model field in Django? I am writing a serializer with the REST framework and I want to write a custom validation function to validate the length. Note that i am using SQLite, so the database itself does not enforce the max_length.
You can use the Model _meta API for accessing details of your model's fields.
Here's an example:
class MyModel(models.Model):
title = models.CharField(max_length=200)
# retrieve the max_length
MyModel._meta.get_field('title').max_length
The _meta became a formal API in Django version 1.8. The documentation can be found at https://docs.djangoproject.com/en/stable/ref/models/meta/

mongoengine and django rest framework - fields aren't allowed to be optional

I've setup a REST api with django rest framework, using mongoengine as the ORM for my models. However, I keep getting this response back from the api for a field that should be optional:
{"ref":["This field may not be null."]}
The problem I'm running into is that it seems like all fields (I'm specifically using ReferenceFields, but I've tried it with StringFields, etc too) are not allowed to be optional/null.
I've tried setting validation methods to an empty lambda (that returns True), setting null=True and required=False where the field is defined in the model.
from mongoengine import *
class B(Document):
...
class A(Document):
ref = ReferenceField('B', null=True, required=False, dbref=False, validation=lambda: True)
I even tried explicitly setting the serializer in A's serializer so that I could tell it to allow nulls (with allow_null=True):
from api.models import A,B
from rest_framework_mongoengine.serializers import DocumentSerializer
class BSerializer(DocumentSerializer):
class Meta:
model = B
depth = 2
class ASerializer(DocumentSerializer):
ref = BSerializer(allow_null=True)
class Meta:
model = A
depth = 2
How do I get optional (nullable) fields to work with django rest framework and mongoengine? Again, this isn't just ReferenceFields, it's the same with any field I try.

Required POST parameter in django or django-rest-framework

How do you enforce a required field when using POST in django view or django-rest-framework view other than this:
required_field = ['id', 'email', 'name']
for f in required_field:
if not f in request.POST:
print "Required field missing"
Is there a better way?
Django REST Framework allows you to specify required=True when initializing the field. If you are using a model, Django REST Framework will automatically detect if the field is required based on if the field has empty=False specified when it was initialized.
When working outside of Django REST Framework, there is no better way of checking for required fields than doing what you are currently doing.

Admin Form Integration for Custom Model Fields in Django

I need a model field composed of a numeric string for a Django app I'm working on and since one doesn't exist I need to roll my own. Now I understand how "get_db_prep_value" and such work, and how to extend the Model itself (the django documentation on custom model fields is an invaluable resource.), but for the life of me I can't seem to figure out how to make the admin interface error properly based on input constraints.
How do I make the associated form field in the admin error on incorrect input?
Have a look at the Form and field validation section in the Django documentation, maybe that's what you're looking for?
You would have to make a new type of form field for your custom model field.
All you need to do is define a custom modelform which uses your new field, and then tell the admin to use that form to edit your models.
class MyModelForm(forms.ModelForm):
myfield = MyCustomField()
class Meta:
model = MyModel
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm