DRF validator to modify requested data - django-rest-framework

from this serializer:
class SerializerExample(serializers.Serializer):
attr = serializers.CharField()
def validate(self, test_validate):
attr = test_validate['attribute']
if attr == 'whatever':
test_validate['attribute'] = 'check 1'
else:
test_validate['attribute'] = 'check 2'
return test_validate
Now, this is used in the endpoint:
#swagger_auto_schema(query_serializer=SerializerExample)
def create(self, request):
return request_data
So, my question is, will be modifed request.data with the validated method or not?

Ok, no, it's not going to modify the data.
And, in the other hand, If you could you shouldn't, because the official documentation says that you must returns the same data you receive.
This validation only check valid data and raise error if don't match a criteria.

Related

Django abstractuser can't set parameters

I am trying to set a flag when a user signs up. The flags show up on the admin site, so I know the abstract user was implemented. When I toggle them in the admin area it works as well. I just can't get the form to work for regular users. I have tried many combinations with self.instance and self.request.
def save(self, commit=True):
self.instance.user.is_member = True
### additional code that works and sets non-abstractuser parameter ####
return super(UpdateUserProfileForm, self).save(commit=commit)
def form_valid(self, form):
form.instance.user = self.request.User
# form.instance.user.is_member = True
# self.request.user.is_member = True
return super().form_valid(form)
After further research I needed to add the lines
def save(self, commit=True):
user = self.instance.user
user.is_member = True
user.save()

Decent way to add a validator for DRF Field class child

