Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update required field status #192

Closed
morgan opened this issue Apr 12, 2015 · 3 comments
Closed

Update required field status #192

morgan opened this issue Apr 12, 2015 · 3 comments

Comments

@morgan
Copy link

morgan commented Apr 12, 2015

Pretty normal operation, feel like I am possibly missing something. Have a schema for creation where fields are required in order to create the object. Then during edit (such as a PATCH operation), certain fields are no longer required. Such as updating a user that required a password at creation but doesn't require the password field for an update.

Currently, I'm doing something like this to solve the problem:

fields = ('first_name', 'last_name')
if 'password' in input:
    fields += ('password',)

result, errors = UserSchema(only=fields).load(input)

Feel there should be a more elegant way to modify the field itself. What are your recommendations for handling this?

@sloria
Copy link
Member

sloria commented May 6, 2015

@morgan If you're using a framework with a thread-local request object, you could do something like:

from flask import request
from marshmallow import missing, Schema, fields, ValidationError

def required_on_post(val):
    if request.method == 'POST':
        if val is missing:
            raise ValidationError('Field is required')

class UserSchema(Schema):
    password = fields.Str(validate=required_on_post, load_only=True)

Of course, this can be generalized with a validator class like RequiredForMethods.

@sloria
Copy link
Member

sloria commented Sep 18, 2015

Also see #272 for a similar question and solution.

Closing this for now.

@sloria sloria closed this as completed Sep 18, 2015
@gw
Copy link

gw commented Jun 7, 2016

Hey @sloria ! Grateful Marshmallow user here--just wanted to update this issue as I recently came across it in Google search results.

This particular solution will not work in 2.7.3 because Field instance validators (i.e. those passed via the validate kwarg to a Field instance) will not get called if the field is not represented in the data to load.

To the other forsaken souls finding this issue: use partial (PR, docs).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants