M
M
Mikhail Bolev2021-03-26 18:57:39
Django
Mikhail Bolev, 2021-03-26 18:57:39

How to enter the current user in the model field?

I'm trying to add the current user to the Order model (order.user = request.user). I am getting an error. The fact is that I have created a custom model for users. How to do it better?

Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x000001DE65B696D0>>": "Order.user" must be a "CustomUser" instance.


model
class Order(models.Model):

    STATUS = [
        (None, 'Статусы'), 
        ('a', 'новый'),
        ('b', 'в обработке'),
        ('с', 'согласован'),
        ('d', 'ожидает оплаты'),
        ('e', 'ожидает товар'),
        ('f', 'собран'),
        ('g', 'отправлен'),
        ('h', 'доставлен'),
        ('i', 'в ожидании оплаты'),
        ('k', 'оплачен'),
        ('l', 'отменен'),
    ]

    first_name = models.CharField(max_length=50, verbose_name='Имя')
    last_name = models.CharField(max_length=50, verbose_name='Фамилия')
    email = models.EmailField(verbose_name='Эл. почта')
    address = models.CharField(max_length=250, verbose_name='Адрес')
    postal_code = models.CharField(max_length=20, verbose_name='Почтовый индекс')
    city = models.CharField(max_length=100, verbose_name='Город')
    created = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания')
    updated = models.DateTimeField(auto_now=True, verbose_name='Дата изменения')
    paid = models.BooleanField(default=False, verbose_name='Оплачен')
    status =  models.CharField(max_length=1, choices=STATUS, verbose_name='Статус')
    coupon = models.ForeignKey(Coupon, on_delete=models.CASCADE, related_name='orders', null=True, blank=True)
    discount = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(100)])
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, related_name='orders')
    product = models.ManyToManyField(Product)


custom model
class CustomUser(AbstractUser):
    pass


performance
def order_create(request):
    cart = Cart(request)
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            order = form.save(commit=False)
            order.user = request.user #здесь возникает ошибка
            if cart.coupon:
                order.coupon = cart.coupon
                order.discount = cart.coupon.discount
            order.save()
            for item in cart:
                OrderItem.objects.create(order=order,
                                         product=item['product'],
                                         price=item['price'],
                                         quantity=item['quantity'])
                                         
                print(OrderItem)            # очистка корзины
            cart.clear()
            order_created(order.id)
            # запуск асинхронной задачи
            # order_created.delay(order.id)
            return render(request, 'orders/order/created.html',
                          {'order': order})
    else:
        form = OrderCreateForm
    return render(request, 'orders/order/create.html',
                  {'cart': cart, 'form': form})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-03-26
@Scorpion_MB

if request.user.is_authenticated:
    order.user = request.user

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question