django-usersdjango-request

How to Save Currently Logged in User to Model in Django


I am trying to get the currently logged in User and save it to a model. I am getting the following error

"Cannot assign "<SimpleLazyObject: <User: rsomani005>>": "process_master.user" must be a "User" instance"

I am using Django's built in user model.

My model looks like this -

class User(auth.models.User,auth.models.PermissionsMixin):
    def __str__(self):
        return "@{}".format(self.username)

class plan_master(models.Model):
    plan_name = models.CharField(max_length=256)
    plan_description = models.CharField(max_length=256)
    plan_price = models.FloatField()
    plan_active_status = models.BooleanField(default=True)
    plan_credits = models.IntegerField(default=0)
    registration_type_name = models.CharField(max_length=50)

My view file looks like this -

class FileFieldView(LoginRequiredMixin,FormView):
    form_class = FileFieldForm
    template_name = 'merge_ops/merge_ops.html' 
    success_url = reverse_lazy('merge_ops:file_setup') 

    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        files = request.FILES.getlist('file_field')

        if form.is_valid():
            for f in files:
                fs = FileSystemStorage()
                fs.save(f.name,f)
            obj = process_master()
            user = request.user
            obj.user = user
            obj.process_date = datetime.now()
            obj.number_of_workbooks = len(files)
            obj.save()
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

Solution

  • An easy way to get the logged user in one of your views is:

    user = request.user
    

    but that is usually when the user model that you have created is something like that in the model.py:

    from django.contrib.auth.models import AbstractUser
    from django.db import models
    
    
    class User(AbstractUser):
        pass
    

    I would suggest using this one to register users because it is automatic and complete.

    and from there use the object for what you need. You can pass it on as a context or source model objects from it.