Django form submit with ajax form.serialize() - python

views.py
def login(request):
password = request.POST.get('password')
mobile = request.POST.get('mobile')
user = authenticate(username=mobile, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect("/owner/?own=" + str(user.id))
login.html
$('.login-form').on('submit', function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
url: '/ajax/login/',
type: "POST",
data: form.serialize()
success: function(data) {
});
});
i'm getting error:
Method Not Allowed (POST): /
Method Not Allowed: /
[20/Oct/2018 04:41:30] "POST / HTTP/1.1" 405 0

You have a name conflict between your login function and the django built in login function, rename your function to something else like user_login.

I suppose you're missing csrf token? Try passing Django csrf token into your JQuery.

Related

How in CBV correctly redirect user if he dont have permission?

I want to redirect user to url (reverse_lazy('dashboard')) if Class Based View is not available to user (he dont have permission). I use next code but it dont redirect user. Whats wrong?
views.py:
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core.urlresolvers import reverse_lazy
class UserEditView(PermissionRequiredMixin, UpdateView):
template_name = 'users/edit_user.html'
form_class = UserEditForm
model = User
permission_required = ('auth.change_user')
login_url = None
redirect_field_name = reverse_lazy('dashboard')
LOG in terminal:
LevelName: WARNING | Message: Not Found: /accounts/login/
LevelName: WARNING | Message: "GET /accounts/login/?/=/user/50/edit/ HTTP/1.1" 404 2838
Also I tried next. If in settings.py I set LOGIN_URL = reverse_lazy('administration_login')in terminal I see next log but it dont redirect user:
LevelName: INFO | Message: "POST /user/50/edit/ HTTP/1.1" 302 0
LevelName: INFO | Message: "GET /login/?/=/user/50/edit/ HTTP/1.1" 302 0
LevelName: INFO | Message: "GET / HTTP/1.1" 200 2427
QUESTION: Can someone say how to make correct redirection to custom url if user don't have permission?
JS:
$(function () {
var saveForm = function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
if (data.form_is_valid) {
$("#users").html(data.html_users);
$("#user-modal").modal("hide");
}
else {
$("#user-modal .modal-content").html(data.html_form);
$("#user-errors").fadeIn("slow");
var error_message = "</br>";
var json_string = JSON.stringify(data.form_errors);
var json_object = jQuery.parseJSON(json_string);
$.each(json_object, function(key, value){
for (var i = 0; i < value.length; i++) {
error_message += value[i] + "</br>";
}
});
$("#user-errors .error-description").html(error_message);
setTimeout(function() {$("#user-errors").fadeOut("slow");}, 10000);
}
},
error: function (xhr, ajaxOptions, thrownError) {
$("#user-errors").fadeIn("slow")
$("#user-errors .error-description").html(thrownError);
setTimeout(function() {$("#user-errors").fadeOut("slow");}, 10000);
},
cache: false,
contentType: false,
processData: false,
});
return false;
};
$("#user-modal").on("submit", ".user-edit-form", saveForm);
});
You are misusing redirect_field_name. It should be the name of the field that stores the next URL, and it defaults to the string 'next'. Unless you have a good reason to change that you should remove that line and let Django use the default.
Use the login_url to configure your view to redirect to the dashboard.
class UserEditView(PermissionRequiredMixin, UpdateView):
login_url = reverse_lazy('dashboard')

Django: How to Like an Object with Ajax

Here's my View,
class ObjLike(RedirectView):
def get_redirect_url(self, *args, **kwargs):
id = self.kwargs.get('id')
obj = get_object_or_404(Data, id=id)
user = self.request.user
if user.is_authenticated():
if user in obj.likes.all():
obj.likes.remove(user)
else:
obj.likes.add(user)
So after this view how can I redirect user to the same page?
I used "return redirect(request.META['HTTP_REFERER'])" but it gives an error "name 'request' is not defined"
I can't use the get absolute URL method, i'm using this view at several places.
So, how can I do that?
to like an object with ajax calls do this
first in html we want to make a like button:
<button id="like">Like!</button>
the add a script that contain the ajax:
<script>
$(document).ready(function() {
$("#like").click(function(event){
$.ajax({
type:"POST",
url:"{% url 'like' Obj.id %}",
success: function(data){
confirm("liked")
}
});
return false;
});
});
</script>
the we add the like url to the urlpatterns list:
url(r'like/obj/(?P<pk>[0-9]+)/', views.like, name="like"),
adding the view :
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def like(request, pk)
obj = Obj.objects.get(id=pk)
obj.likes += 1
obj.save()
return HttpResponse("liked")
Note: you can customize the like view to check if user liked already

