Tuesday, December 1, 2015

Possible bug with forms and arrays? Multiple forms on one view and Array fields in Models ---: Django and Postgres

I get a strange error and I can't find the solution. The view is used to create data entries for a user but with an option to go back and edit hence the singular view to deal with an update...

The code works with only one form being pulled into the view but not with several, then it gives a nonsensical error. 

This is all in one app with its own set of urls.py

I have entered in the data raw for now in the form field rendered so eg interests : [1,2,3,4,5] in those fields
This worked as its should with no errors or abnormalities (data was updated in field)  but when i added skills through incremental development it shows this error:

 missing "]" in array dimensions
    LINE 1: ...akeProfile_skills" SET "user_id" = 11, "skills" =  '[0,1,2,3,..

I am using :
postgres1.9
Python3.4
Django 1.8.7

Code:

view.py 
    
    @login_required
    def step2(request):
    
    title =" Step 2 of 4 "
    # if request.method.upper() == 'POST':
    #     print('hello free stackoverflow points')

    #user_answer = UserAnswer.objects.get(user=request.user, question =instance)
    #profile, created = Profile.objects.get_or_create(user=request.user)
    form2p0 = step2p0Form()
    form2p1 = step2p1Form()
    form2p2 = step2p2Form()


    context ={
        "title":title,
        "form2p0":form2p0,
        "form2p1":form2p1,
        "form2p2":form2p2,

    }
    #skills, created = Skills.objects.get_or_create(user=request.user)
    if request.method.upper() == 'POST':

        interests, created = Interests.objects.get_or_create(user=request.user)
        skills, created = Skills.objects.get_or_create(user=request.user)
        languages, created = Languages.objects.get_or_create(user=request.user)

        form2p0 = step2p0Form(request.POST or None, instance= interests)
        form2p1 = step2p1Form(request.POST or None, instance= skills)
        form2p2 = step2p2Form(request.POST or None, instance= languages)

        context ={
            "title":title,
            "form2p0":form2p0,
            "form2p1":form2p1,
            "form2p2":form2p2,

        }

        if  form2p0.is_valid() and form2p1.is_valid() and form2p2.is_valid():

            instance2p0 =form2p0.save(commit=False)
            instance2p1 =form2p1.save(commit=False)
            instance2p2 =form2p2.save(commit=False)

            interests = form2p0.cleaned_data.get('interests')
            instance2p0.user = request.user
            instance2p0.interest = interests

            skills= form2p1.cleaned_data.get('skills')
            instance2p1.user = request.user
            instance2p1.skills = skills

            languages =  form2p2.cleaned_data.get('languages')
            instance2p2.languages = languages

            instance2p0.save()
            instance2p1.save()
            instance2p2.save()


            return HttpResponseRedirect(reverse('makeProfile:step3'))

    return render(request, "profile/step2.html", context)


form.py 

    class step2p0Form(forms.ModelForm):
        class Meta:
           model =Interests
           fields = ['interests']

        interests = forms.CharField(required = True)

    class step2p1Form(forms.ModelForm):
        class Meta:
            model =Skills
            fields = ['skills']

        skills = forms.CharField(required = True)

    class step2p2Form(forms.ModelForm):
        class Meta:
            model = Languages
            fields =['languages']

        languages = forms.CharField()

model.py

    class Skills(models.Model):

    user = models.OneToOneField(User,primary_key=True)
    #skills = models.CharField(max_length = 128, null=True, blank=True)
    skills =  ArrayField(models.IntegerField( null=True, blank=True, default = -1 ))


    class Interests(models.Model):

    user = models.OneToOneField(User,primary_key=True)
    #interests = models.CharField(max_length = 128, null=True, blank=True)
    interests =  ArrayField(models.IntegerField( null=True, blank=True, default = -1))


  
    
    class Languages(models.Model):

    user = models.OneToOneField(User,primary_key=True)

    languages =  ArrayField(models.CharField(max_length=50,blank=True,default="None"))



    #*******************SIGNALS***********************


    @receiver(post_save, sender=settings.AUTH_USER_MODEL)
    def create_profile_handler(sender, instance, created, **kwargs):
    
    if not created:
       print("hello#########")
       return

    profile = Profile(user=instance)
    interests = Interests(user=instance)
    skills= Skills(user=instance)
    languages = Languages(user=instance)

    interests.interests = [0]
    skills.skills = [0]
    languages.languages = ["None"]

    skills.save()
    interests.save()
    languages.save()
    profile.save()



    DataError at /makeProfile/step2/
    missing "]" in array dimensions
    LINE 1: ...akeProfile_skills" SET "user_id" = 11, "skills" =  '[0,1,2,3,...
                                                             ^
    Request Method: POST
    Request URL: http://127.0.0.1:8888/makeProfile/step2/
    Django Version: 1.8.7
    Exception Type: DataError
    Exception Value:
    missing "]" in array dimensions
    LINE 1: ...akeProfile_skills" SET "user_id" = 11, "skills" =  '[0,1,2,3,...
                                                             ^
    Exception Location: /home/g4/django/pureRu/lib/python3.4/site-p   ackages/django/db/backends/utils.py in execute, line 64
    Python Executable: /home/g4/django/pureRu/bin/python
    Python Version: 3.4.3
    Python Path:
    ['/home/g4/django/pureRu/src',
    '/home/g4/django/pureRu/lib/python3.4',
    '/home/g4/django/pureRu/lib/python3.4/plat-x86_64-linux-gnu',
    '/home/g4/django/pureRu/lib/python3.4/lib-dynload',
    '/usr/lib/python3.4',
    '/usr/lib/python3.4/plat-x86_64-linux-gnu',
    '/home/g4/django/pureRu/lib/python3.4/site-packages']
    Server time: Fri, 27 Nov 2015 18:42:54 +0000

