get current user for 'created_by' field in model class
Refer official doc. It explained it pretty well. An example is also there
from django.views.generic.edit import CreateView
from myapp.models import Author
class AuthorCreate(CreateView):
model = Author
fields = ['name']
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-editing/#models-and-request-user
If anyone encounters this problem I followed the advice of a_k_v and did it in views. Here is how I did it :
I added two fields in my class :
class Class(models.Model):
created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='create')
updated_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True, null=True, related_name='update')
then created a function :
def created_updated(model, request):
obj = model.objects.latest('pk')
if obj.created_by is None:
obj.created_by = request.user
obj.updated_by = request.user
obj.save()
to get it into my views.py :
if request.method == 'POST':
form = AddVacation(request.POST)
if form.is_valid:
form.save()
created_updated(Vacation, request)