0

I use a generic CreateView to let logged in users (Creator) add objects of the model Piece. Since creating a Piece is done by the Creator (logged in user) there is no need for the CreateView to either show or manipulate the 'creator' field. Hence I wish to not show it and set it to the logged in user. However, approaches such as overwriting form_valid or using get_form_kwargs seem not to get it done. Using the form_valid method gives a ValueError:

Cannot assign "<SimpleLazyObject: <User: patrick1>>": "Piece.creator" must be a "Creator" instance.

The solution seems to be just around the corner, I hope.

Tried but did not work: form_valid method, form_valid method, get_form_kwargs method

My code:

models.py

class Piece(models.Model):
    creator = models.ForeignKey('Creator', on_delete=models.SET_NULL, null=True)
    title = models.CharField(max_length=200)
    summary = models.TextField(max_length=1000, help_text='Enter a brief description of the Piece')
    created = models.DateField(null=True, blank=True)
    ...

from django.contrib.auth.models import User
class Creator(models.Model):
    ...
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    ...

views.py

class PieceCreate(LoginRequiredMixin, CreateView):
    model = Piece
    fields = ['title', 'summary', 'created']
    initial = {'created': datetime.date.today()}

    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.creator = self.request.user
        return super(PieceCreate, self).form_valid(form)

    success_url = reverse_lazy('pieces')

Any suggestions are highly appreciated!

Aaron Scheib
  • 358
  • 4
  • 18

1 Answers1

1
obj.creator = Creator.objects.get(user=self.request.user)

or any other solution that will give you Creator instance for current user instead of User. Just as the error message says.

Cannot assign "User: patrick1": "Piece.creator" must be a "Creator" instance.

Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39