Python TypeError:升级到Django 2.1后,“用户”类型的对象不可JSON序列化

时间:2019-03-03 07:47:49

标签: python django python-3.x django-2.1 django-1.10

我正在尝试将Django项目从Django(1.10)升级到Django(2.1),同时我只遇到一个错误,就是使用request.user.pk传递用户创建的错误一个对象。

到目前为止,这就是我所拥有的:

来自models.py

class TaggedArticle(models.Model):
    user = models.ForeignKey(User, related_name='tagging', on_delete=models.CASCADE)
    email = models.EmailField(max_length=255)
    category_fit = models.CharField(choices=choices, max_length=255)
    article = models.ForeignKey(Article, related_name='articles', on_delete=models.CASCADE)
    link = models.URLField(max_length=255,)
    relevant_feedback = models.TextField(blank=True)
    category = models.CharField(max_length=255,)
    created_at = models.DateTimeField(default=timezone.now, editable=False)

来自forms.py

class TagForm(forms.ModelForm):
    class Meta:
        model = TaggedArticle
        fields = ('user', 'category_fit', 'article', 'link', 'relevant_feedback', 'category',)
        widgets = {
            'category_fit': forms.RadioSelect()
        }

并且来自views.py

class TagView(LoginRequiredMixin, generic.CreateView):
    form_class = forms.TagForm

    def post(self, request, *args, **kwargs):
        try:
            post_data = request.POST.copy()
            post_data.update({'user': request.user.pk})
            print(post_data.values)
            form = forms.TagForm(post_data)
            if form.is_valid():
                tag = form.save(commit=False)
                tag.user = request.user
                tag.email = request.user.email
                tag.save()
                request.session['user'] = tag.user
                request.session['email'] = tag.email
            else:
                print(form.errors)
                return HttpResponse(form.errors, status=400)

            print('going to redirect after successful tagging.')
            return HttpResponseRedirect(reverse('users:dashboard'))

        except Exception as exp:
            logging.error(exp)
            print('error is: {}'.format(exp))
            return HttpResponse(exp, status=400)
  

更新:这是模板中的HTML表单:

<form class="omb_loginForm" action="{% url 'users:tagged' %}" method="POST">
      {% csrf_token %}
      <table class="table">
         <thead><h4> Tag this Article:</h4></thead>
         <tbody>
            <tr>
               <th>Reviewer:</th>
               <td></td>
               <td>{{ user.username }}</td>
             </tr>
             <tr>
                <th>No of Article Reviewed:</th>
                <td></td>
                <td>{{ user.tagging.all |length }}</td>
              </tr>
              <tr>
                 <th>Category:</th>
                 <td></td>
                 <td>{{ art.category }}
                     <input type="hidden" value="{{ art.id }}" name="article"/>
                     <input type="hidden" value="{{ art.link }}" name="link"/>
                     <input type="hidden" value="{{ art.category }}" name="category"/>
                 </td>
              </tr>
              <tr>
                <th>Does the text of this article fit in this category?</th>
                   <td><label class="radio-inline"><input type="radio" name="category_fit"
                                                                            value="yes">Yes</label></td>
                    <td><label class="radio-inline"><input type="radio" name="category_fit"
                                                                               value="no">No</label></td>
                    <td><label class="radio-inline"><input type="radio" name="category_fit"
                                                                               value="not sure">Not Sure</label>
                     </td>
                </tr>
                <tr>
                   <th><label for="comment">Copy and then paste in a relevant sentence for categorization:</label></th>
                      <td colspan="3">
                          <textarea class="form-control" rows="7" id="comment"
                                                      name="relevant_feedback"></textarea>
                      </td>
                  </tr>
              </tbody>
         </table>
         <button class="btn btn-lg btn-primary btn-block" type="submit">Tag</button>
</form>

因此,在POST请求中,它返回以下错误:

TypeError: Object of type 'User' is not JSON serializable

当我打印form.errors时,它会打印:

<ul class="errorlist"><li>user<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul>

那么,这里有什么问题呢?

谢谢!

1 个答案:

答案 0 :(得分:1)

由于您的user实例中的TaggedArticle是当前登录的用户,我认为您无需在user中指定TagForm。您可以从user的{​​{1}}中删除fields

TagForm

现在,由于视图自动将当前登录的用户保存为class TagForm(forms.ModelForm): class Meta: model = TaggedArticle fields = ('category_fit', 'article', 'link', 'relevant_feedback', 'category',) widgets = { 'category_fit': forms.RadioSelect() } 的{​​{1}},因此无需进行其他工作,并且也可能不会发生错误。

编辑:也许该错误是由以下行产生的:

user

此处,User对象不可JSON序列化,并且Django在版本1.6之后使用JSON序列化会话数据。因此,您可能需要存储用户ID而不是User对象。 示例:

TaggedArticle