Django take value from url - python

I have problem with take value from url (?site=value). When I had function in views.py it was work, but now I moved this to another file. Can someone solve this problem?
functionAjax.py:
def htmlMain(request):
if request.is_ajax and request.method == "POST":
UrlCut = request.GET.get('site','Main')
Messages = NewsMessage.objects.all().order_by('-Data').values()
context = {
"Messags" : Messages
}
return render(request, 'ajax'+UrlCut+'.html', context)
AjaxFunction.js:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
let tech = ""
if($.urlParam('site') != null)
{
tech = "?site=" + $.urlParam('site');
}
UrlSet = "/get/ajax/validate/MainSite"+tech;
$.ajax({
url: UrlSet,
data: $('#FormSite').serialize(),
type: "POST",
async:false,
success: function(response) {
$("#AjaxChange").replaceWith(response);
},
error: function(data)
{
alert('Bad connection');
console.log(data);
}
});

use 'Site' instead of 'site' to get Site=value
UrlCut = request.GET.get('Site', 'Main')

Related

jquery ajax function undo not working as expected

I have a list of words, and want users to be able to click a button if they know a word, then this word will change to 'Known', the css class will change and the field word_is_known will change from False to True. But I also want the user to be able to undo this action. This seems to be working fine the first time, i.e. if the user clicks and then unclicks. But if the user clicks the same word again, it creates another entry into the KnownWord model instead of updating the existing one. I've been playing around with this endlessly, but can't figure it out.
Here is my jquery:
$(document).ready(function() {
var known_words = 0;
var clicked_words = [];
var unclicked_words = [];
$(".word_known").click(function() {
var reference = this;
var objectpk = $(this).data('objectpk');
var userpk = $(this).data('userpk');
$(this).toggleClass('increment');
if ($(this).hasClass('increment')) {
known_words++;
clicked_words.push($(this).data('word'));
add_object = 'add';
$.ajax({
async: false,
url: "/videos/songs/vocab/known/"+objectpk+"/"+userpk+"/",
data: {'action': add_object, 'known_words': known_words, 'clicked_words': clicked_words},
success: function(data) {
$(reference).removeClass("btn-warning");
$(reference).addClass("btn-success");
$(reference).text("Known");
},
failure: function(data) {
alert("There is an error!")
},
contentType: "application/x-www-form-urlencoded; charset=utf-8",
})
console.log(known_words, clicked_words);
}
else {
known_words--;
unclicked_words.push($(this).data('word'));
remove_object = 'remove';
$.ajax({
async: false,
url: "/videos/songs/vocab/known-undo/"+objectpk+"/"+userpk+"/",
data: {'action': remove_object, 'known_words': known_words, 'unclicked_words': unclicked_words},
success: function(data) {
$(reference).removeClass("btn-success");
$(reference).addClass("btn-warning");
$(reference).text("Yes");
},
failure: function(data) {
alert("There is an error!")
},
contentType: "application/x-www-form-urlencoded; charset=utf-8",
})
console.log(known_words, unclicked_words);
}
})
});
My views:
def word_known(request, object_pk, pk_user):
if request.method == 'POST':
pass
elif request.method == 'GET' and request.GET['action'] == 'add':
known_words = request.GET.get('known_words', '')
clicked_words = request.GET.getlist('clicked_words[]')
request.session['known_words'] = known_words
request.session['clicked_words'] = clicked_words
user = request.user
song = models.Song.objects.get(pk=object_pk)
for word in set(clicked_words):
models.KnownWord.objects.get_or_create(word_is_known=True,
word=word, user=user, song=song)
print('The number of known words is {} and clicked words are {}'.format(known_words, clicked_words))
return HttpResponse(json.dumps(clicked_words), content_type='application/json')
def word_known_undo(request, object_pk, pk_user):
if request.method == 'POST':
pass
elif request.method == 'GET' and request.GET['action'] == 'remove':
known_words = request.GET.get('known_words', '')
unclicked_words = request.GET.getlist('unclicked_words[]')
request.session['known_words'] = known_words
request.session['unclicked_words'] = unclicked_words
user = request.user
song = models.Song.objects.get(pk=object_pk)
for word in set(unclicked_words):
models.KnownWord.objects.filter(word=word,
user=user, song=song).update(word_is_known=False)
print('The number of known words is {} and deleted words are {}'.format(known_words, unclicked_words))
return HttpResponse(json.dumps(unclicked_words), content_type='application/json')
The KnownWord model:
class KnownWord(models.Model):
word_is_known = models.BooleanField(default=False)
word = models.CharField(max_length=25)
user = models.ForeignKey(User, related_name="known_words", on_delete=models.CASCADE)
song = models.ForeignKey(Song, on_delete=models.CASCADE, null=True, blank=True)
movie = models.ForeignKey(Movie, on_delete=models.CASCADE, null=True, blank=True)
And the relevant part from my template:
....
{% elif item.0 in known_words %}
Known
{% else %}
Yes
{% endif %}
Your problem here is you didn't remove the value from the other array
Its all about arrays push , check , splice take a look at the next example
$(document).ready(function(){
var clicked_words = [] ;
var unclicked_words = [];
var known_words = 0;
$(document).on('click' ,'.word_to_know:not(.pending)' , function(){ //<<<<<<<<<<< here
var This = $(this);
var This_data_word = This.data('word');
This.addClass('pending').toggleClass('increment');
if(This.hasClass('increment')){
known_words++;
clicked_words.push(This_data_word);
unclicked_words = remove_if_in_array(unclicked_words , This_data_word);
// inside ajax callback //<<<<<<< here
setTimeout(function(){ //<< don't use this .. this is just for the demo
This.removeClass('pending'); // <<<<<<<< here
} , 2000); //<< don't use this .. this is just for the demo
}else{
known_words--;
unclicked_words.push(This_data_word);
clicked_words = remove_if_in_array(clicked_words , This_data_word);
// inside ajax callback //<<<<<<< here
setTimeout(function(){ //<< don't use this .. this is just for the demo
This.removeClass('pending'); // <<<<<<<< here
} , 2000); //<< don't use this .. this is just for the demo
}
console.log('known_words '+known_words);
console.log('clicked_words [' +clicked_words +']');
console.log('unclicked_words [' + unclicked_words+']');
});
});
// remove value if is in the array
function remove_if_in_array(array , value){
var index = array.indexOf(value);
if (index > -1) {
array.splice(index, 1);
}
return array;
}
// update value if is in the array
function update_if_in_array(array , value){
var index = array.indexOf(value);
if (index > -1) {
array.splice(index, 1);
}
array.push(value);
return array;
}
a.increment{
border : 1px solid #000;
background : green;
color : #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Known
Yes
I make a single class for all <a> named it word_to_know you can change anything whatever you want .. But I hope you got the idea

Error trying to save data in django via ajax(fetch)

I have a model that references other models, I am trying to save data using ajax
Example:
class Friend(models.Model):
name = ...
class Main(models.Model):
name = ....
friend = models.ForeignKey(Friend, on_delete=models.CASCADE)
All body comes from ajax(fetch) request
I have a table (html), and add data to cells, then with the
enter event, send data.
Like this:
input.addEventListener("keyup", function (e) {
//in this scenario I already have the whole row
// get full_row `row_data`
post_ajax = {
method: "POST",
headers: {
"X-CSRFToken": crf_token, // I get it with a regular expression
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest",
Accept: "application/json",
},
body: JSON.stringify(row_data),
};
fetch("my_url", post_ajax)
.then((res) => res.json())
.catch((error) => console.error("Error:", error))
.then((response) => console.log("Success:", response));
});
My view function
def save_post(request):
if request.is_ajax and request.method == "POST":
body_unicode = request.body.decode('utf-8')
data = json.loads(body_unicode)
print('here the data arrives',data)
# here the data arrives {'name': 'Ale', 'friend_id': 22}
Main.objects.create(name=data['name'], friends=data['friend_id'])
return JsonResponse({"instance": data}, status=200)
return JsonResponse({"error": ""}, status=400)
This is the error
raise TypeError("%s() got an unexpected keyword argument '%s'" %
(cls.__name__, kwarg))
TypeError: Main() got an unexpected keyword argument 'Friends'
Any idea or suggestion?
EDIT:
When you are creating the Main object, try making the "friend" attribute an object, like this:
friend = Friend.objects.get(id=data['friend_id'])
Main.objects.create(name=data['name'], friend=friend)
Also, the main issue appears to be you are calling the column "friends" but it should be "friend" when you are creating the Main object.
This:
Main.objects.create(name=data['name'], friends=data['friend_id'])
Should be:
Main.objects.create(name=data['name'], friend=data['friend_id'])
PREVIOUS ANSWER:
Assuming you are using JQuery in the template to send an AJAX request, since you did not specify.
In your urls.py:
...
path('/api/post_friend/', post_friend_api, name="post_friend_api"),
...
In your template :
<script type="text/javascript">
$("#myBurron").click(function(){
var csrfToken = $( "input[name='csrfmiddlewaretoken']"); // assuming this is a form
var friend_name = $("#friend_name").val();
$.ajax({ url: '{% url 'post_friend_api' %}',
type: "POST",
dataType: "json",
data: {'friend':friend_name, 'csrfmiddlewaretoken':csrfToken.val()},
cache: false
}).done(function(data) {
if (data.result === true){
alert(data.message);
}
});
});
});
</script>
In your views.py:
from django.http import JsonResponse
def post_friend_api(request):
data = {}
if request.POST.get('friend', None) is not None:
friend_name = request.POST.get('post_note')
# save the object and indicate success
data['result'] = True
data['message'] = "Friend saved successfully"
...
if request.is_ajax():
return JsonResponse(data)
else:
return HttpResponseBadRequest()
When you are sending data via POST don't forget to pass along your CSRF token as in the example above. This assumes you have a form on the page you can get it from, otherwise you can use something like this to get it:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
If you don't want to deal with the CSRF token, you can mark the view with the #csrf_exempt decorator and remove the 'csrfmiddlewaretoken' data element from the Ajax call in the template, but it may not be ideal or the most secure. An example of that:
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
#csrf_exempt()
def post_note_api(request):
...
If you post more details I can update my answer.

