Reputation: 4285
This will going to be a very basic question that how to integrate Django with angularjs.I have developed a web application using Django.In views.py, i want to use json to dump my data from database but i don't have any idea or you can say i can't get started with the process.I have a very basic level knowledge about Angularjs.If you give some examples , then it will help me to get start in Angularjs using Django.For better convenience,here is a sample view that i have produced..
def userphoto(request):
user_photo = Photo.objects.get(user = request.user)
context = RequestContext(request)
ctx_dict = {'user_photo': user_photo}
return render_to_response('userena/profile_detail.html',ctx_dict,context)
here the ctx_dict directly rendering into a html file,but i want to render them using Angularjs probably using json and http get request to implement the data using Angularjs http service.How can i do this?in mention i am a novice in angularjs.
Upvotes: 2
Views: 1986
Reputation: 1563
You can use django-angular, of cause, but I find this package too WIP.
You should think about AJAX instead of just rendering. It depends on a problem.
I'd suggest to use plain django or adding tastypie or django-rest-framework. I, currently, use plain django views.
Yes, to send models data back to angular, you should provide JSON of your data, you should serialize your model. But! There is a lot problems and catches. First of, you don't need everything from the model. Because user could access to some strange fields. Because you will send too many data you don't use on client side.
So, you should serialize your items data into JSON with fields you want. Here is example how I do it:
@ajax_request
@login_required
def mydata_ajax(request):
qs = MyData.objects.all()
#add possible filters
if request.GET.get('search'):
s = request.GET.get('search')
qs = qs.filter(
Q(name__icontains=s) |
Q(email__icontains=s) |
Q(address__icontains=s) |
)
qs = qs.order_by('task_time', 'name')
#setup pagination so angular will retrieve data page by page
pages = Paginator(qs, 20)
try:
current_page = int(request.GET.get('page', 1))
except ValueError:
current_page = 1
if current_page > pages.num_pages:
current_page = 1
#get reguested page
page = pages.page(current_page)
#create response
return {
'total': pages.count,
'num_pages': pages.num_pages,
'page': current_page,
'data': [{
'id': o.id,
'name': o.name,
'email': o.email,
'address': o.address,
} for o in page.object_list]
}
First of, I use ajax_request
decorator, from django-annoying package, for my view, which expects view to return list, dictionary or any other simple data so it will automatically
serialize(convert) it to JSON.
There is some handy things for you, like example of filters and pagination, btw.
Upvotes: 1