I have a custom DRF field element that looks like this:
class TimestampField(serializers.DateTimeField):
def __init__(self, allow_future=True, *args, **kwargs):
self.allow_future = allow_future
def some_sort_of_validator(...): # Don't know how to do that
if not self.allow_future:
if value > timezone.now():
raise ValidationError('...')
Basically, I want to do some custom validation for that field elements. For example, I want to assure that future dates are prohibited. Looks like I need to add something that is refered to as validator in the docs. And I wonder how to do that correctly, so that not to kill native validators. I found nothing regarding this neither in the DRF doc, nor in SO.
There is an article in the docs about writing validators and a section about writing custom validators.
in your case, something like this should work
class TimestampValidator:
def __init__(self, allow_future):
self.allow_future = allow_future
def __call__(self, value):
if not self.allow_future:
if value > timestamp.now():
raise ValidationError('...')
and to use it in your actual serializer
class MySerializer((serializers.Serializer):
timestamp = serializers.DateTimeField(validators=[TimestampValidator(allow_future=True)])
# .. the rest of your serializer goes here
you can also check the code for the built-in validators to see how they are done

Django Forms - is it advisable to change user submitted data in the clean method

I have the following code in my Django project:
def my_view(request):
form = MyForm(request.POST):
if form.is_valid():
instance = form.save(commit = False)
instance.some_field = 'foo'
form.save()
#...
The question is, is it advisable to rewrite this the following way:
forms.py
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
# ...
def clean(self):
form.some_field = 'foo'
I wonder, if clean method should be used exclusively for data validation, or I could also perform here some business logic stuff, thus making my views more concise and devoid of business logic details.
One of possible advantages of making the assignment in the clean method is that sometimes data validation could be dependent on some_field.
Have you considered putting it in .save?

Rails 4 validation not working

I have a model which I would like to validate the name if it is part of an array that I get from somebody else's API.
class Model < ActiveRecord::Base
validate :exists_at_api?
def exists_at_api?
api_data.detect { |d| d == self.name }
end
end
The problem occurs when I send invalid data
The validation gets called, and returns false, but the model is still saved.
I also tried this variation of the above with the same results:
validate :name, if: :exists_at_api?
I'm sure this is something simple, can somebody point me in the right direction?
You need to add something to the errors hash to indicate the failure. See the Rails documentation for details and examples.
Try something like:
validate :exists_at_api?
def exists_at_api?
if api_data.detect { |d| d == self.name }
errors.add(:name, "can't be whatever...")
end
end

Generating JSON for Sinatra

I'm having an issue with passing the generated JSON notation of my object to my Sinatra application. The problem I have is twofold:
I have 2 classes that are mapped to a database using the Sequel gem. When they generate JSON it is ok and properly implemented.
I have a custom class called registration that maps one of the classes with an additional field. The goal is to generate JSON out of this and pass that JSON to the application using cucumber (test purpose)
The application code responsible for handling the request has the following function defined:
post '/users' do
begin
hash = JSON.parse(self.request.body.read)
registration = Registration.new.from_json(#request.body.read)
registration.user.country = Database::Alaplaya.get_country_by_iso_code(registration.user.country.iso_code)
return 400 unless(registration.is_valid?)
id = Database::Alaplaya.create_user(registration.user)
# If the registration failed in our system, return a page 400.
return 400 if id < 1
end
problem 1: I cannot use the params hash. It exists but is just an empty hash. Why?
problem 2: I cannot deserialize the JSON generated by the class itself. Why?
The registration class looks like this:
require 'json'
class Registration
attr_accessor :user, :project_id
def to_json(*a)
{
'json_class' => self.class.name,
'data' => [#user.to_json(*a), #project_id]
}.to_json(*a)
end
def self.json_create(o)
new(*o['data'])
end
# Creates a new instance of the class using the information provided in the
# hash. If a field is missing in the hash, nil will be assigned to that field
# instead.
def initialize(params = {})
#user = params[:user]
#project_id = params[:project_id]
end
# Returns a string representing the entire Registration.
def inspect
"#{#user.inspect} - #{#user.country.inspect} - #{#project_id}"
end
# Returns a boolean valid representing whether the Registration instance is
# considered valid for the API or not. True if the instance is considered
# valid; otherwise false.
def is_valid?
return false if #user.nil? || #project_id.nil?
return false if !#user.is_a?(User) || !#project_id.is_a?(Fixnum)
return false if !#user.is_valid?
true
end
end
I had to implement the methods to generate the JSON output correctly. When I run this in console I get the following output generated:
irb(main):004:0> r = Registration.new(:user => u, :project_id => 1)
=> new_login - nil - 1
irb(main):005:0> r.to_json
=> "{\"json_class\":\"Registration\",\"data\":[\"{\\\"json_class\\\":\\\"User\\\
",\\\"login\\\":\\\"new_login\\\"}\",1]}"
Which looks like valid JSON to me. However when I POST this to the application server and try to parse this, JSON complains that at least 2 octets are needed and refuses to deserialize the object.
If you're using Sequel as your ORM, try something like this:
In your model:
class Registration < Sequel::Model
many_to_one :user
many_to_one :project
plugin :json_serializer
end
The server:
before do
#data = JSON.parse(request.body.read) rescue {}
end
post '/users' do
#registration = Registration.new #data
if #registration.valid?
#registration.save
#registration.to_json #return a JSON representation of the resource
else
status 422 #proper status code for invalid input
#registration.errors.to_json
end
end
I think you may be overcomplicating your registration process. If the HTTP action is POST /users then why not create a user? Seems like creating a registration is overly complex. Unless your user already exists, in which case POST /users would be incorrect. If what you're really intending to do is add a user to to a project, then you should PUT /projects/:project_id/users/:user_id and the action would look something like this:
class User < Sequel::Model
many_to_many :projects
end
class Project < Sequel::Model
many_to_many :users
end
#make sure your db schema has a table called users_projects or projects_users
put '/projects/:project_id/users/:user_id' do
#find the project
#project = Project.find params[:project_id]
raise Sinatra::NotFound unless #project
#find the user
#user = Project.find params[:project_id]
raise Sinatra::NotFound unless #user
#add user to project's users collection
#project.add_user #user
#send a new representation of the parent resource back to the client
#i like to include the child resources as well
#json might look something like this
#{ 'name' : 'a project name', 'users' : ['/users/:user_id', '/users/:another_user_id'] }
#project.to_json
end

Resources