Django REST Framework和Vue.js在帖子

时间:2018-04-10 01:06:01

标签: django api vue.js django-rest-framework

我有一个由Django REST框架创建的API,它将数据提供给我的Vue.js前端。在我尝试发布API之前,这一切都很顺利。我得到的错误是:

django.db.utils.IntegrityError: null value in column "ifflist_id" violates not-null constraint
DETAIL:  Failing row contains (100, do more  stuff, f, null).

以下是我试图发布的模型:

class TodoItem(models.Model):
    text = models.CharField(max_length=200)  # this is the text of the actual to-do
    ifflist = models.ForeignKey(IffList,
                                on_delete=models.CASCADE,
                                related_name='item')
    is_completed = models.BooleanField(default=False)

这里是serializers.py:

class TodoItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = TodoItem
        fields = '__all__'
        depth = 1

这是API views.py:

class TodoListCreateAPIView(ListCreateAPIView):
    queryset = TodoItem.objects.all()  # this returns all the things, which is bad
    permission_classes = (IsAuthenticated, )
    serializer_class = TodoItemSerializer
    lookup_field = 'id'

class TodoRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):
    queryset = TodoItem.objects.all()  # this returns all the things, which is bad
    permission_classes = (IsAuthenticated, )
    serializer_class = TodoItemSerializer
    lookup_field = 'id'

相关的urls.py:

path('api/', api_views.IffListCreateAPIView.as_view(), name='ifflist_rest_api'),
path('api/todoitems/', api_views.TodoListCreateAPIView.as_view(), name='todoitem_rest_api'),
path('api/user/', api_views.UserListCreateAPIView.as_view(), name='user_rest_api'),
# api/:slug
path('api/<int:id>/', api_views.IffListRetrieveUpdateDestroyAPIView.as_view(), name='ifflist_rest_api'),
path('api/todoitems/<int:id>/', api_views.TodoRetrieveUpdateDestroyAPIView.as_view(), name='todoitem_rest_api'),

最后,发生魔法的Vue.js方法:

addTodo: function () {
  let new_todo_item = document.querySelector('#new_todo_item').value;
  this.newTodo = {'text': new_todo_item, 'ifflist_id': this.displayedIfflist.id};
  console.log(this.newTodo.text);
  console.log(this.newTodo.ifflist_id);
  let csrf_token = Cookies.get('csrftoken');
  this.$http.post('/api/todoitems/', this.newTodo, {headers: {'X-CSRFToken': csrf_token}})
      .then((response) => {
        this.loading = false;
        this.getIfflist(this.displayedIfflist.id);
      })
      .catch((err) => {
        this.loading = false;
        console.log(err);
      })
    },

我在Django 2和Vue 2上。

2 个答案:

答案 0 :(得分:2)

所以原来这里是深度属性:

class TodoItemSerializer(serializers.ModelSerializer):
class Meta:
    model = TodoItem
    fields = '__all__'
    depth = 1

一旦我删除它,一切都很好。这似乎是一个奇怪的DRF错误......

答案 1 :(得分:1)

this.newTodo = {'text': new_todo_item, 'ifflist_id': this.displayedIfflist.id}; 

更改为

this.newTodo = {'text': new_todo_item, 'ifflist': this.displayedIfflist.id};