我正在尝试通过ajax提交表单。我的模板如下:-
<form method="POST" id="form1" class="SignUP signupform">
<div class="classheading">Sign-up</div>
{% csrf_token %}
<input type="text" name="user" placeholder="Username" class="sinput" required="true" />
<input type="text"name="email" placeholder="Email" class="sinput" required="true"/>
<input type="password"name="password"placeholder="Password" class="sinput" required="true"/>
<input type="password"placeholder="Re-enter Password" class="sinput" required="true"/>
<button type="submit" class="subform">Sign Up</button>
</form>
提交此表单的ajax视图是:-
$(document).ready(function(){
$('#form1').submit(function(){
console.log('form is submitted');
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
var formdata={
'username':$('input[name=user]').val(),
'email':$('input[name=email]').val(),
'password1':$('input[name=password]').val(),
'password2':$('input[name=password1]').val(),
};
console.log("Formvalue is taken");
$.ajax({
type:'POST',
url:'/Submit/signingup',
data:formdata,
dataType:'json',
encode:true,
headers:{
"X-CSRFToken": csrftoken
},
})
.done(function(data){
console.log(data);
});
event.preventDefault();
});
});
在后端,我正在使用Django提交此表单。相应的视图如下:-
@csrf_protect
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
current_site = get_current_site(request)
mail_subject = 'Activate your blog account.'
message = render_to_string('acc_active_email.html', {
'user': user,
'domain': current_site.domain,
'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(),
'token':account_activation_token.make_token(user),
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return HttpResponse("Confirm your email.")
else:
return JsonResponse({'success': False,'errors': [(k, v[0]) for k, v in form.errors.items()]})
但是它显示403错误。在命令提示符下,它显示“ CSRF_TOKEN丢失或不正确”。 可能是什么错误?
答案 0 :(得分:0)
像这样从打开标记后立即输入csrf_token。并尝试
<form method="POST" id="form1" class="SignUP signupform">{% csrf_token %}
答案 1 :(得分:0)
尝试
mypal <- colorNumeric(palette = "viridis", domain = d$A)
leaflet() %>%
addProviderTiles("OpenStreetMap.Mapnik") %>%
setView(lat = 39.8283, lng = -98.5795, zoom = 4) %>%
addPolygons(data =
USA, stroke = TRUE, color='black', opacity=1, weight=.5, smoothFactor = 0.2, fillOpacity = 1,
fillColor = ~mypal(d$A),
popup = paste('<b>',d$state, "</b><br>A:", d$A) %>%
addLegend(position = "bottomleft", pal = mypal, values = d$A,
title = "A",
opacity = 1)