无法执行发布请求Django + React

时间:2020-10-20 09:33:06

标签: python django

#accounts.models.py:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from words import models as word_models

# Create your models here.class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete  = models.CASCADE)
    last_visited_word = models.ForeignKey(word_models.Word, default=4760, on_delete = models.CASCADE)

def create_user_profile(sender, instance, created, **kwargs):
    if created:  
       profile, created = UserProfile.objects.get_or_create(user=instance)  

post_save.connect(create_user_profile, sender=User) 

#words/models.py
from django.db import models
from django.conf import settings


# Create your models here.

class Word(models.Model):
    word = models.TextField(blank=True, null=True)
    meaning = models.TextField(blank=True, null=True)
    
#accounts/serializers.py:
from rest_framework import serializers
from .models import UserProfile


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = '__all__'
    
    
#accounts/views.py:
@api_view(['POST'])
  #@authentication_classes([SessionAuthentication, BasicAuthentication])
@permission_classes([IsAuthenticated])
def userprofile_create_view(request, *args, **kwargs):
    user_id = request.data.get('user')
    try:
        instance = UserProfile.objects.get(user_id=user_id)
    except UserProfile.DoesNotExist:
        instance=None
    serializer = UserSerializer(instance, data=request.data)

    if serializer.is_valid(raise_exception=True):
        # create or update data
        serializer.save()
        return Response(serializer.data)
 

因此,基本上,当用户访问该特定ID时,我必须更新用户的last_visited_word。我无法执行“ post”方法来更新last_visited_word。 api调用是使用axios完成的。我正在使用React作为我的前端。当我尝试使用发布请求时,它说一个错误的请求。 BTW react和django已连接,因为我能够成功执行GET请求。

2 个答案:

答案 0 :(得分:0)

第一个问题是有点不完整,但是据我了解,您需要配置settings.py以允许来自您的React localhost的发布请求。在Django周围找到一种方法并做出反应也很棘手。

答案 1 :(得分:0)

检查api是否按预期工作。同样在django设置中,在中间件中启用cors并将运行React的服务器白名单。

相关问题