How is MultiValueDictKeyError and AttributeError related in Django here?

I have a function in Django that I am trying to solve from my previous question here. While trying out my own solutions, I have made significant updates but I encounter an error.
I'm trying this out right now:
def view_routes(request, query=None):
routes = None
if query is None:
routes = Route.objects.all()
else:
#View: Routes in Queried Boundary
if request.method == 'POST':
return HttpResponse("OK")
elif request.method == 'GET':
json_feature = json.loads(request.GET.get('geo_obj', False))
#json_feature = json.loads(request.GET['geo_obj'])
geom = make_geometry_from_feature(json_feature)
routes = Route.objects.filter(wkb_geometry__within=geom[0])
print("Total Routes Filtered: " + str(Route.objects.filter(wkb_geometry__within=geom[0]).count()))
#Render to Django View
routes_json = serialize('geojson', routes, fields=('route_type', 'route_long', 'route_id', 'wkb_geometry',))
routes_geojson = json.loads(routes_json)
routes_geojson.pop('crs', None)
routes_geojson = json.dumps(routes_geojson)
#return render(request, 'plexus/view_routes.html', {'routes':routes})
return redirect('routes_view', query)
I am having trouble switching/commenting out between these two lines:
json_feature = json.loads(request.GET.get('geo_obj', False))
json_feature = json.loads(request.GET['geo_obj'])
Both presents an error respectively:
TypeError: the JSON object must be str, not 'bool'
django.utils.datastructures.MultiValueDictKeyError: "'geo_obj'"
Edited function with AJAX inside:
function sendQueryData(url, query){
url =url.replace('query' , query);
if (query === ""){
alert("City Input Required");
}else{
if(geo_obj === null){
alert("Click Search Button...")
}else{
$.ajax({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
type: "GET",
url: url,
dataType: 'html',
data: {
'geo_obj' : JSON.stringify(geo_obj)
},
success: function(data){
alert(data);
window.location.href = url;
//var result = $('<div />').append(data).find('#list-group').html();
//$('#list-group').html(result);
},
error: function(xhr, textStatus, errorThrown) {
alert('Request Failed' + textStatus + ":" + errorThrown);
}
});
}
}
}
Try using json.loads(request.body) if you are passing raw JSON, request.GET['foo'] is for form-encoded data

