Home > Software design >  How to save from html select to sql in django
How to save from html select to sql in django

Time:04-18

I want to save from HTML select to SQL but "Cannot assign "'27'": "UserProduct.category" must be a "Category" instance." I get an error. What am I doing wrong?

sell.html

<div >
        <p>Yerləşdirdiyiniz məhsul "İkinci əl məhsullar" kateqoriyasında görünəcək.</p>
        <select  name="up_category">
            <option value="0">Kateqoriya seç</option>
            {% for category in category %}
                {% if category.active %}
                    {% if category.parent_id %}
                        <option value="{{category.id}}">{{category.name}}</option>
                    {% else %}
                        <option value="{{category.id}}" style="font-weight: bold;">{{category.name}}</option>
                    {% endif %}
                {% endif %}
            {% endfor %}
        </select>
    </div>

views.py

def sell(request):
category = Category.objects.all()
context = {'category': category}
if request.POST:
    product_name = request.POST.get('product_name')
    up_category = request.POST.get('up_category')
    keywords = request.POST.get('keywords')
    descriptions = request.POST.get('descriptions')
    main_image = request.POST.get('main_image')
    price = request.POST.get('price')
    detail = request.POST.get('detail')
    image1 = request.POST.get('image1')
    image2 = request.POST.get('image2')
    image3 = request.POST.get('image3')
    if product_name == '' or up_category == 'Kateqoriya seç' or keywords == '' or descriptions == '' or price == '' or price == str or detail == '':
        messages.warning(request, 'Bütün xanaları doldurduğunuzdan əmin olun!')
    else:
        newUserProduct = UserProduct(user=request.user,
                                     name=product_name,
                                     category=up_category,
                                     keywords=keywords,
                                     descriptions=descriptions,
                                     detail=detail,
                                     main_image=main_image,
                                     image1 = image1,
                                     image2 = image2,
                                     image3 =image3
                                     )
        newUserProduct.save()
        messages.warning(request, 'Məhsulunuz satışa çıxdı.')
        return render(request, 'forms/sell.html', context)
return render(request, 'forms/sell.html', context)

models.py

class UserProduct(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=False)
name = models.CharField(max_length=100)
category = models.ForeignKey(Category, on_delete=models.DO_NOTHING)
main_image = models.ImageField(upload_to='static/product_images/%Y/%m/%d/')
detail = models.TextField()
keywords = models.CharField(max_length=50)
description = models.CharField(max_length=1000)
price = models.FloatField()
sale = models.IntegerField(blank=True, null=True, verbose_name="Sale (%)")
image1 = models.ImageField(upload_to='static/product_images/%Y/%m/%d/', blank=True, null=True)
image2 = models.ImageField(upload_to='static/product_images/%Y/%m/%d/', blank=True, null=True)
image3 = models.ImageField(upload_to='static/product_images/%Y/%m/%d/', blank=True, null=True)
date_created = models.DateTimeField(auto_now_add=True)

I want to save from HTML select to SQL but "Cannot assign "'27'": "UserProduct.category" must be a "Category" instance." I get an error. What am I doing wrong?

CodePudding user response:

In your UserProduct class, the field category is a ForeignKey to the Category class. Try getting the Category first from your request.POST, then adding it:

def sell(request):
    category = Category.objects.all()
    context = {'category': category}
    if request.POST:
        product_name = request.POST.get('product_name')
        up_category = request.POST.get('up_category')
        keywords = request.POST.get('keywords')
        descriptions = request.POST.get('descriptions')
        main_image = request.POST.get('main_image')
        price = request.POST.get('price')
        detail = request.POST.get('detail')
        image1 = request.POST.get('image1')
        image2 = request.POST.get('image2')
        image3 = request.POST.get('image3')
        if product_name == '' or up_category == 'Kateqoriya seç' or keywords == '' or descriptions == '' or price == '' or price == str or detail == '':
            messages.warning(request, 'Bütün xanaları doldurduğunuzdan əmin olun!')
        else:
            cat = Category.objects.get(pk=up_category)    # CHANGED
            newUserProduct = UserProduct(user=request.user,
                                     name=product_name,
                                     category=cat,    # CHANGED
                                     keywords=keywords,
                                     descriptions=descriptions,
                                     detail=detail,
                                     main_image=main_image,
                                     image1 = image1,
                                     image2 = image2,
                                     image3 =image3
                                     )
        newUserProduct.save()
        messages.warning(request, 'Məhsulunuz satışa çıxdı.')
        return render(request, 'forms/sell.html', context)
    return render(request, 'forms/sell.html', context)
  • Related