-1

I'm new to django so sorry for this simple question. I'm building web app using django. and i want to save current logged in user while he/she create any new object automatically. I want to implement this features in custom admin panel.

class Post(models.Model):
   user = models.ForeginKey(...)
   .............

So here i want to fill user field automatically.

1 Answers1

1

You can reference the user model directly.

from django.contrib.auth.models import User
from django.db import models

class Post(models.Model):
    user = models.ForeginKey(User, on_delete=models.CASCADE)

Or you can use the AUTH_USER_MODEL setting (this is recommended)

from django.conf import settings
from django.db import models

class Post(models.Model):
    user = models.ForeginKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

Inside your generic create view you can then associate the request.user with the object inside the form_valid method as explained here Accessing request.user in class based generic view CreateView in order to set FK field in Django

class PostView(CreateView):

    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.user = self.request.user
        obj.save()        
        return http.HttpResponseRedirect(self.get_success_url())
LonnyT
  • 590
  • 1
  • 8
  • 21