Django Rest Framework Angulars upload file using ModelSerializer - python

I'm trying to upload an image using Django Rest Framework and AngularJs
I'm using ng-file-upload to upload the image with AngularJs.
I saw it's possible to use ApiViewSet to do this. But as my Image is in a model and I use ModelSerializer so if it's possible I prefer to use ModelViewSet.
The problem is when I upload the image I got an error:
image: ["The submitted data was not a file. Check the encoding type on the form."]
Here is my code
Models.py
class Image(models.Model):
image = models.ImageField(upload_to="articles")
article = models.ForeignKey(Article)
Serializers.py
class ImageSerializer(serializers.ModelSerializer):
class Meta:
#article = ArticleSerializer(read_only=True, required=False)
image = serializers.ImageField(use_url=True, allow_empty_file=True)
model = Image
fields = ('id', 'image', 'article')
read_only_fields = ('id', )
#def get_validation_exclusions(self, *args, **kwargs):
# exclusions = super(ImageSerializer, self).get_validation_exclusion()
# return exclusions + ['article']
Views.py
class ImageViewSet(viewsets.ModelViewSet):
queryset = Image.objects.order_by('id')
serializer_class = ImageSerializer
class ImageArticleViewset(viewsets.ModelViewSet):
queryset = Image.objects.select_related('article').all()
serializer_class = ImageSerializer
def list(self, request, *args, image_pk=None):
queryset = self.queryset.filter(article__id=image_pk)
serializer = self.serializer_class(queryset, many=True)
return Response(serializer.data)
And the Controller
(function () {
'use strict';
angular
.module(nameProject + '.article.post.controller')
.controller('ArticlePostController', ArticlePostController);
ArticlePostController.$inject = ["$scope", "Articles", "Upload", "$timeout"];
function ArticlePostController($scope, Articles, Upload, $timeout) {
var vm = this;
vm.postArticle = postArticle;
$scope.$watch('files', function () {
$scope.upload($scope.files);
console.debug("files = ", $scope.files);
//console.debug("upload = ", $scope.upload);
});
$scope.upload = function (files) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
console.debug("file = ", file, "type = ", file.type);
Upload.upload({
url: '/api/v1/images/',
fields: {
'idArticle': 1,
'article': 1,
'image': file
},
file: file,
image:file
}).progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
$scope.log = 'progress: ' + progressPercentage + '% ' +
evt.config.file.name + '\n' + $scope.log
}).success(function (data, status, headers, config) {
$timeout(function () {
console.log("data === ", data.result);
$scope.log = 'file: ' + config.file.name + ', Response: ' + JSON.stringify(data) + '\n' + $scope.log;
});
});
}
}
};
}
})();
And this line
console.debug("files = ", $scope.files);
prints in the console
type = image/jpeg
The Jade template
form.form-signin(ng-submit="vm.postArticle()" enctype="multipart/form-data")
h2.form-signin-heading Post un article
input.input-block-level(type="text", name="title", placeholder="Title" ng-model="vm.title")
input.input-block-level(type="number", name="price", placeholder="Price" ng-model="vm.price")
input.input-block-level(type="text", name="content", placeholder="Description" ng-model="vm.description")
input.input-block-level(type="number", name="quantity", placeholder="Quantity" ng-model="vm.quantity")
input.input-block-level(type="text", name="color", placeholder="Color" ng-model="vm.color")
input.input-block-level(type="text", name="state", placeholder="State" ng-model="vm.state")
input.input-block-level(type="number", name="year", placeholder="Year" ng-model="vm.year")
p watching model
div(class="button" ngf-select ng-model="files" ngf-multiple="multiple") Select File on file change:
button.btn.btn-large.btn-primary(type="submit") Submit article