error 405 get method not allowed

Angularjs code
var app = angular.module('myApp', []);
app.factory('httpSend', ['$http', '$q', function($http, $q) {
var app = {};
app.sendToServer = function(data) {
$http({
method: "POST",
url: '/report',
data: data,
headers: {
'Content-type': 'application/x-www-form.urlencoded;'
}
}).then(function(response) {
debugger
var result = data;
});
}
app.getfromServer = function() {
var def = $q.defer();
$http.get('/report').then(function(data) {
console.log(data);
def.resolve(data);
}),
function(error) {
def.reject("Failed to get albums");
};
return def.promise;
}
return app;
}]);
app.controller('myCtrl', ['$scope', '$http', 'httpSend', '$filter', function($scope, $http, httpSend, $filter) {
$scope.names = ["ankit patidar", "adhishi ahari", "kritin joshi", "kautilya bharadwaj", "punita ojha", "manvi agarwal", "apeksha purohit", "shipra jain", "mansi nangawat", "praveen soni"];
$scope.data = [];
$scope.names.forEach(function(name) {
$scope.data.push({
name: name,
checkin: "",
checkout: ""
})
});
$scope.login = [];
$scope.check = function(name, doing) {
debugger
name[doing] = new Date();
name[doing] = $filter('date')(name[doing], 'dd-MM-yyyy hh:mm:ss');
$scope.login.push(angular.copy(name));
if (doing == "checkout") {
var q = JSON.stringify($scope.login);
httpSend.sendToServer(q);
}
}
$scope.getData = function() {
httpSend.getfromServer();
}
}]);
`
Python Code
def get(self):
logging.info('get is triggered')
obj = CheckIn.query().fetch()
emp_obj = []
for x in obj:
logging.info('I am inside for loop ')
emp_obj.append({
'name': x.name,
'Check_in': x.inDate,
'check_out': x.outDate
})
logging.info('I am inside emp_obj')
self.response.write(json.dumps(emp_obj))
i need to fetch all the data stored on ndb datastore on front end view thats why i m using http get method but error is showed method not allowed. can u please help e despite using query fetch and showing its response on python ad triggering get method, why error is coming, is there a mistake in control flow or something is missing in my get method, as for now i m able to post nd store data
Change your factory to the following. Don't use the same variable app that you are using for initialising your module for your controller logic.
app.factory('httpSend',['$http', '$q',function($http, $q){
return {
'sendToServer': function(data) {
var def = $q.defer();
$http({
method: "POST",
url: '/report',
data: data,
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
debugger
var result = response.data;
def.resolve(result );
});
return def.promise;
},
'getfromServer': function() {
var def = $q.defer();
$http.get('/report').then(function(data) {
console.log(data);
def.resolve(data);
}),
function(error) {
def.reject("Failed to get albums");
};
return def.promise;
}
}
}]);

POST request to view function

I want to send POST request to view function. Now I am getting 500 error. I could not figure out where is the problem. The view function is receiving POST request but not returning any data.
EDIT: Now problem with 500 error solved. But how should I return form for editing object?
Template:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function editParticipant(event_id, row_id){
var postdata = {
'csrfmiddlewaretoken': csrftoken
}
$.post( "/edit-participant-" + event_id + "/", postdata, function( data ) {
console.log(data);
});
}
View:
def edit_participant(request, participant_id):
participant = Participant.objects.get(pk=participant_id)
form = RegisterToEvent(request.POST or None, instance = participant)
if form.is_valid():
form.save()
return HttpResponseRedirect('/event-%s' %2)
data = {'form': form}
return JsonResponse(data)
URL:
url(r'^edit-participant-(?P<participant_id>[0-9]+)/$', 'event.views.edit_participant', name='edit_participant'),
Your view doesn't return a response
def edit_participant(request, participant_id):
return JsonResponse({'data':"Test"})
You should also turn on debug in the settings by setting DEBUG to true, it will tell you exactly what the error is, just remember to turn this off before production. You can also implement error logging.
There isn't anything about this function that needs to use ajax requests. If you want to keep the same page if the form isn't valid, then just return the form errors and do something with them
data = { 'errors': form.errors }
But this doesn't make much sense to me when you can just load the page again with a form and let django do it for you with its form rendering.
return render(request, 'yourhtml.html', {form: form})

Categories