开发者

error while submitting data in the form django

I am trying to insert data into db it throws below error,can any please fix this.

enter code here

model.py

from django.db import models

# Create your models here.

class Profile(models.Model):
     name = models.CharField(max_length=50, primary_key=True)
     assign = models.CharField(max_length=50)
     doj = models.DateField()

     class Meta:
        db_table= 'profile'


     def __unicode__(self):

       return  u'%s' % (self.name)



class working(models.Model):
   w_name =models.ForeignKey(Profile, db_column='w_name')
   monday =  models.IntegerField(null=True, db_column='monday', blank=True)
   tuesday =  models.IntegerField(null=True, db_column='tuesday', blank=True)
   wednesday =  models.IntegerField(null=True, db_column='wednesday', blank=True)

   class Meta:
        db_table = 'working'



   def __unicode__(self):
      return  u'%s ' % ( self.w_name)

forms.py

from models import *
from django import forms

class WorkingForm(forms.ModelForm):

  def __init__(self,  *args, **kwargs):
        super(WorkingForm, self).__init__(*args, **kwargs)
        self.fields['w_name'] =forms.CharField(initial='x',widget=forms.HiddenInput())

  class Meta:
        model = working
        exclude = ('id')

view.py

# Create your views here.
from forms import *
from django import http
from django.shortcuts import render_to_response, get_object_or_404


def index(request):
  if request.method == "POST":
          form = WorkingForm(request.POST)
          if form.is_valid():
            form.save()
            return http.HttpResponse('Added')
  else:  
    form = WorkingForm()
  return render_to_response('add_workingdays.html',locals())

Error Message:

ValueError at /

Cannot assign "u'x'": "working.w_name" must be a "Profile" instance.

Request Method:     POST
Request URL:    http://127.0.0.1:8000/
Django Version:     1.2.4
Exception Type:     ValueError
Exception Value:    

Cannot assign "u'x'": "working.w_name" must be a "Profile" instance.

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/
Django Version: 1.2.4
Python Version: 2.6.5
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'check']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/core/handlers/base.py" in get_response
  100.                     response = callback(request, *callback_args, **callback_kwargs)
File "/home/xyz/newapp/../newapp/check/views.py" in index
  10.           if form.is_valid():
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/fo开发者_开发技巧rms/forms.py" in is_valid
  121.         return self.is_bound and not bool(self.errors)
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/forms/forms.py" in _get_errors
  112.             self.full_clean()
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/forms/forms.py" in full_clean
  269.         self._post_clean()
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/forms/models.py" in _post_clean
  320.         self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/forms/models.py" in construct_instance
  51.             f.save_form_data(instance, cleaned_data[f.name])
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/db/models/fields/__init__.py" in save_form_data
  416.         setattr(instance, self.name, data)
File "/usr/local/lib/python2.6/dist-packages/Django-1.2.4-py2.6.egg/django/db/models/fields/related.py" in __set__
  318.                                  self.field.name, self.field.rel.to._meta.object_name))

Exception Type: ValueError at /
Exception Value: Cannot assign "u'x'": "working.w_name" must be a "Profile" instance.

I did a foreign key relation between two tables and i am trying to insert the data to working table it get Cannot assign "u'x'": "working.w_name" must be a "Profile" instance.

If I remove

def __init__(self,  *args, **kwargs):
    super(WorkingForm, self).__init__(*args, **kwargs)
    self.fields['w_name'] =forms.CharField(initial='x',widget=forms.HiddenInput())

it works normally,but i want to enter the username as hidden,but it throwing foreign key error

EDIT:

Also refer to Foriegnkey issue while submitting the form for a problem throwing same error.


Update:
Looks like normally for ForeignKey fields the ModelForm generates a ModelChoiceField where its to_python method manages getting the foreign key instance from a PK value.

CharField.to_python just returns smart_unicode(value)

I would override the ModelForm clean_w_name method and ensure it returns a Profile object from your key.

class WorkingForm(forms.ModelForm):

    def __init__(self,  *args, **kwargs):
        super(WorkingForm, self).__init__(*args, **kwargs)
        self.fields['w_name'] =forms.CharField(initial='x',widget=forms.HiddenInput())

    def clean_w_name(self):

        data = self.cleaned_data['w_name']
        try:
            profile = Profile.objects.get(pk=data)
            return profile
        except Profile.DoesNotExist:
            raise forms.ValidationError("Profile doesn't exist")

    class Meta:
        model = working
        exclude = ('id')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