M
M
Maxim Zubenko2018-11-09 15:29:37
Django
Maxim Zubenko, 2018-11-09 15:29:37

How to get current user in Django 2 model?

Let's say there are two models Product and Log
Product with the usual fields: category, name, price, and so on.
log like this:

LOG_EVENT_CHOICES = (
    ('added_qty', 'Добавлено количество'),
    ('changed_qty', 'Изменено количество'),
    ('changed_price', 'Изменена цена'),
)

class Log(models.Model):
    product = models.ForeignKey(Product, on_delete=models.PROTECT, verbose_name="Изделие")
    event = models.CharField(max_length=30, choices=LOG_EVENT_CHOICES, default='added_qty', verbose_name="Событие")
    description = models.CharField(max_length=100, blank=True)
    created = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Дата создания")
    staff = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name="Инициатор")
    qty = models.IntegerField(default=0, verbose_name="Количество")

And then someone on the product changes the price. To catch this moment, I override the save() method in the Product model:
def save(self, *args, **kwargs):
        
        if self.id: # сразу будет отсекать новые записи у которых ещё нет id
            # запись события смены цены
            orig_price = float(Product.objects.get(id=self.id).price)
            if orig_price != float(self.price):
                log = Log()
                log.product = self
                log.event = 'changed_price'
                log.description = 'old: ' + str(orig_price) + ' , new: ' + str(self.price)
                log.qty = self.qty
                log.staff = КАК СЮДА ПОЛУЧИТЬ ТЕКУЩЕГО ЮЗЕРА???
                log.save()

How to write the current user to the log.staff variable?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yura Khlyan, 2018-11-09
@MAGistr_MTM

Transfer the price change logging logic to the view from the model

def product_edit_view(request, id):
    product = Product.objects.get(id=id)
    form = ProductForm(request.POST or None, request.FILES or None, instance=product)
    if form.is_valid():
        if product.price != form.cleaned_data['price']:
                log = Log()
                log.product = product
                log.event = 'changed_price'
                log.description = 'old: ' + str(product.price) + ' , new: ' + str(form.cleaned_data['price'])
                log.qty = product.qty
                log.staff = request.user
                log.save()
        form.save()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question