Django's REST Framework default way of dealing with uploaded files is to examine the header and decide how to deal with it:
http://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser
By default ng-file-upload, uploads the file in json format, this means that the file you are uploading is submitted as Base64 to Django, which in turn will try to decode the file using the following:
http://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser
This does not work with the default Django File field, there are different ways to accomplish this, one is to use the following option (sendFieldAs) in your request:
Upload.upload({
url: '/api/v1/images/',
...
sendFieldsAs: form,
This will submitt the data as a form, which Django REST framework will process as it should. The other options, would include decoding the Base64 and manually creating the File to be used with the file field, something that adds overhead compared to the sendFieldAs option.

Related

Django multiple AJAX queries for images

I made a button the user can click and it makes a AJAX GET request to the backend class Image. The response is the image url. I paste the url into a image tag and display it on the template
models.py
class Image(models.Model):
img = models.ImageField()
views.py
def ajax(request):
from django.http import JsonResponse
if request.is_ajax():
image = request.FILES.get('data')
aaa = Image.objects.get(id=1)
aaa = str(aaa.img.url)
return JsonResponse({'image_query': aaa}, status=200)
return render(request, 'components/ajax.html')
AJAX (template)
<button id="getData" class="btn btn-success">Get</button>
<div id="seconds"></div>
...
<script>
$(document).ready(function () {
$('#getData').click(function () {
$.ajax({
url: 'ajax',
type: 'get',
data: {
data: $(this).text()
},
success: function (response) {
$('#seconds').append('<img src="' + response.image_query + '" width="300">')
}
})
})
})
</script>
Everything works fine and the image is rendered to the template! Now I dont want to query the image with ID=1, I want all images to be fetched to the template.
I tried to do by adding a for loop into the views.py but it only returns the first element.
if request.is_ajax():
image = request.FILES.get('data')
for i in range(1, 5):
aaa = Image.objects.get(id=i)
aaa = str(aaa.img.url)
return JsonResponse({'image_query': aaa}, status=200)
I don't know what to modify that it will query every image in the DB. Does someone have a solution for my problem?
It's returning the only first element because you are returning inside the for loop, instead put the return 1 indent back, and put all of the urls in array.
... # code you have above
images = []
for i in range(1, 5):
aaa = Image.objects.get(id=i)
images.append(aaa.img.url)) # append the url to the list
return JsonResponse({'images': images}, status=200) # 1 indent back
as a result you'll have to change your javascript code like this.
const success = (response) => {
// Loop through each of the links
for (let i=0; i < response.image_query.length; i++) {
$('#seconds').append('<img src="' + response.image_query[i] + '" width="300">')
}
}
// ... Other code
$.ajax({
url: 'ajax',
type: 'get',
data: {
data: $(this).text()
},
success: success,
});
Also be carefull with $('#seconds').append('<img src="' + response.image_query + '" width="300">'), appending raw html could cause an XSS attack, if you are not completely sure that response.image_query is safe do not do this. (Since it is a url it should be escaped)

Django API REST : Issue with function in CreateAPIView

I'm working on my Django API Rest but it's pretty new for me and I have one more question about my code.
I'm reading all the time Django Rest Doc
------------------------------------------------------------------------------------------------------------------------------------
FIRST PART - My code :
------------------------------------------------------------------------------------------------------------------------------------
I have a serializer.py file which describe my ModelSerializer like this :
class IndividuCreateSerializer(serializers.ModelSerializer) :
class Meta :
model = Individu
fields = [
'Etat',
'Civilite',
'Nom',
'Prenom',
'Sexe',
'Statut',
'DateNaissance',
'VilleNaissance',
'PaysNaissance',
'Nationalite1',
'Nationalite2',
'Profession',
'Adresse',
'Ville',
'Zip',
'Pays',
'Mail',
'Telephone',
'Image',
'CarteIdentite',
]
def create(self, validated_data):
print('toto')
obj = Individu.objects.create(**validated_data)
Identity_Individu_Resume(self.context.get('request'), obj.id)
return obj
This create function calls another function which is not in my API module, but in my main module : Identity_Individu_Resume
As you can see here, this function takes the last created object and applies multiple processes :
#login_required
def Identity_Individu_Resume(request, id) :
personne = get_object_or_404(Individu, pk=id)
NIU = lib.Individu_Recherche.NIUGeneratorIndividu(personne)
personne.NumeroIdentification = NIU
if personne.Image != " " :
NewImageName = 'pictures/' + personne.Nom +'_'+ personne.Prenom +'_'+ NIU + '.jpg'
FilePath = settings.MEDIA_ROOT
FilePathOLD = settings.MEDIA_ROOT + str(personne.Image)
FilePathNEW = settings.MEDIA_ROOT + NewImageName
file = os.path.exists(FilePath)
if file :
os.rename(FilePathOLD, FilePathNEW)
personne.Image = NewImageName
if personne.CarteIdentite != " " :
NewCarteName = 'Carte_Identite/' + 'Carte_Identite_' + personne.Nom +'_'+ personne.Prenom +'_'+ NIU + '.jpg'
FilePath = settings.MEDIA_ROOT
FilePathOLD = settings.MEDIA_ROOT + str(personne.CarteIdentite)
FilePathNEW = settings.MEDIA_ROOT + NewCarteName
file = os.path.exists(FilePath)
if file :
os.rename(FilePathOLD, FilePathNEW)
personne.CarteIdentite = NewCarteName
else :
pass
personne.save()
context = {
"personne" : personne,
"NIU" : NIU,
}
return render(request, 'Identity_Individu_Resume.html', context)
Then, I have in my API module a views.py file with a specific class named IndividuCreateAPIView which is very simple and call my serializer class describes above :
class IndividuCreateAPIView(CreateAPIView) :
queryset = Individu.objects.all()
serializer_class = IndividuCreateSerializer
Then I have my urls.py file :
urlpatterns = [
url(r'^$', IndividuListAPIView.as_view() , name="IndividuList"),
url(r'^docs/', schema_view),
url(r'^create/$', IndividuCreateAPIView.as_view() , name="Create"),
]
------------------------------------------------------------------------------------------------------------------------------------
SECOND PART - Using API REST Interface :
------------------------------------------------------------------------------------------------------------------------------------
In this part, I'm using my API Rest interface with http://localhost:8000/Api/Identification/
When I create an object, the create function in my serializers.py file works well and I get a well-created object in my database :
So there is none issue !
------------------------------------------------------------------------------------------------------------------------------------
THIRD PART - Using API REST with pythonic file :
------------------------------------------------------------------------------------------------------------------------------------
In this case, I'm getting an issue.
I have a file API_create.py which is executed from my terminal and should simulate an external application which try to connect to my API and create an object.
import requests
url = 'http://localhost:8000/Api/Identification/create/'
filename1 = '/Users/valentin/Desktop/Django/DatasystemsCORE/Media/pictures/photo.jpg'
filename2 = '/Users/valentin/Desktop/Django/DatasystemsCORE/Media/Carte_Identite/carte_ID.gif'
files = {'Image' : open(filename1,'rb'), 'CarteIdentite': open(filename2,'rb')}
data = {
"Etat": "Vivant",
"Civilite": "Monsieur",
"Nom": "creation",
"Prenom": "via-api",
"Sexe": "Masculin",
"Statut": "Célibataire",
"DateNaissance": "1991-11-23",
"VilleNaissance": "STRASBOURG",
"PaysNaissance": "FR",
"Nationalite1": "FRANCAISE",
"Nationalite2": "",
"Profession": "JJJ",
"Adresse": "12, rue des fleurs",
"Ville": "STRASBOURG",
"Zip": 67000,
"Pays": "FR",
"Mail": "",
"Telephone": ""
}
response = requests.post(url, files=files, data=data)
print(response.text)
But, when I execute this script, my object is well-created BUT the function create in my serializers.py is not called !
In this case, I'm getting that :
My question is : Why my create function doesn't work ? I don't understand because my url is correct and should call this function in order to replace my NIU (NULL) by the generated NIU and change pictures names too ...
Could you help me to find why it doesn't work ?
Probably this is because of login_required decorator in Identity_Individu_Resume view. You can try to remove it or you need to provide auth token with request: response = requests.post(url, files=files, data=data, headers={'Authorization': 'Token <MY_TOKEN>'}).
UPD
Actually I suppose it would be better to move common part of api and non-api views to third function and call it separately from both views. In this case you probaly would like to add login_required to IndividuCreateAPIView view also. In this case you need to add IsAuthenticated permission like this:
from rest_framework.permissions import IsAuthenticated
class IndividuCreateAPIView(CreateAPIView) :
queryset = Individu.objects.all()
serializer_class = IndividuCreateSerializer
permission_classes = (IsAuthenticated,)

Create Google Cloud Function using API in Python

I'm working on a project with Python(3.6) & Django(1.10) in which I need to create a function at Google cloud using API request.
How can upload code in the form of a zip archive while creating that function?
Here's what I have tried:
From views.py :
def post(self, request, *args, **kwargs):
if request.method == 'POST':
post_data = request.POST.copy()
post_data.update({'user': request.user.pk})
form = forms.SlsForm(post_data, request.FILES)
print('get post request')
if form.is_valid():
func_obj = form
func_obj.user = request.user
func_obj.project = form.cleaned_data['project']
func_obj.fname = form.cleaned_data['fname']
func_obj.fmemory = form.cleaned_data['fmemory']
func_obj.entryPoint = form.cleaned_data['entryPoint']
func_obj.sourceFile = form.cleaned_data['sourceFile']
func_obj.sc_github = form.cleaned_data['sc_github']
func_obj.sc_inline_index = form.cleaned_data['sc_inline_index']
func_obj.sc_inline_package = form.cleaned_data['sc_inline_package']
func_obj.bucket = form.cleaned_data['bucket']
func_obj.save()
service = discovery.build('cloudfunctions', 'v1', http=views.getauth(), cache_discovery=False)
requ = service.projects().locations().functions().generateUploadUrl(parent='projects/' + func_obj.project + '/locations/us-central1', body={})
resp = requ.execute()
print(resp)
try:
auth = views.getauth()
# Prepare Request Body
req_body = {
"CloudFunction": {
"name": func_obj.fname,
"entryPoint": func_obj.entryPoint,
"timeout": '60s',
"availableMemoryMb": func_obj.fmemory,
"sourceArchiveUrl": func_obj.sc_github,
},
"sourceUploadUrl": func_obj.bucket,
}
service = discovery.build('cloudfunctions', 'v1beta2', http=auth, cachce_dicovery=False)
func_req = service.projects().locations().functions().create(location='projects/' + func_obj.project
+ '/locations/-',
body=req_body)
func_res = func_req.execute()
print(func_res)
return HttpResponse('Submitted',)
except:
return HttpResponse(status=500)
return HttpResponse('Sent!')
Updated Code below:
if form.is_valid():
func_obj = form
func_obj.user = request.user
func_obj.project = form.cleaned_data['project']
func_obj.fname = form.cleaned_data['fname']
func_obj.fmemory = form.cleaned_data['fmemory']
func_obj.entryPoint = form.cleaned_data['entryPoint']
func_obj.sourceFile = form.cleaned_data['sourceFile']
func_obj.sc_github = form.cleaned_data['sc_github']
func_obj.sc_inline_index = form.cleaned_data['sc_inline_index']
func_obj.sc_inline_package = form.cleaned_data['sc_inline_package']
func_obj.bucket = form.cleaned_data['bucket']
func_obj.save()
#######################################################################
# FIRST APPROACH FOR FUNCTION CREATION USING STORAGE BUCKET
#######################################################################
file_name = os.path.join(IGui.settings.BASE_DIR, 'media/archives/', func_obj.sourceFile.name)
print(file_name)
service = discovery.build('cloudfunctions', 'v1')
func_api = service.projects().locations().functions()
url_svc_req = func_api.generateUploadUrl(parent='projects/'
+ func_obj.project
+ '/locations/us-central1',
body={})
url_svc_res = url_svc_req.execute()
print(url_svc_res)
upload_url = url_svc_res['uploadUrl']
print(upload_url)
headers = {
'content-type': 'application/zip',
'x-goog-content-length-range': '0,104857600'
}
print(requests.put(upload_url, headers=headers, data=func_obj.sourceFile.name))
auth = views.getauth()
# Prepare Request Body
name = "projects/{}/locations/us-central1/functions/{}".format(func_obj.project, func_obj.fname,)
print(name)
req_body = {
"name": name,
"entryPoint": func_obj.entryPoint,
"timeout": "3.5s",
"availableMemoryMb": func_obj.fmemory,
"sourceUploadUrl": upload_url,
"httpsTrigger": {},
}
service = discovery.build('cloudfunctions', 'v1')
func_api = service.projects().locations().functions()
response = func_api.create(location='projects/' + func_obj.project + '/locations/us-central1',
body=req_body).execute()
pprint.pprint(response)
Now the function has been created successfully, but it fails because the source code doesn't upload to storage bucket, that's maybe something wrong at:
upload_url = url_svc_res['uploadUrl']
print(upload_url)
headers = {
'content-type': 'application/zip',
'x-goog-content-length-range': '0,104857600'
}
print(requests.put(upload_url, headers=headers, data=func_obj.sourceFile.name))
In the request body you have a dictionary "CloudFunction" inside the request. The content of "CloudFunction" should be directly in request.
request_body = {
"name": parent + '/functions/' + name,
"entryPoint": entry_point,
"sourceUploadUrl": upload_url,
"httpsTrigger": {}
}
I recomend using "Try this API" to discover the structure of projects.locations.functions.create .
"sourceArchiveUrl" and "sourceUploadUrl" can't appear together. This is explained in Resorce Cloud Function:
// Union field source_code can be only one of the following:
"sourceArchiveUrl": string,
"sourceRepository": { object(SourceRepository) },
"sourceUploadUrl": string,
// End of list of possible types for union field source_code.
In the rest of the answer I assume that you want to use "sourceUploadUrl". It requires you to pass it a URL returned to you by .generateUploadUrl(...).execute(). See documentation:
sourceUploadUrl -> string
The Google Cloud Storage signed URL used for source uploading,
generated by [google.cloud.functions.v1.GenerateUploadUrl][]
But before passing it you need to upload a zip file to this URL:
curl -X PUT "${URL}" -H 'content-type:application/zip' -H 'x-goog-content-length-range: 0,104857600' -T test.zip
or in python:
headers = {
'content-type':'application/zip',
'x-goog-content-length-range':'0,104857600'
}
print(requests.put(upload_url, headers=headers, data=data))
This is the trickiest part:
the case matters and it should be lowercase. Because the signature is calculated from a hash (here)
you need 'content-type':'application/zip'. I deduced this one logically, because documentation doesn't mention it. (here)
x-goog-content-length-range: min,max is obligatory for all PUT requests for cloud storage and is assumed implicitly in this case. More on it here
104857600, the max in previous entry, is a magical number which I didn't found mentioned anywhere.
where data is a FileLikeObject.
I also assume that you want to use the httpsTrigger. For a cloud function you can only choose one trigger field. Here it's said that trigger is a Union field. For httpsTrigger however that you can just leave it to be an empty dictionary, as its content do not affect the outcome. As of now.
request_body = {
"name": parent + '/functions/' + name,
"entryPoint": entry_point,
"sourceUploadUrl": upload_url,
"httpsTrigger": {}
}
You can safely use 'v1' instead of 'v1beta2' for .create().
Here is a full working example. It would be to complicated if I presented it to you as part of your code, but you can easily integrate it.
import pprint
import zipfile
import requests
from tempfile import TemporaryFile
from googleapiclient import discovery
project_id = 'your_project_id'
region = 'us-central1'
parent = 'projects/{}/locations/{}'.format(project_id, region)
print(parent)
name = 'ExampleFunctionFibonacci'
entry_point = "fibonacci"
service = discovery.build('cloudfunctions', 'v1')
CloudFunctionsAPI = service.projects().locations().functions()
upload_url = CloudFunctionsAPI.generateUploadUrl(parent=parent, body={}).execute()['uploadUrl']
print(upload_url)
payload = """/**
* Responds to any HTTP request that can provide a "message" field in the body.
*
* #param {Object} req Cloud Function request context.
* #param {Object} res Cloud Function response context.
*/
exports.""" + entry_point + """= function """ + entry_point + """ (req, res) {
if (req.body.message === undefined) {
// This is an error case, as "message" is required
res.status(400).send('No message defined!');
} else {
// Everything is ok
console.log(req.body.message);
res.status(200).end();
}
};"""
with TemporaryFile() as data:
with zipfile.ZipFile(data, 'w', zipfile.ZIP_DEFLATED) as archive:
archive.writestr('function.js', payload)
data.seek(0)
headers = {
'content-type':'application/zip',
'x-goog-content-length-range':'0,104857600'
}
print(requests.put(upload_url, headers=headers, data=data))
# Prepare Request Body
# https://cloud.google.com/functions/docs/reference/rest/v1/projects.locations.functions#resource-cloudfunction
request_body = {
"name": parent + '/functions/' + name,
"entryPoint": entry_point,
"sourceUploadUrl": upload_url,
"httpsTrigger": {},
"runtime": 'nodejs8'
}
print('https://{}-{}.cloudfunctions.net/{}'.format(region,project_id,name))
response = CloudFunctionsAPI.create(location=parent, body=request_body).execute()
pprint.pprint(response)
Open and upload a zip file like following:
file_name = os.path.join(IGui.settings.BASE_DIR, 'media/archives/', func_obj.sourceFile.name)
headers = {
'content-type': 'application/zip',
'x-goog-content-length-range': '0,104857600'
}
with open(file_name, 'rb') as data:
print(requests.put(upload_url, headers=headers, data=data))

DoesNotExist: [Model] matching query does not exist at id (ObjectId)

I am trying to query a unique document using its ObjectId. However the error comes up:
DoesNotExist: Route matching query does not exist
When, upon passing this to my view as request, it prints out the corresponding ObjectId in ObjectId typeform. Therefore there shouldn't be a problem with the line route_test = Route.objects.get(id=_id).
I have the following code:
views.py
def update(request):
if request.method == "POST":
_id = request.POST.get('_id',ObjectId())
print(_id)
route_id = request.POST.get('route_id','')
geometry = request.POST.get('geometry', '')
properties = request.POST.get('properties','')
#r = Route.objects.get(route_id='LTFRB_PUJ2616') --> I cannot use this
#because it has 5 instances (Not Unique)
#print (r["id"],r["properties"])
test = Route.objects.get(id = ObjectId('587c4c3b203ada19e8e0ecf6'))
print (test["id"], test["properties"])
try:
route_test = Route.objects.get(id=_id)
print(route_test)
Route.objects.get(id=_id).update(set__geometry=geometry, set__properties=properties)
return HttpResponse("Success!")
except:
return HttpResponse("Error!")
ajax
var finishBtn = L.easyButton({
id:'finish',
states: [{
icon:"fa fa-check",
onClick: function(btn){
selectedFeature.editing.disable();
layer.closePopup();
var editedFeature = selectedFeature.toGeoJSON();
alert("Updating:" + editedFeature.route_id);
$.ajax({
url: "/update/",
data: {id:editedFeature.id,
route_id: JSON.stringify(editedFeature.route_id),
geometry: JSON.stringify(editedFeature.geometry),
properties: JSON.stringify(editedFeature.properties)
},
type: 'POST'
});
}
model.py
from __future__ import unicode_literals
from mongoengine import *
class Route(Document):
type = StringField(required=True)
route_id = StringField(required=True)
geometry = LineStringField()
properties = DictField()
meta = {'collection':'routes'}
What should be done? Even the line test = Route.objects.get(id = ObjectId('587c4c3b203ada19e8e0ecf6')) where I directly supplied the incoming _id has the same error...

Pass arguments to multiple forms with the same request in Django

I am new in django and I have a doubt:
Is possible pass arguments to a several forms.
Scenario:
I have an html table rendered with django-tables2, in the first column I have a drop down button. One item from the drop down button open a bootstrap modal window with 3 diffetent forms(all the forma re modelbased forms).
The arguments are pased with a javascript function, the function take the value from some cells of the html table and send this value as argument.
All this form take the same arguments. I can pass the arguments to one form but I need to pass the arguments to all the forms.
In simple words:
How can I pass arguments to various forms in the same post request?
How I say above I am new with django and I don't know if is possible get this functionality.
UPDATE
my forms: (all the forms have the same code. nonly the name change)
class RecepcionForm(forms.ModelForm):
def __init__(self,*args,**kwargs):
super(RecepcionForm,self).__init__(*args,**kwargs)
self.helper = FormHelper(self)
self.helper.layout.append(Submit('save','Grabar'))
class Meta:
model = DetalleRecepcion
my views:(all the form use a view like this. only the name of the view change
def RecepcionView(request):
idp = request.GET.get('i')
anio = request.GET.get('a')
mes = request.GET.get('m')
if request.method == 'POST':
r = DetalleRecepcion.objects.get(id_proveedor=idp,anio=anio,mes=mes)
form = RecepcionForm(request.POST, instance=r)
if form.is_valid():
form.save()
return HttpResponseRedirect('/monitor/')
else:
r = DetalleRecepcion.objects.get(id_proveedor=idp,anio=anio,mes=mes)
form = RecepcionForm(instance=r)
return render_to_response('recepcion.html',
{'form':form},
context_instance=RequestContext(request))
I only know how to pass the value to an unique form. I use this fucntion:
<script type="text/javascript">
function param(){
var tbl = document.getElementById("myTable");
var rows = tbl.rows;
var argu = "";
for (var i = 0; i < rows.length; i++){
rows[i].onclick = function(){
idpro = this.cells;
argu = "?i="+idpro[0].innerHTML+"&a="+idpro[1].innerHTML+"&m="+idpro[2].innerHTML;
window.location = "/recepcion/"+argu;
}
}
}
</script>
I know that function is really bad coding, but I have some trouble to redirect toe the template using ajax post request.
I try to use this function but I can never redirect to the form where i send the parameters
<script type="text/javascript">
function param(){
$(function(){
//var http = new XMLHttpRequest();
var tbl = document.getElementById("myTable");
var rows = tbl.rows;
var url = "/recepcion/";
for (var i = 0; i < rows.length; i++){
rows[i].onclick = function(){
idpro = this.cells;
ano = this.cells;
mes1 = this.cells;
$.ajax({
async : false,
type:"GET",
url: "/recepcion/",
datatype: 'json',
data: ({i: idpro[0].innerHTML, a: ano[1].innerHTML, m: mes1[2].innerHTML }),
success: function(){
}
});
}
}
});
return false;
}
</script>
Any idea or advice how can I achieve this functionality.?
Thanks in advance

Categories