D
D
darkglare2020-11-27 20:08:42
Django
darkglare, 2020-11-27 20:08:42

How to fix int() error?

How to fix int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' error?

views.py

from .models import Order
from .forms import OrderCreateForm
from cart.cart import Cart
from django.shortcuts import render, get_object_or_404,redirect
from shop.models import Product

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.nickname = request.user
            order.product = Product.objects.get(id=id)         
            order.save()
            for item in cart:
                Order.objects.create(
                                         product=item['product'],
                                         price=item['price'],
                                         quantity=item['quantity'])
            # очистка корзины
            cart.clear()
            return render(request, 'orders/order/created.html',
                          {'order': order})
    else:
        form = OrderCreateForm
    return render(request, 'orders/order/create.html',
                  {'cart': cart, 'form': form, })


Error in the line
order.product = Product.objects.get(id=id)
In general, this function passes the name of the authorized user and the name of the product to the checkout form. Here is the name of the product can not be conveyed.

models.py

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

class Order(models.Model):

   
    product = models.ForeignKey(Product, related_name='order_items',on_delete=models.CASCADE, default=False)
    price = models.DecimalField(max_digits=10, decimal_places=2, default=False)
    quantity = models.PositiveIntegerField(default=1)
    
    nickname = models.ForeignKey(User, on_delete=models.CASCADE, default=False)

    email = models.EmailField()
    postal_code = models.CharField(max_length=20)
    city = models.CharField(max_length=100)
    street = models.CharField(max_length=100, default="s")
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    paid = models.BooleanField(default=False)

    class Meta:
        ordering = ('-created',)
        verbose_name = 'Заказ'
        verbose_name_plural = 'Заказы'

    def __str__(self):
        return 'Order {}'.format(self.id)

    def get_total_cost(self):
        return sum(item.get_cost() for item in self.items.all())


models.py (product model)

Product Model
class Product(models.Model):
    #ОБЩИЕ ХАРАКТЕРИСТИКИ 
    category = models.ForeignKey(Category, related_name='products')
    name = models.CharField(max_length=200, db_index=True, verbose_name="Название")
    slug = models.SlugField(max_length=200, db_index=True)
    image1 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, verbose_name = "Картинка_1")
    image2 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, verbose_name = "Картинка_2")
    image3 = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, verbose_name = "Картинка_3")


    case_type = models.CharField (max_length = 255 ,default = False, verbose_name = "Тип корпуса")
    duo_sim = models.BooleanField (default = True, verbose_name = "Поддержка двух сим карт")
    sim_type = models.CharField(max_length=255, default="input", verbose_name = "Тип SIM-карты")
    system= models.CharField(max_length = 100, default = "system", verbose_name = "Операционная система")

    #ДИСПЛЕЙ

    display_type = models.CharField(max_length = 10, default = False, verbose_name = "Тип экрана")
    resolution = models.CharField(max_length = 20,default = False , verbose_name = "Разрешение экрана")

    #КОНФИГУРАЦИЯ
    processor = models.CharField(max_length = 255, default = False, verbose_name = "Процессор")
    gpu = models.CharField(max_length = 255, default = False, verbose_name = "Графический ускроритель")
    cores = models.CharField(max_length = 5, default = False, verbose_name = "Кол-во ядер")
    cpu_frequency = models.CharField(max_length = 5,  verbose_name= "Частота процессора")
    ram = models.CharField(max_length=255, verbose_name='Объем оперативной памяти')
    ram_inside = models.CharField(max_length = 255,  verbose_name = "Объем встроенной памяти")
    sd = models.BooleanField(default=True, verbose_name='Наличие SD карты')
    sd_volume_max = models.CharField(max_length=255, blank=True, null=True, verbose_name='Максимальный объем SD карты')

    #КАМЕРА
    main_cam_mp = models.CharField(max_length=255, verbose_name='Основная камера')
    frontal_cam_mp = models.CharField(max_length=255, verbose_name='Фронтальная камера')
    flash = models.BooleanField(default=True, verbose_name = "Вспышка")

    #МУЛЬТИМЕДИА

    mp3_pleer = models.BooleanField(default=True, verbose_name="MP3 плеер")
    recorder = models.BooleanField(default=True, verbose_name="Диктофон")
    usb_interface = models.CharField (max_length = 255, verbose_name = "Интерфейс USB")

    #ПИТАНИЕ

    accum_volume = models.CharField(max_length=255, verbose_name='Объем батареи мА*ч ')
    
   
    #КОПРУС

    size = models.CharField(max_length=255, verbose_name = "Размеры (ШхВхТ)")
    weigth = models.CharField(max_length = 10, verbose_name = "Вес г.")
    
    description = models.TextField(blank=True)
    country = models.CharField(max_length= 255, verbose_name = "Страна производителя")
    warranty  = models.CharField(max_length= 255, verbose_name = "Гарантия")
    price = models.DecimalField(max_digits=10, decimal_places=2)
    stock = models.PositiveIntegerField()
    available = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('name',)
        index_together = (('id', 'slug'),)

    def get_absolute_url(self):
        return reverse('shop:product_detail',
                        args=[self.id, self.slug])

    def __str__(self):
        return self.name


admin.site.register(Product)


5fc131e9bec2f816343981.jpeg

Please tell me what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2020-11-27
@darkglare

order_createThere are no variables named in the scope of the function , so a reference to the built-in function idid is passed as an argument in the string , and the method expects a number. order.product = Product.objects.get(id=id)get

D
Dr. Bacon, 2020-11-27
@bacon

Please tell me what am I doing wrong?
you do not show us a normal traceback, so that you could understand something about the error. Well, I would also translate the text of the error, what to understand what it is about.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question