0

I'v been trying to figure out a way to auto fill a field, i want the user logged in to fill the Created_by field when a new Event is made. Below is my original code that works

created_by = models.ForeignKey(
    settings.AUTH_USER_MODEL,
    verbose_name=_('Created by'),
    related_name='events',
    blank=False, null=False,
    default='',
)

I have tried to import the User and put this into the field but...

from django.contrib.auth.models import User
created_by = models.ForeignKey(
    settings.AUTH_USER_MODEL,
    User,
    verbose_name=_('Created by'),
    related_name='events',
    blank=False, null=False,
    default='',
)

Depending on where i put "User" i get different errors as show above if i put the User after the "settings.Auth_USER_MODEL" i get this error:

User has no field named <class 'django.contrib.auth.models.User'>

If i put it before the "settings.Auth_USER_MODEL" i get this error:

User has no field named 'auth.User'

The field is within

class Event(EventModelMixin):

Would this have anything to do with why i am having these problems?

I'm using django 1.8,

So now i understand i can't do it from a model view, im currently trying to edit the views and i have wrote a section of code:

class EventCreateView(CreateView):
    form_class = CreateEvent
    model = Event

    def form_valid(self, form):
        Event = form.save(commit=False)
        Event.created_by = User
        Event.save()
        return HttpResponseRedirect(self.get_success_url())

but i get this error that i can't understand for the life of me.

Cannot assign "<class 'django.contrib.auth.models.User'>": "Event.created_by" must be a "User" instance.
All Day
  • 147
  • 12
  • 1
    You cannot add stuff to the field definition to somehow make it auto-populate the current user. Instead you need to do that logic in the view - see http://stackoverflow.com/questions/21743050/get-the-currently-logged-in-django-user-in-a-models-py-file and http://stackoverflow.com/questions/10991460/django-get-current-user-in-model-save – solarissmoke Aug 03 '16 at 09:43
  • You might want to use django-audit-log (http://django-audit-log.readthedocs.io/en/latest/change_tracking.html) AuthStampedModel and inherit in your model. It's useful if you would like to have this field in more than one model. On side not, it could be little heavy if you are not using other functionality from this module. – Nikhil N Aug 03 '16 at 10:00

0 Answers0