Django + Phonegap Authentication

I am building an application with Phonegap on the client side and a Django server on the backend. I am not able to authenticate the user. Here's my code.
$.ajax({
url: "http://192.168.0.101/userbase/login/",
type: "POST",
dataType: "json",
data: {"username": username,
"account": account,
"password": password,},
success: function (json) {
if (json.logged_in == true) {
window.location.href = "products.html";
}
else {
alert("Invalid Credentials. " + json.error);
}
}
});
This is the AJAX call to log in the user from the index.html. It is authenticated temporarily as in the views.py
# SOME CODE
login(request, user=user)
print(request.user.is_authenticated())
response = JsonResponse(response_data)
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Methods'] = 'OPTIONS,GET,PUT,POST,DELETE'
response['Access-Control-Allow-Headers'] = 'X-Requested-With, Content-Type'
return response
prints True. But, when the window redirects to products.html and I make an AJAX request to my Django server and check if the user is authenticated or not, it returns False. I am not able to find the error.
Please help. Thanks.

Cordova and Django login, session expire

I have a backend in django, and endpoint (rest framework) to login.
simple ajax
$.ajax({
type : "POST",
url : url+login/",
data : {username:username, password:password}
})
and simple view
#api_view(['POST'])
def login(request):
username = request.POST.get('username')
password = request.POST.get('password')
user = auth.authenticate(username=username, password=password)
if user is not None:
if user.is_active:
auth.login(request, user)
#When I type here: print request.session.items()
#I get _auth_user... things.
else:
pass
return Response({})
But when I change page in my native app, and there call another ajax e.g. url "test/", and this url call this view:
def test(request):
if request.user.is_authenticated():
print "Logged in
else:
#redirect to home...
return response
Then request.user.is_authenticated return False, looks like session expire is to small, so I try this:
...
auth.login(request, user)
#When I type here: print request.session.items()
#I get _auth_user... things.
request.session.set_expire(0)
...
But this doesn't work.
** EDIT **
Im using Django Rest Framework. And 'turn on':
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
)
}
I think you should consider using
'rest_framework.authentication.TokenAuthentication'
which will be much easier to handle on a mobile app, as you can just store the token after login, and use that token for any other API call. It also allows you to safely use csrf_exempt
AFAIK, $.ajax won't send any cookies if you are crossing domains, which you are doing by definition from a mobile app. So, I think your issue has to do with CORS and how you initialize the ajax call.
Try using:
xhrFields: { withCredentials:true }
on your .ajax call.
You also need to set up CORS (use django-cors-headers)
See http://www.django-rest-framework.org/topics/ajax-csrf-cors/ for other things that you may need to worry about. In particular
https://docs.djangoproject.com/en/dev/ref/csrf/#ajax
But as I said, consider using tokens instead of sessions.
I've had troubles with Django and post variables before.
Try changing your $.ajax call to:
$.ajax({
type : "POST",
url : "yourURL/",
contentType: "application/x-www-form-urlencoded",
data : 'username='+encodeURIComponent(username)+'&password='+encodeURIComponent(password),
});

Django returns invalid ajax response

I have a ajax call in my django template file as:
$(document).ready(function () {
$("button#wdsubmit").click(function(){
$.ajax({
type: "post",
url: "/audit/addwd/",
data: $('form.wddetails').serialize(),
dataType: "json",
success: function(msg){
alert(msg);
alert('Added Successfully');
$("#newwd").modal('hide'); //hide popup
},
error: function(msg){
alert(msg.success);
}
});
});
});
Form:
class WDForm(ModelForm):
class Meta:
model = WDModel
fields = '__all__'
and view in django is :
def addwd(request):
if request.method == 'POST':
updated_request = request.POST.copy()
updated_request.update({'updated_by': request.user.username})
form = WDForm(updated_request)
if form.is_valid():
form.save()
response = simplejson.dumps({'success': True})
return HttpResponse(response, content_type="application/json", mimetype='application/json')
else:
response = simplejson.dumps({'error': True})
return HttpResponse(response , content_type="application/json")
Whenever I make a Ajax call it always returns error even though I have sent Success(Means the form is valid and data is successfully pushed to database).
I also tried to send response={'success':True} doesn't work.
Please help me to solve this issue.
Environment Details:
Python verion: 3.4
Django :1.7
Windows OS 8
I doubt on this line " response = simplejson.dumps({'success': success})
"
you can try JsonResponse objects.
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

Categories

Resources