A
A
Andrey Kirdyashkin2020-11-19 11:01:08
Django
Andrey Kirdyashkin, 2020-11-19 11:01:08

How to enter the username of the user who added the record to the database?

models.py

from django.db import models
import datetime
from django.utils import timezone
import getpass

# Create your models here.
class factory(models.Model):
    factory_city = models.CharField('Город', max_length=30)
    factory_name = models.CharField('Наименование организации', max_length=50)
    factory_tin = models.CharField('ИНН', max_length=12)
    factory_equipment = models.CharField('Оборудование', max_length=50)
    factory_dealer = models.CharField(default=(getpass.getuser()), max_length=50)
    factory_createdate = models.CharField(default=(timezone.localtime(timezone.now()).strftime('%d.%m%.%Y')), max_length=50)

    def __str__(self):
        return self.factory_name

    class Meta:
        verbose_name = 'Организация'
        verbose_name_plural = 'Организации'


I can’t figure out how to enter the username into the model (in the template engine everything is OK through {{username}}, but it doesn’t need to be displayed in the template), and the model is even trouble

Entered through getpass.getuser() gives only the admin login when you add an entry a regular user, the admin name is displayed in the database

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-11-19
@ANDYNEI

1. it is customary to make the name of the class capitalized, Factory, not factory
2. factory_ are superfluous in the name of the model fields, it is better to just remove them
3. for the date, use the DateField type, it has a special parameter auto_now_add, so as not to fence the collective farm with default
4. dealer in default, you need to pass a link to the function, and not its call, then it will be called with each addition (and then there will most likely be a user running django), and not once, when importing the code, as it is now. It's better to use the built-in auth system, and get the current user via request.user.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question