How to send data from JavaScript file to views.py django? - python

How can I send data ( the user_to_follow in this example ) to my views.py function ( follow ) to do some updates?
I'm trying to send the username from my JavaScript and then add the logged-in username to that username following list ( all done in my views.py function )
Views.py.
def follow(request, profile_to_follow):
try:
user_to_follow = User.objects.get(username=profile_to_follow)
user_to_following = Profile.objects.get(user=request.user.id)
except User.DoesNotExist:
return JsonResponse({"error": "Profile not found."}, status=404)
if request.method == "PUT":
user_to_following.following.add(user_to_follow)
return HttpResponse(status=204)
index.js
function follow_user(user_to_follow){
// How To send the user_to_follow to my views.py method.
// to add the current logged in user to the user_to_follow following list
console.log(user_to_follow)
}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
# API Routes
path("posts", views.compose_post, name="compose_post"),
path("posts/all_posts", views.show_posts, name="show_posts"),
path("posts/<int:post_id>", views.post, name="post"),
path("profile/<str:profile>", views.display_profile, name="profile"),
path("<str:profile_posts>/posts", views.display_profile_posts, name="profile_posts"),
path("follow/<str:user_to_follow>", views.follow, name="follow"),
]

The easiest method would be using an Ajax Query to send data from templates to your views.py
index.js
<script>
$(document).ready(function() {
function follow_user(user_to_follow){
$.ajax({
type: "PUT",
url: "{% url 'follow' user_to_follow %}",
data: {
user_data: user_to_follow,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success: function( data )
{
alert("Successful Added User to list");
}
});
});
});
</script>
views.py
def follow(request, profile_to_follow):
try:
user_to_follow = User.objects.get(username=profile_to_follow)
user_to_following = Profile.objects.get(user=request.user.id)
except User.DoesNotExist:
return JsonResponse({"error": "Profile not found."}, status=404)
if request.method == "PUT" and request.is_ajax():
user_to_following.following.add(user_to_follow)
return HttpResponse(status=204)
request.is_ajax()
This will return a boolean value based on whether the request is an AJAX call or not.
You can also refer to this documentation https://api.jquery.com/jQuery.ajax/#options

Related

How to solve Django form redirect not working?

I created a form. I want to when the user fills the form and then sends it, redirect a specific page.
But in my case, the form is saving successfully but does not redirect the page. How can I solve it?
views.py
def setup_wizard(request):
form = SetupForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
setup = form.save()
setup.user = request.user
setup.save()
redirect('dashboard')
else:
form = SetupForm()
context = {
'form': form,
}
return render(request, 'setup_wizard.html', context)
dashboard.urls.py
urlpatterns = [
path('', dashboard, name="dashboard"),
path('setup', setup_wizard, name="setup"),
]
mainproject.urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('dashboard/', include('dashboard.urls')),
... ]
When you're using the redirect method from Django shortcuts you need to return the function result. See this from Django docs

Send a queryset from Django views to JQuery

