Tengo un modelo que se llama dispositivo, este crea el folio y el nombre y adicional quiero almacenar el id del usuario que está logueado. Esta es mi clase:
class RegistroDispositivo(CreateView):
model = Device
template_name = 'registroDispositivo.html'
form_class = RegistroDevice
success_url = reverse_lazy('login')
def post(self, request, *args,**kwargs):
usuario = request.user
if usuario:
user_id = User.objects.get(email=usuario)
form = self.form_class(initial={'user_id':user_id})
return HttpResponseRedirect(self.get_success_url())
else:
form = self.form_class()
return super(RegistroDispositivo, self).post(form)
Mi models.py incluye un abstractBaseUser para otras funcionalidades adicionales al user de Django
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields)
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
is_active = models.BooleanField(_('active'), default=True)
is_staff = models.BooleanField(default=False)
nombreEmpresa = models.CharField(max_length=100, blank=True)
USERNAME_FIELD = 'email'
objects = UserManager()
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
class Device(models.Model):
folio = models.CharField(max_length=15, unique=True)
deviceName = models.CharField(max_length=50, unique=True)
usuario = models.ForeignKey(User)