django-formsgraphene-django

Add user to model before saving with DjangoModelFormMutation


I have a Django Log model which has many-to-one with a User

from django.db import models

class Log(models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    ...

I have a Django form for the Log

from django.forms import ModelForm

class LogForm(ModelForm):
    class Meta:
        model = Log
        exclude = ("user",)

I have a graphene-django mutation to enable Log creation

import graphene
from graphene_django import DjangoObjectType
from graphene_django.forms.mutation import DjangoModelFormMutation

class LogType(DjangoObjectType):
    class Meta:
        model = Log
        fields = "__all__"

class CreateLogMutation(DjangoModelFormMutation):
    log = graphene.Field(LogType)

    class Meta:
        form_class = LogForm

How do I set Log.user to the current user before saving? With Django class-based views you would do as follows:

from django.views.generic import CreateView

class LogCreateView(CreateView):
    model = Log
    form_class = LogForm

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

How is this achieved with graphene-django?


Solution

  • Override perform_mutate and add the user there. pefrom_mutate is called after Django's Form.is_valid.

    class CreateLogMutation(DjangoModelFormMutation):
        log = graphene.Field(LogType)
    
        class Meta:
            form_class = LogForm
    
        @classmethod
        def perform_mutate(cls, form, info):
            form.instance.user = info.context.user
            return super().perform_mutate(form, info)