2

I am making an E commerce site, I want to store Cart elements in an integer Array Field. I am using PostGreSql as my database. I have created model for cart by extending Django User model. Here is my models

class UserCart(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    user_product=models.IntegerField(blank=True, null=True)
    cart_products = ArrayField(
        models.IntegerField(blank=True),
        default = list
    )

User.profile = property(lambda u:UserCart.objects.get_or_create(user=u)[0])

Below is my Form.py. I have created only basic form from django import forms from .models import UserCart from django.db import models from django.contrib.postgres.fields import ArrayField

class UserCartForm (forms.ModelForm):

    class Meta:
        model= UserCart
        fields = ('user_product',)

I have searched alot on internet but was unable to find the relevant answer.I want that whenever user clicks on Add to Cart button, that product_id gets stored in cart_products array.I read somewhere that ArrayFields behave as list in Django, so here is my views.py

@login_required
def user_cart(request):
    if request.method=='POST':
        form=UserCartForm(request.POST , instance=request.user.profile)
        if form.is_valid():
            post = form.save(commit=False)
            post.cart_products.append(99)
            post.save()
            return HttpResponseRedirect('/user_login/loggedin')
        else:
            HttpResponse("Error")
    else:
        user=request.user
        profile=user.profile
        form= UserCartForm(instance=profile)
        args={}
        args.update(csrf(request))
        args['form']=form
        return render_to_response('cartapi.html' ,args)

Its giving me Error that

 AttributeError at /cart/ac/
 'NoneType' object has no attribute 'append'
 Request Method:    POST
 Request URL:   http://localhost:8000/cart/ac/
 Django Version:    1.11.2
 Exception Type:    AttributeError
 Exception Value:   
 'NoneType' object has no attribute 'append'
 Exception Location:    C:\Users\Muhammad                
 Jawad\AppData\Local\Programs\Python\Python36-32\mysite\cart\views.py in 
 user_cart, line 19
 Python Executable: C:\Users\Muhammad 
 Jawad\AppData\Local\Programs\Python\Python36-32\python.exe

And if i save cart_products this way

 post.cart_products=99

Then it throws this error

 column "cart_products" is of type int4range but expression is of type integer
 LINE 1: ...er_id" = 1, "user_cart" = 3000, "cart_products" = 99 WHERE "...
                                                         ^
 HINT:  You will need to rewrite or cast the expression.
 Request Method:    POST
 Request URL:   http://localhost:8000/cart/ac/
 Django Version:    1.11.2
 Exception Type:    ProgrammingError
 Exception Value:   
 column "cart_products" is of type int4range but expression is of type integer
 LINE 1: ...er_id" = 1, "user_cart" = 3000, "cart_products" = 99 WHERE "...
                                                         ^
 HINT:  You will need to rewrite or cast the expression.

Kindly Help me in this matter.Summarizing my Question: How can i get user_product as id and save it in cart_products

2
  • Can you append values in cart_products in terminal ? Commented Aug 26, 2017 at 7:51
  • Yes , I have tried, is giving the same error Commented Aug 26, 2017 at 14:10

4 Answers 4

0

change yor views like this

views.py

@login_required
def user_cart(request):
    if request.method=='POST':
        form=UserCartForm(request.POST , instance=request.user.profile)
        if form.is_valid():
            post = form.save(commit=False)
            if post.cart_products:
                post.cart_products.append(99)
            else:
                post.cart_products = [99]
            post.save()
            return HttpResponseRedirect('/user_login/loggedin')
        else:
            HttpResponse("Error")
    else:
        user=request.user
        profile=user.profile
        form= UserCartForm(instance=profile)
        args={}
        args.update(csrf(request))
        args['form']=form
        return render_to_response('cartapi.html' ,args)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks For Answer but It is giving me Error that column "cart_products" is of type int4range but expression is of type integer[] LINE 1: ...er_id" = 1, "user_cart" = 3000, "cart_products" = ARRAY[99] ... ^ HINT: You will need to rewrite or cast the expression.
0

Your database is messed up. Drop it and remigrate (or craft a custom migration if you have data to preserve: basically, you just have to expand existing ranges into the full array).

See https://docs.djangoproject.com/en/2.1/_modules/django/contrib/postgres/fields/ranges/#IntegerRangeField

The int4range is the db type associated with the IntegerRangeField. This indicates either problem with your migrations (try running ./manage.py makemigrations) or that your database is out-of-sync with your DB (try running ./manage.py migrate).

It's hard to say what exactly the problem is without looking at your migrations and the current table definition in the database, but this should get you started.

Comments

0

keyword_from_user="My name is John Doe" I have Django 3.1.7 and this method has worked for me.

models.py


class Keys(models.Model):
    keys = ArrayField(models.CharField(max_length=50, blank=True),size=5,blank=True)
    docfile = models.FileField(upload_to='documents/%Y/%m/%d', blank=True, null=True)
   

views.py create object

new_document_object = Keys.objects.create(keys= keyword_from_user.split(), docfile =file)

views.py create object

new_document_object = Keys.objects.create(keys= keyword_from_user.split(), docfile =file)

views.py update object

keys = Keys.objects.get(id=id_from_user)
keys.keys=user_data['keyword_update_list']
keys.save()

Comments

0

You can save your cart_products into a python list then modify that list using the append method. Thereafter, you can save the new value of the list into the ArrayField

@login_required
def user_cart(request):
    if request.method=='POST':
        form=UserCartForm(request.POST , instance=request.user.profile)
        if form.is_valid():
            post = form.save(commit=False)
            # copy the existing cart_products to a temp variable
            temp_cart = post.cart_products
            # append your new product code to the temp_cart
            temp_cart.append(99)
            # save the new value of temp_cart to the cart_products field
            post.cart_products = temp_cart
            # save the post
            post.save()
            return HttpResponseRedirect('/user_login/loggedin')
        else:
            HttpResponse("Error")
    else:
        user=request.user
        profile=user.profile
        form= UserCartForm(instance=profile)
        args={}
        args.update(csrf(request))
        args['form']=form
        return render_to_response('cartapi.html' ,args)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.