0

I am trying to create a post request from Angular 5 to DRF. The field is a form that a user submits. I created the serializer and i can post something from DRF interface

models.py

class UserForm(models.Model): id_user_form = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, db_column='idUser', unique=False) name = models.CharField(max_length=50) type = models.CharField(max_length=25) location = models.CharField(max_length=200)

serilizers.py `class UserFormSerializer(serializers.ModelSerializer):

class Meta:
    model = UserForm
    fields = ('user', 'name', 'type', 'location')

def create(self, validated_data):
    user_data = validated_data.pop('user')
    user_form = UserForm.objects.create(user_id=user_data, **validated_data)

    return user_form

views.py

class FormSubmit(generics.ListCreateAPIView): queryset = UserForm.objects.all() serializer_class = UserFormSerializer

When i try to post it via Angular I get this error: Forbidden (CSRF token missing or incorrect.): /api/form/

Am I doing something wrong?

1 Answers1

0

Had the exact same problem when I wanted to upload a profile picture to my Django REST backend.

You have 2 options, basically.

The first one is disabling the CSRF checks, which are by default enforced by DRF. Have a read here. You may do this for testing purposes.

The second option would be to pass the CSRF Token inside your request header. To do that, have a look at the $cookies API. With that, you can get the token out of the cookie and paste it into your header like so: 'X-CSRFToken': your-csrf-token-here.

You can verify this by opening your dev tools inside the browser and navigating to your site's cookies. You should see one called csrftoken there.

I hope this sent you on the right track.

fweidemann14
  • 1,714
  • 3
  • 13
  • 20
  • Thanks for the answer!! I had already implemented jwt. The problem was just an extra '/' in the url (const formUrl = `api/form/`;). The moment i removed it everything works fine. Sorry for the lack of info in the question and i really appreciate spending time to answer me. It helped me figure out other things that haven't completely understood. Piece – Thanos Ganja May 02 '18 at 19:42