question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Django: Map Form to Mutation

See original GitHub issue

Currently it’s possible to map Django models to ObjectTypes using DjangoNode. I think it would be nice to have a similar feature that allows mapping forms to Mutation with a DjangoMutation class.

This would provide several great improvements:

  • No need to duplicate form fields in Input classes anymore.
  • There would be a simple and obvious way to handle validation.
  • The code could map form.errors to info.context.errors (It took a while until I figured out how to do that) on it’s own.

In the simple case you’d only have to define the outputs and a method that takes the validated data and returns an instance of the mutation class. I believe that even that would be unnecessary, if you’re working with ModelForms. In that case a default method could just save the form and return the model instance wrapped in the corresponding DjangoNode.

Code that gets us some of the way to such a class already appears to exist, which was written for the django-filter integration.

I’m not that familiar with the code base itself but I have read quite a bit of it and I’ think it might be able to implement this. I’m interested to know what you think of it and whether this has a chance to be accepted.

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:14
  • Comments:12 (6 by maintainers)

github_iconTop GitHub Comments

3reactions
johandccommented, May 4, 2017

Hi what is the status on this?

I need something like a UserInputType for a IntroduceUser mutation and i don’t want to manually map all the fields of the Django User model.

I would like if there would be a DjangoInputObjectType that could be created similar to the DjangoObjectType. Passing it through Django Forms is a brilliant solution to handling field validation, but being able to bypass validation would be appreciated for bulk data imports from a trusted system.

2reactions
gcheshkovcommented, May 27, 2016

@stefanfoulis ErrorType is simple graphene object type for representing errors:

class ErrorType(graphene.ObjectType):
    field = graphene.String()
    message = graphene.String()

However now I took different approach to error handling. Just raising ValidationError in mutation handler and adding error messages to errors object in overridden GraphQLView.format_error method:

def format_error(error):
    data = {
        'message': str(error),
    }

    if isinstance(error, GraphQLLocatedError):
        data.update(format_graphql_error(error))
        if isinstance(error.original_error, Exception):
            error = error.original_error
        else:
            return data

    if isinstance(error, APIException):
        if isinstance(error, ValidationError):
            data.update({
                'message': _('Validation error'),
                'code': 'validation_error',
                'fields': error.detail
            })
        else:
            if getattr(error, 'error_code', None):
                data['code'] = error.error_code

            if getattr(error, 'extra', None):
                data.update(error.extra)

    elif isinstance(error, DjangoPermissionDenied):
        data.update({
            'message': _('Permission denied'),
            'code': 'permission_denied'
        })

    elif isinstance(error, GraphQLError):
        pass

    elif isinstance(error, HttpError):
        pass

    else:
        data['code'] = 'unhandled_exception'
        if not settings.DEBUG:
            data['message'] = _('Server error')
        else:
            data['message'] = '{}: {}'.format(error.__class__.__name__, error)
            data['traceback'] = itertools.chain(
                *[[l for l in ll.split('\n') if l.strip() != '']
                  for ll in traceback.format_exception(
                        error.__class__, error, error.__traceback__)])

    return data

Read more comments on GitHub >

github_iconTop Results From Across the Web

Mutations - Graphene-Python
Graphene-Django comes with mutation classes that will convert the fields on Django forms into inputs on a mutation. DjangoFormMutation¶. from graphene_django.
Read more >
Forms So Painless a Baby Could Write 'em with Django's ...
Mutations and django-graphene's Model Form Mutations ... Here's a definition of a Profile form mapping to the Profile model that we defined ...
Read more >
how to make Mutation by graphene-django when there are no ...
i want to just save new data to Stock DB. I don't want to give data to web. below code show error "GetStockMutation...
Read more >
Working with forms - Django documentation
This document provides an introduction to the basics of web forms and how ... (A ModelForm maps a model class's fields to HTML...
Read more >
graphene-django-cud · PyPI
Create, update and delete mutations for graphene-django. ... auto_context_fields, Dict, None, A mapping of context values into model fields. See below.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found