TrackBack:

    Environment:


    Request Method: POST
    Request URL: http://127.0.0.1:8888/makeProfile/step2/

    Django Version: 1.8.7
    Python Version: 3.4.3
    Installed Applications:
    ('django.contrib.auth',
    'django.contrib.admin',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'crispy_forms',
    'registration',
    'newsletter',
    'questions',
    'makeProfile')
    Installed Middleware:
    ('django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware')


Traceback:

        File "/home/g4/django/pureRu/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
          132.                     response = wrapped_callback(request,   *callback_args, **callback_kwargs)
        File "/home/g4/django/pureRu/lib/python3.4/site-  packages/django/contrib/auth/decorators.py" in _wrapped_view
          22.                 return view_func(request, *args, **kwargs)
         File "/home/g4/django/pureRu/src/makeProfile/views.py" in step2
          111.             instance2p1.save()
        File "/home/g4/django/pureRu/lib/python3.4/site-  packages/django/db/models/base.py" in save
          734.                        force_update=force_update,   update_fields=update_fields)
         File "/home/g4/django/pureRu/lib/python3.4/site-packages/django/db/models/base.py" in save_base
          762.             updated = self._save_table(raw, cls, force_insert,  force_update, using, update_fields)
        File "/home/g4/django/pureRu/lib/python3.4/site- packages/django/db/models/base.py" in _save_table
          827.                                       forced_update)
          File "/home/g4/django/pureRu/lib/python3.4/site-  packages/django/db/models/base.py" in _do_update
          877.         return filtered._update(values) > 0
          File "/home/g4/django/pureRu/lib/python3.4/site- packages/django/db/models/query.py" in _update
          580.         return query.get_compiler(self.db).execute_sql(CURSOR)
    File "/home/g4/django/pureRu/lib/python3.4/site- packages/django/db/models/sql/compiler.py" in execute_sql
          1062.         cursor = super(SQLUpdateCompiler,   self).execute_sql(result_type)
          File "/home/g4/django/pureRu/lib/python3.4/site-  packages/django/db/models/sql/compiler.py" in execute_sql
      840.             cursor.execute(sql, params)
    File "/home/g4/django/pureRu/lib/python3.4/site-packages/django/db/backends/utils.py" in execute
           79.             return super(CursorDebugWrapper, self).execute(sql,   params)
          File "/home/g4/django/pureRu/lib/python3.4/site-  packages/django/db/backends/utils.py" in execute
           64.                 return self.cursor.execute(sql, params)
           File "/home/g4/django/pureRu/lib/python3.4/site- packages/django/db/utils.py" in __exit__
          98.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
          File "/home/g4/django/pureRu/lib/python3.4/site-packages/django/utils/six.py" in reraise
          685.             raise value.with_traceback(tb)
          File "/home/g4/django/pureRu/lib/python3.4/site-  packages/django/db/backends/utils.py" in execute
          64.                 return self.cursor.execute(sql, params)
    
         Exception Type: DataError at /makeProfile/step2/
         Exception Value: missing "]" in array dimensions
         LINE 1: ...akeProfile_skills" SET "user_id" = 11, "skills" =   '[0,1,2,3,..
    .^

I am hoping its not a typo if you read all of that but I have had two eyes on this code and have checked it a million times.... So at this stage I am just hoping someone out there can help.

Thank you

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/c9483f8d-5b82-4318-b61c-5c96a2672dcf%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment