Update Contacts using Python, Django and Graph - python

I'm trying to update contacts using Python and Microsoft Graph within a profile page I've created using Django.
I can access contacts and get all the data I need, however I can't work out how to update the fields.
The only information I can find is on the Graph website, however I can't work out how to translate this into usable code:
PATCH PATCH https://graph.microsoft.com/beta/me/contacts/
Content-type: application/json
{
"title": "Mr",
"givenName": "Steve"
}
I assume there is a way to just put this together as a simple link but I cannot work it out. I've tried the following:
PATCH https://graph.microsoft.com/beta/me/contacts/{id}/title/Mr
PATCH https://graph.microsoft.com/beta/me/contacts/{id}/title:Mr
PATCH https://graph.microsoft.com/beta/me/contacts/{id}/title/$value==Mr
but they all produce errors
There are no tutorials for doing this with Python on the Microsoft site and it's proving very difficult to find any info on it. So hopefully someone can help out.
Cheers!
!!!!!!!!!!!!! UPDATE !!!!!!!!!!!!!!!!!!
Here is my current code which still sadly does nothing:
In my views.py:
def profile(request):
if request.session['has_id']==False:
contact_id = request.session['contact_id'] = request.POST.get('edit')
request.session['has_id'] = True
else:
contact_id = request.session['contact_id']
context = ct.profile(request,id=request.session.get('contact_id'),init=initialize_context,get_tok=get_token)
if request.method=="PATCH":
ct.update(contact_id,'title',request.PATCH.get('title'))
return render(request, 'tutorial/profile.html', context)
and my updater:
def update(id,key,value):
url = '{}/me/contacts/{}'.format(graph_url,id)
payload = {key : value}
head = {
"Content-type" : "application/json",
}
requests.patch(url=url,data=payload,headers=head)

Finally worked it out, I thought I'd tried something like this yesterday but apparently not.
Here's how to do it!
views.py
def profile(request):
if request.session['has_id']==False:
contact_id = request.session['contact_id'] = request.POST.get('edit')
request.session['has_id'] = True
else:
contact_id = request.session['contact_id']
context = ct.profile(request,id=request.session.get('contact_id'),init=initialize_context,get_tok=get_token)
if request.method=="PATCH":
ct.update(contact_id,'title',request.PATCH.get('title'))
return render(request, 'tutorial/profile.html', context)
contacts_helper.py:
def update(token,id,key,value):
graph_client = OAuth2Session(token=token)
url = '{}/me/contacts/{}'.format(graph_url,id)
payload = {key : value}
graph_client.patch(url,data=json.dumps(payload),headers={'Content-type': 'application/json'})
Obviously if you're looking at this you've probably already set up auth_helper.py and graph_helper.py but if you haven't then you should head over the Microsoft Graph website and follow these instructions:
https://developer.microsoft.com/en-us/graph/get-started/python

Related

Passing data from post form to FileResponde view

I recently started using Django and I managed to create two views, one to submit a form and another to return a FileResponse, separately, they work fine.
Now, I need to integrate both, when the client submit the form, I want to redirect to the another view using the fields submitted at the previous form. How can I do that?
Here is my form view:
def submitForm(request):
if 'report' in request.POST:
date_start = request.POST.get('date_start')
date_end = request.POST.get('date_end')
state = request.POST.get('state')
return render(request, 'comissao.html')
Here is my view that creates a pdf file
def createPdf(request):
date_start = '20220301'
date_end = '20220331'
state = 'G00471'
body = "some html"
options = { 'quiet': '' }
pdfkit.from_string(body, options=options)
file = open('file.pdf', 'rb')
return FileResponse(file)
As you can see, I need the information passed at my first view, to use at second view, I tried something like this, but I think I'm mistaking the concept,
return reverse('pdf', kwargs={'state':state, 'date_start':date_start, 'date_end':date_end})
reverse() only returns the URL, but I think you rather want to do a redirect() to that view.
For passing the parameters you have several options:
GET parameters
Session
URL parameters
Let's use GET parameters, which I would suggest:
from urllib.parse import urlencode
...
def submitForm(request):
...
response = redirect('pdf')
params = { state' : state, 'date_start: date_start, 'date_end': date_end}
response['Location'] += f'?{urlencode(params)}'
return response
Then in your PDF view you need to parse the GET parameters:
def createPdf(request):
date_start = request.GET.get("date_start")
...
Note that you may also need to convert your dates into string and back for the query, which I ignored here.

Django Rest - How to retreive more than one record from API and pass all of them to loop though in template?

Most of tutorials that I found was about creating APIs and not about using existing ones. I know that I am missing some huge, crucial thing. Could you please point me to it?
I want to receive from OMDB API several hits after posting title to search. My current code in views.py looks like this:
class MoviesList(APIView):
def get(self, APIView):
movies = Movie.objects.all()
serializer = MovieSerializer(movies, many=True)
return Response(serializer.data)
def post(self, request):
title = request.POST.get("Title")
api_key = "111111"
url = f"http://www.omdbapi.com/?t={title}&type=movie&apikey={api_key}"
response = requests.get(url)
serializer = MovieSerializer(data=response.json())
if serializer.is_valid():
serializer.save()
movie_details = {
'title': response.json()['Title'],
'genre': response.json()['Genre'],
'plot': response.json()['Plot'],
'year': response.json()['Year'],
'runtime': response.json()['Runtime'],
}
return render(request, 'movie_database/results.html', movie_details)
else:
print(serializer.errors)
print("Something went wrong.")
And it is working. With this code I receive one result and I can pass that to my template. And use values like "title" and "genre".
But I know that by changing in "url" t={title} to s={title} I can receive 10 results (I tested it in browser by hand and it is working).
EDIT:
When I change this letter "t" to "s" I receive this error:
AssertionError at /MoviesList/
Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
How I can utilize that and loop through them in my template? After looking for over 1 hour for answer I know that my basic approach is wrong but I am unable to find proper one right now.
Thank you.
Please check this documentation to loop over list in templates.
Plus why are you receiving APIView in get method!

Django filtering queryset

Here is my simple view:
def transaction_list(request):
current_user = request.user
month = datetime.date.today().month
try:
page = request.GET.get('page', 1)
except PageNotAnInteger:
page = 1
objects = Transaction.objects.filter(user=current_user, date__month=month)
p = Paginator(objects, 10, request=request)
transactions = p.page(page)
return render(request, 'transaction/list.html',
{'transactions': transactions})
It shows a list of transactions which occured in the current month.
I want to add an option to change the month of the transactions being displayed but I have no clue how to tackle this and make it work. Should it be done in a view? maybe template? I would appreciate any ideas
Take some time to read some Django docs as they may prove really valuable (not to mention they are very clean and well written for every version available). I would focus on Working With Forms
In short, you'll pass the month from your django template (maybe via ajax or a simple HTML form POST), to your view, and use your view function to get the POST data and use that in your queryset.
It is hard to provide a good, thorough answer because there are different ways to do this. Do you want AJAX? Simple form with page reload, etc? 
Okay, here, in detail, is how I usually handle a POST request. This isn't tested code, it's just psuedo code, but should work as far as I can tell, aside from a few minor typos probably. BUT, it should give you an idea of how to handle ajax requests in Django.
This is pretty 101 and taking some time to read the docs and run through some of the early projects covers a these concepts much I, so my going into more depth isn't really valuable to SO readers.
views.py
class change_date_form(forms.Form):
new_date = forms.DateField()
def change_transaction_date(request):
#Do some checks to make sure user is authorized to do this
current_user = ...
customer_data = []
if request.method == 'POST':
form = change_date_form(request.POST, request.FILES)
if form.is_valid():
change_date = form.cleaned_data.get('new_date')
objects = Transaction.objects.filter(user=current_user, date__month=change_date)
for i in objects:
customer_data.append(objects.name)
response_data = json.dumps(customer_data)
return HttpResponse(response_data, content_type='application/json')
urls.py
...
url(r'^change_date_view/', 'module.views.change_transaction_date'),
Jquery:
$('button_handler').on('click', function() {
var new_date_value = $(date_field_selector).val()
$.ajax({
url: "/change_date_view/",
type: "POST",
data: {
new_date: button_handler,
},
success:function(data) {
//build your html via javascript with response data
}
})
})

integrating Django with Angular js

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.
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.
have a look at
django-angular integration
django-angular-model-forms
django-angular

Django star rating system and AJAX

I am trying to implement a star rating system on a Django site.
Storing the ratings in my models is sorted, as is displaying the score on the page. But I want the user's to be able to rate a page (from 1 to 5 essentially) without a refresh or change of page.
I have found the following, and like the style of the stars here: http://jvance.com/blog/2008/09/22/JQueryRaterPluginNew.xhtml
Currently have a limited understanding of javascript and AJAX. Does anyone know how to use the stars in the above example combined with AJAX and Django, so you are able to update the database (models) without a page refresh when a user selects a rating?
It is also important that users are only able to vote once, i.e. they are not allowed to rate a page twice. It is stored in the models whether they have already voted and what their previous vote was. But how would I be able to modify the stars to show this?
So if you know how to do these things, or a more appropriate star rating graphics solution, or any good tutorials... please do share. Thank you.
AJAX sounds scary and confusing but it doesn't have to be. Essentially what you want to do is post some data to a particular url/view combo. See jQuery.post for more information on using AJAX to send data to the server.
#urls
urlpatterns += patterns('',
url(r'^article/rate/', 'article.rate'),
#views
def rate(request):
if request.method == 'POST':
# use post data to complete the rating..
#javascript
$.post("/article/rate", { rating: 3, article: 2 },
function(data) {
// success! so now set the UI star to 3
});
As far as I know, star-ratings are produced with radio controls and css. So if you want to show the current rating per user on load of the page, just have your template render the associated radio with the checked option.
Jonathan you are welcome to the django world. as Django is a cool framework some djangonauts have written nice sites to help us.
if you go to http://djangopackages.com/categories/apps/ and search "rating" you will find some django pluggables with examples that will help you a lot with your project.
also see those util answers in another question: Best Practices: How to best implement Rating-Stars in Django Templates
Working on this recently, so thought I would provide a solution to the mix. Firstly, I'm using RateIt, which I have found to be very simple to set up and quite intuitve to use (add the RateIt *.js and .*css files to your base.html template):
http://www.radioactivethinking.com/rateit/example/example.htm
Here are the key pieces to my solution:
urls.py
url(r'^object/rate/$', RateMyObjectView.as_view(), name='rate_my_object_view'),
my_template.html
<div class="rateit" data-rateit-resetable="false">Rate it!</div>
ajax.js
$('.rateit').bind('click', function(e) {
e.preventDefault();
var ri = $(this);
var value = ri.rateit('value');
var object_id = ri.data('object_id');
$.ajax({
url: '/object/rate/?xhr',
data: {
object_id: object_id,
value: value
},
type: 'post',
success: function(data, response) {
console.log("ajax call succeeded!");
},
error: function(data, response) {
console.log("ajax call failed!");
}
});
});
Some view bits are from James Bennett (setting xhr, for example):
http://www.b-list.org/weblog/2006/jul/31/django-tips-simple-ajax-example-part-1/
views.py
from django.views.generic.base import View
from .models import MyObject
class RateMyObjectView(View):
def post(self, request):
my_object = MyObject.objects.all().last()
xhr = 'xhr' in request.GET
star_value = request.POST.get('value', '')
my_object.score = star_value
my_object.save()
response_data = {
'message': 'value of star rating:',
'value': star_value
}
if xhr and star_value:
response_data.update({'success': True})
else:
response_data.update({'success': False})
if xhr:
return HttpResponse(json.dumps(response_data), content_type="application/json")
return render_to_response(self.template_name, response_data)
models.py
from django.db import models
class MyObject(models.Model)
score = models.FloatField(max_length=1, default=0)
Keep in mind that this is a naive solution, and simply replaces the current star score in the last item in your object list. It's not ideal, as it would be better to store scores as their own model and link to the object. This was you can store them and do calculations like average, etc. I'm working on this now and will update this answer when I'm finished.

Categories