0

I use Django 2.7 to build Rest API application, and having problem to validate/clean the request data from client for get detail transaction (Not Save/update). for example the request data trx_no cannot less than 5 char length. where's the validation class i should create? should I validate on Model.py or using forms, or in serializer? Here's my models.py:

class mst_trx(models.Model):
    trx_no = models.CharField(max_length=20,primary_key=True) 

Here's my views.py:

class views_index(APIView):

def post(self,request):
    action = request.POST['action']

    if action == 'detail' :
        resp = detail.as_view()(request)


class detail(APIView):
    def dispatch(self,request): 

    ##I want to validate first before get data
    try:
        detail = mst_trx.objects.select_related().get(pk=request.POST['trx_no'])
    except mst_trx.DoesNotExist:
        raise Http404("Transaction does not exist")
    else:
        serializer = TrxDetailSerializer(detail)
        return serializer.data

And Here's my serializer.py :

class TrxDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = mst_trx
        fields = ('trx_no')

1 Answer 1

1

Validation logic should be in forms.py file

for e.g.

def clean_columnname(self):
    columnname = self.cleaned_data['columnname']
    if len(columnname) < 1:
        raise ValidationError('Please add some content  ...')
    elif len(columnname) > 500000:
        raise ValidationError('Too many characters ...')
    return columnname
Sign up to request clarification or add additional context in comments.

1 Comment

@dennysaputra You just need to call isValid() for your form and clean_fieldname will be called. form = YourForm(request.POST) form.is_valid() For more details you can refer official doc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.