I want to send a JsonResponse of a queryset from Django views to JQuery but I am not getting any data from the JQuery side.
This is my views file add_field_views.py :
from django.http import JsonResponse
def drop_down_requests(request):
text = request.POST['text']
print("---->", text)
from captiq.financing_settings.models import ChoiceGroup
response = ChoiceGroup.objects.get(slug="Ja/Nein")
output = JsonResponse(response,safe=False)
print("output -", output)
return output
this is where I declared the URL in urls.py inorder for the Jquery to GET the data from the views :
urlpatterns = [
path('my-ajax-test/', add_field_views.drop_down_requests, name='ajax-test-view'),
]
project urls.py:
frontend_urls = []
for module_name, module_data in FRONTEND_MODULES.items():
frontend_urls.append(re_path(
module_data['url'],
XFrameSameOriginView.as_view(template_name=module_data['view']),
name=module_name))
urlpatterns = i18n_patterns(
path('admin/', admin_site.urls),
path('admin/log_viewer/', include(
('log_viewer.urls', 'log-viewer'), namespace='log-viewer')),
path('admin/docs/', include('docs.urls')),
path('_nested_admin/', include('nested_admin.urls')),
path('accounts/', include(
('accounts.urls', 'accounts'), namespace='accounts')),
path('api-auth/',
include('rest_framework.urls', namespace='rest_framework')),
)
api_v1_patterns = [
path('financing/', include(
('financing.urls', 'financing'), namespace='financing')),
path('financing-settings/', include(
('financing_settings.urls', 'financing_settings'),
namespace='financing_settings')),
path('partners/', include(
('partners.urls', 'partners'), namespace='partners')),
path('accounts/', include(
('accounts.urls', 'accounts'), namespace='accounts')),
path('customers/', include(
('customers.urls', 'customers'), namespace='customers')),
]
urlpatterns += [
path('api/v1/', include((api_v1_patterns, 'api'), namespace='api')),
path('', RedirectView.as_view(url='loan-application/auth')),
path('notifications/', include(
'notifications.urls', namespace='notifications')),
] + frontend_urls
if settings.ENABLE_ROSETTA:
urlpatterns += i18n_patterns(
path('admin/rosetta/', include('rosetta.urls')),
)
if settings.DEBUG:
urlpatterns += static(
settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
then is my JQuery which is waiting for the queryset data or JSON data :
window.addEventListener('load', function () {
(function ($) {
"use strict";
$(document).ready(function () {
$("#id_depending_field").change(function (event) {
console.log("am here man");
const valueSelected = this.value;
$.ajax({
type: "POST",
url: 'my-ajax-test/',
data: {
csrfmiddlewaretoken:
document.getElementsByName('csrfmiddlewaretoken')[0].value,
text: valueSelected
},
success: function callback(response) {
console.log("____________", response)
}
});
})
});
})(django.jQuery);
});
With the code above am not able to get JSON data in JQuery, Instead I get a weird HTML output below :
<link rel="stylesheet" type="text/css" href="/static/css/notifications.css">
.
What am I doing wrong here ?
when you use relative path it is easy to lead your urls to wrong place. at your page your ajax will call for /en/admin/financing_settings/field/add/my-ajax-test/.
you can save exact url on your html page with data-* attribute.
In your example add data-ajax_url attribute to your #id_depending_field (or any other element)
data-ajax_url="{% url "api:financing_settings:ajax-test-view" %}" - url must be like this as i understand your routing
and then in your ajax code instead of url: 'my-ajax-test/', use url: $(#id_depending_field).data('ajax_url')
this will always give you exact url from any page where you load your .js file. And later if you decide to refactor your project and change url path it will keep all changes for you without changing html or js code
Use absolute URL when sending AJAX request:
$.ajax({
type: "POST",
url: '/my-ajax-test/',
data: {
...
})
Apparently, you were sending it to /en/admin/financing_settings/field/add/my-ajax-test/ cause it was relative

Django URL redirecting issue

i have a redirect url problem when the user complete editing his profile informations ,i want to redirect to the profile page , but it display to me 404 error
this is My view.py file :
def ProfileView(request, pk=None):
prof = Profile.objects.all()
if pk:
pr = User.objects.get(pk=pk)
else:
pr = request.user
context= {
'pro':prof,
'profile':pr
}
return render(request,'profile.html',context)
def update_profile(request,id):
profile = get_object_or_404(Profile,id=id)
form = ProfileForm(request.POST or None ,request.FILES or None,instance=profile)
if request.method=='POST':
if form.is_valid:
form.save()
return redirect(reverse('profile-detail'))
context = {
'form':form
}
return render(request,'profile_update.html',context)
thi is my url.py file :
urlpatterns = [
path('admin/', admin.site.urls),
path ('',index),
path ('events_details/<id>',events_details,name="events_details"),
path ('evenements/',evenements,name="events"),
path ('projets/',projets,name="project"),
path ('project_detail/<id>/',project_detail,name="project-detail"),
path ('create_post',create_post,name="create_post"),
path ('project_detail/<id>/update_post',update_post,name="update_post"),
path ('project_detail/<id>/delete_post',delete_post,name="delete_post"),
#------------------------------------------------------------
path ('profile/',ProfileView,name="profile-detail"),
path ('profile_update/<id>',update_profile,name="profile-update"),
path('tinymce/', include('tinymce.urls')),
path('accounts/', include('allauth.urls')),
path('api-auth/', include('rest_framework.urls'))
]
The Error i got :
Request Method: POST
Request URL: http://127.0.0.1:8000/profile_update/
.
.
.
The current path, profile_update/, didn't match any of these.
The problem is that your url expects an id with the url (ie localhost:8000/profile_update/12), but when you are making a post request, you are not sending one.
So I am guessing you need to update the code like this:
def update_profile(request,id):
profile = get_object_or_404(Profile,id=id)
form = ProfileForm(request.POST or None ,request.FILES or None,instance=profile)
if request.method=='POST':
if form.is_valid:
form.save()
return redirect(reverse('profile-detail'))
context = {
'form':form,
'pk': id
}
return render(request,'profile_update.html',context)
And update the template as well:
<form name="form" method="post" action="{% url 'profile-update' pk %}">
Try changing the redirect line from
return redirect(reverse('profile-detail'))
to
return redirect('app-name:profile-detail')
where app-name is the name of your django app.

Unable to use Django Authenticate

I am receiving this error:
TypeError at /auth/
authenticate() missing 1 required positional argument: 'request'
I am using Django and also Django Rest Framework.
The HTTP POST looks like this:
{
"username": "HelloUser",
"password": "Hello123"
}
VIEW
#csrf_exempt
#api_view(['POST'])
def authenticate(self, request):
print(request.data)
user = authenticate(username=request.data['username'], password=request.data['password'])
if user is not None:
return Response({'Status': 'Authenticated'})
else:
return Response({'Status': 'Unauthenticated'})
URLS
urlpatterns = [
url(r'^', include(router.urls)),
url(r'create/', views.create),
url(r'retrieve/', views.retrieve),
url(r'auth/', views.authenticate),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
Firstly you should not use the name of the view as authenticate as it is getting mixed with Django auth's authenticate
And second, you don't need self parameter in authentication view i.e. def authenticate_user(request)
Update your code like this:
VIEW
from django.contrib.auth import authenticate
#csrf_exempt
#api_view(['POST'])
def authenticate_user(request):
print(request.data)
user = authenticate(username=request.data['username'], password=request.data['password'])
if user is not None:
return Response({'Status': 'Authenticated'})
else:
return Response({'Status': 'Unauthenticated'})
And your urls.py will be updated as per the view's name:
URLS
urlpatterns = [
url(r'^', include(router.urls)),
url(r'create/', views.create),
url(r'retrieve/', views.retrieve),
url(r'auth/', views.authenticate_user),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

How to recognise urls starting with anchor(#) in urls.py file in django?

I have starting building my application in angularJS and django, and after creating a login page, I am trying to redirect my application to a new url after successful login. I am using $location variable to redirect my page. Here is my code:
$scope.login = function() {
$http({
method: 'POST',
data: {
username: $scope.username,
password: $scope.password
},
url: '/pos/login_authentication/'
}).then(function successCallback(response) {
user = response.data
console.log(response.data)
if (user.is_active) {
$location.url("dashboard")
}
}, function errorCallback(response) {
console.log('errorCallback')
});
}
My initial url was http://localhost:8000/pos/, and after hitting the log in button, the above function calls, and I am redirected to http://localhost:8000/pos/#/dashboard. But I am unable to catch this url in my regex pattern in urls.py file:
My project urls.py file:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^pos/', include('pos.urls')),
url(r'^admin/', admin.site.urls),
]
And my pos application's urls.py file:
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^login_authentication/$', views.login_authentication, name='login_authentication'),
url(r'^#/dashboard/$', views.dashboard, name='dashboard')
]
Using this, I am getting the same login page on visiting this http://localhost:8000/pos/#/dashboard link. This means that in my urls.py file of my pos application, it is mapping my http://localhost:8000/pos/#/dashboard to first object of urlpatterns:url(r'^$', views.index, name='index'). How do I make python differentiate between both the links?
You have some major misunderstanding about and anchor in url. The anchor is called officially Fragment identifier, it's not part of the main url, so if you have # when you visit an url like http://localhost:8000/pos/#/dashboard, your browser would treat the remaining #/dashboard as the anchor in page that http://localhost:8000/pos/ renders. You shouldn't be even using it in your urls.py definition. Please read the link above more carefully about the usage of an anchor.
Using help from this answer, I figured a good redirection method through angular which doesn't append any anchor tag using $window:
$scope.login = function() {
$http({
method: 'POST',
data: {
username: $scope.username,
password: $scope.password
},
url: '/pos/login_authentication/'
}).then(function successCallback(response) {
user = response.data
console.log(response.data)
if (user.is_active) {
$window.location.href = '/pos/dashboard';
}
}, function errorCallback(response) {
console.log('errorCallback')
});
}

Categories

Resources