保存表单时,Django 1.11 ManytoMany字段的文字无效

时间:2018-04-25 04:27:12

标签: django many-to-many django-localflavor

我有一个拥有多对多领域的模型。当我尝试保存它时,它出错invalid literal for int() with base 10: 'A'错误。从其他帖子我看过,看起来它与我的forms.py中的CharField有关。在我的clean_states中,我可以打印self.cleaned_data['states']的值并获取状态的两个字母代码。我认为这将是保存到数据库的内容。我不确定为什么它认为我试图保存一个int。

models.py

class States(models.Model):
    state           = models.CharField(max_length=2, choices=US_STATES  , null=True, blank=True) 
    def __str__(self):
        return self.state

class Person(models.Model):    
    user            = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    state           = models.ManyToManyField(States)

views.py

class UserProfileUpdateView(LoginRequiredMixin, UpdateView):
    model      = Person
    form_class = UserProfileChangeForm
    template_name = 'accounts/profile-update-view.html'

    def get_context_data(self, *args, **kwargs):
        context = super(UserProfileUpdateView, self).get_context_data(*args, **kwargs)
        context['states'] = States.objects.all()
        return context

    def get_object(self):
        qs = Person.objects.filter(pk=self.request.user.person.user_id).first()

        return qs

forms.py

class UserProfileChangeForm(forms.ModelForm):
    state= forms.CharField(widget=USStateSelect(), initial='TX')
    class Meta:
        model = SkilledLaborer
        fields = ['user','state']

    def clean_user(self):
        user = self.cleaned_data['user']
        return user

    def clean_state(self):          
        state= self.cleaned_data['state']
        return state

    def save(self, *args, **kwargs):
        print('im saving')
        print(self.cleaned_data['states'])
        obj = super(UserProfileChangeForm, self).save(*args, **kwargs)
        print('here2')
        add_states = self.cleaned_data['states']
        print(add_states)
        print('here3')
        if add_states:
            for state in add_states.split(","):
                state = States.objects.get(state=state)
                obj.states.add(state)
        return obj

栈跟踪

Traceback:

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\views\generic\base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\contrib\auth\mixins.py" in dispatch
  56.         return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\views\generic\base.py" in dispatch
  88.         return handler(request, *args, **kwargs)

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\views\generic\edit.py" in post
  240.         return super(BaseUpdateView, self).post(request, *args, **kwargs)

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\views\generic\edit.py" in post
  183.             return self.form_valid(form)

File "C:\Users\Starlord\Dev\ecommerce\src\accounts\views.py" in form_valid
  174.         form.save()

File "C:\Users\Starlord\Dev\ecommerce\src\accounts\forms.py" in save
  105.         obj = super(UserProfileChangeForm, self).save(*args, **kwargs)

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\forms\models.py" in save
  469.             self._save_m2m()

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\forms\models.py" in _save_m2m
  451.                 f.save_form_data(self.instance, cleaned_data[f.name])

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\fields\related.py" in save_form_data
  1686.         getattr(instance, self.attname).set(data)

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\fields\related_descriptors.py" in set
  1007.                     self.add(*new_objs)

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\fields\related_descriptors.py" in add
  934.                 self._add_items(self.source_field_name, self.target_field_name, *objs)

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\fields\related_descriptors.py" in _add_items
  1083.                             '%s__in' % target_field_name: new_ids,

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\query.py" in filter
  784.         return self._filter_or_exclude(False, *args, **kwargs)

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\query.py" in _filter_or_exclude
  802.             clone.query.add_q(Q(*args, **kwargs))

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\sql\query.py" in add_q
  1250.         clause, _ = self._add_q(q_object, self.used_aliases)

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\sql\query.py" in _add_q
  1276.                     allow_joins=allow_joins, split_subq=split_subq,

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\sql\query.py" in build_filter
  1206.             condition = lookup_class(lhs, value)

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\lookups.py" in __init__
  24.         self.rhs = self.get_prep_lookup()

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\fields\related_lookups.py" in get_prep_lookup
  56.                 self.rhs = [target_field.get_prep_value(v) for v in self.rhs]

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\fields\related_lookups.py" in <listcomp>
  56.                 self.rhs = [target_field.get_prep_value(v) for v in self.rhs]

File "C:\Users\Starlord\Dev\ecommerce\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value
  966.         return int(value)

Exception Type: ValueError at /account/profile/
Exception Value: invalid literal for int() with base 10: 'A'

0 个答案:

没有答案