I will be using Django only as the backend. The front end will be done using React and no django templates. I am using django-rest-framework to create a rest api for my website.
I made a serializer for the user.
class CustomUserSerializer(serializers.ModelSerializer):
class Meta:
model = CustomUser
fields = (
'id', 'email', 'password', 'username', 'first_name', 'last_name', 'date_of_birth', 'gender', 'mobile_number'
)
extra_kwargs = {
'password': {'write_only': True},
'id': {'read_only': True}
}
def create(self, validated_data):
user = CustomUser.objects.create(
email=validated_data['email'],
username=validated_data['email'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
date_of_birth=validated_data['date_of_birth'],
gender=validated_data['gender'],
mobile_number=validated_data['mobile_number']
)
user.set_password(validated_data['password'])
user.save()
return user
class CustomUserViewSet(viewsets.ModelViewSet):
queryset = CustomUser.objects.all()
serializer_class = CustomUserSerializer
In the browser, when I go to /custom/users/ I can view the users. I can also create new users which after successful registration returns back the user. Also it works if I use httpie/curl.
(djangoweb) vagrant@precise32:~$ http --json POST http://55.55.55.5/custom/users/ email="ter23minal2@gmail.com" password="terminal2123" username="t223erm" first_name="te2er" last_name="mi2nal" date_of_birth=1992-12-12 gender=2 mobile_number=66222666666336
It creates and returns the new user object.
So I made a form to register a user which I am not serving from the django server:
<form action="http://55.55.55.5/custom/users/" method="post" id="register-form">
<input type="text" placeholder="email" name="email"/>
...
...
<button id="post">Register</button>
</form>
And ajax to post the form.
// using the javscript Cookies library
var csrftoken = Cookies.get('csrftoken');
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$('#post').click(function(event) {
event.preventDefault();
var $form = $('#register-form');
var data = $form.serialize();
$.ajax({
type: "POST",
url: "http://55.55.55.5/custom/users/",
data: JSON.stringify(data),
sucess: function() { console.log("Success!"); },
contentType: "application/json; charset=utf-8",
dataType: "json",
crossDomain:false,
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
});
});
Now after if I click the button, the problem starts:
- Even though I gave
event.preventDefault()
the page is automatically loaded to the url of the django server (i.e., http://55.55.55.5/custom/users/). - I get an error: "detail": "CSRF Failed: CSRF token missing or incorrect."
How can I handle the post to the django server using django-rest-framework? I didn't find any helping material for this problem. Could you please guide me how to? Thank you.