Tuesday, June 30, 2015

Re: new installations tryout problem

Thanks a lot Mike Dewhirst. I think that's issue.

Directly check the database, there is no poll record there.

My current  models.py in poll reads like

import datetime
from django.db import models
from django.utils import timezone

# Create your models here.

class Poll(models.Model):
    def __unicode__(self):
        return self.question
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Question(models.Model):
    def __unicode__(self):
        return self.question_text
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    def __unicode__(self):
        return self.choice_text
    poll = models.ForeignKey(Poll)
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

And the corresponding mysql database tables are
mysql> desc polls_poll;
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| question | varchar(200) | NO   |     | NULL    |                |
| pub_date | datetime     | NO   |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> desc polls_question;
+---------------+--------------+------+-----+---------+----------------+
| Field         | Type         | Null | Key | Default | Extra          |
+---------------+--------------+------+-----+---------+----------------+
| id            | int(11)      | NO   | PRI | NULL    | auto_increment |
| question_text | varchar(200) | NO   |     | NULL    |                |
| pub_date      | datetime     | NO   |     | NULL    |                |
+---------------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> desc polls_choice;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| choice_text | varchar(200) | NO   |     | NULL    |                |
| votes       | int(11)      | NO   |     | NULL    |                |
| poll_id     | int(11)      | NO   | MUL | NULL    |                |
| question_id | int(11)      | NO   | MUL | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

This tutorial doesn't ask to create poll record, and since question is not modeled related to poll, so I can create and save a question record without poll.

These seem a bit strange, but let's just create a poll record to move on.

It turns out that's not the case:

>>> q.choice_set.create(choice_text='Not much', votes=0)
Cause the exception because
(1) the statement does not contain poll_id value
(2) the statement excutes the database insertion implicitly
(3) the table polls_choice column was set not null.

My guess is that the tutorial is out of sync with the changes of django....

So what's the best doc for learning django?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/29bc8d37-177e-4a54-b232-ae898212df19%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

STATIC_URL with thumbnail_url Template Tag

Hello,

I'm trying to use an image from my 'static' folder in one of my templates. I need to pass the image into the thumbnail_url filter but I can't get it to work. The image is not found. How do I specify the correct image path? (I posted this same question on stackoverflow yesterday.) Thank you!

I've tried this:

{% load thumbnail %}
<a href="{% url 'users:profile' profile.name %}">
    {% with path="{{STATIC_URL}}/images/green-icon.png" %}
    <img src="{{ path|thumbnail_url:'medium' }}" class="img-circle img-profile">
    {% endwith %}
</a>

and also:

{% load thumbnail %}  {% load staticfiles %}  <a href="{% url 'users:profile' profile.name %}">      <img src="{% static 'images/green-icon.png'|thumbnail_url:'medium' %}">  </a>

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/99f1e884-eee0-4329-a689-ce72a3c69522%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Diable basic auth on some pages

Cherie,

By default, there are no authentication controls in Django. Barring some custom middleware, authentication checks are performed within the views themselves or through something like the @login_required or @user_passes_test decorators. Are you certain that authentication is what's blocking your requests?

On Tue, Jun 30, 2015 at 9:43 AM, Cherie Pun <cherie.cy.pun@gmail.com> wrote:
Hi,

In the dev version of the website, we are using basic auth to limit access. However, we are currently developing an api for the website and I would like to use the api without going through the basic auth. Is it possible to disable basic auth for all the api urls?

Cheers,
Cherie

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0d9a681e-74c4-4b74-9648-e0e6c74beeb6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2Bv0ZYV1KjzF3Ao%2By7hp-WA8Txkuoj-uxTtwNv0%2B%2Bm-T0MmZRA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Django REST Cross Domain Request to Download a File

So I am trying to download a file via Django REST (referred to as the Back End from now on) instance through my web page. The web page and the Back End are currently installed on two different servers so this is a cross domain request.

Now, I have no problem making cross domain requests to any of the other API urls on the Back End, but this one that retrieves the file through a view I am struggling with.

The response comes back with status 200 (OK) and the headers all seem to be set correctly, but no download is forced.

I have tried using Ajax requests and XMLHttpRequests in Javascript but the response just doesnt force a download despite containing the correct Content-disposition header.

Any thoughts would be well appreciated. 
Thanks

G

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/91fd9f44-57b4-44d7-8a45-3eb0743de45b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Diable basic auth on some pages

Hi,

In the dev version of the website, we are using basic auth to limit access. However, we are currently developing an api for the website and I would like to use the api without going through the basic auth. Is it possible to disable basic auth for all the api urls?

Cheers,
Cherie

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0d9a681e-74c4-4b74-9648-e0e6c74beeb6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Apps for versioning model fields

Hi Fabio,

Have you tried these django packages?:

Simple History: https://www.djangopackages.com/packages/p/django-simple-history/
AuditLog: https://www.djangopackages.com/packages/p/django-auditlog/
CleanerVersion: https://www.djangopackages.com/packages/p/cleanerversion/

Or any other from: https://www.djangopackages.com/grids/g/model-audit/.

Best,
Afonso

On Monday, June 29, 2015 at 9:54:37 PM UTC-4, Fabio Caritas Barrionuevo da Luz wrote:
Hello, I need to implement versioning of a TextField to an electronic system to manages documents.

Before I try to reinvent the wheel, I'd like to know what are the reusable apps are available that solve this problem.

I have the following model class:
https://gist.github.com/luzfcb/226612d0b98dd4493f9d

I need versioning only the field 'content'

the type of versioning I need is much like the way it is implemented versioning of articles on Wikipedia.

I'm trying to use django-reversion, however, I think it is not designed for this use case.

Would you recommend me look any specific library? If so, what are the pros and cons What do you think of it?

I appreciate the help in advance.


--
Fábio C. Barrionuevo da Luz
Acadêmico de Sistemas de Informação na Faculdade Católica do Tocantins - FACTO
Palmas - Tocantins - Brasil - América do Sul


Blog colaborativo sobre Python e tecnologias Relacionadas, mantido totalmente no https://github.com/pythonclub/pythonclub.github.io .

Todos são livres para publicar. É só fazer fork, escrever sua postagem e mandar o pull-request. Leia mais sobre como publicar em README.md e contributing.md.
Regra básica de postagem:
"Você" acha interessante? É útil para "você"? Pode ser utilizado com Python ou é útil para quem usa Python? Está esperando o que? Publica logo, que estou louco para ler...

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/59a70396-cd11-4e87-a5cc-3cac07f40a31%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Help me develop a Job Tracker (?)

I knew there had to be something like a workflow engine, thanks for the hint.

I had a look at django-viewflow which looks pretty promising. Still, as far as I'm aware, some points are beyond the scope of this framework:
  • It would be nice if users could set up their own workflows.
  • I would like to have the flexibility of a workflow engine and some ingredients from standard bug trackers: It should be possible to comment on the different workflows.
  • I'd like to maintain a history of each workflow: Creation date, status change date, ... (who did what and when?)
  • User can subscribe to a workflow. They can choose when they want to get an update: Status change, someone commented, ...
  • when defining a workflow, for each activity one should be able to preset a user who is typically responsible and a due date for this event.
  • a comprehensive list of all workflows: filter based on workflow type, responsible user, in time / overdue, type of work, customer...
  • user should be able to change some properties of a workflow that is currently executed: For example to postpone a deadline. Users need to give a reason for this.
I'll dig a bit into django-viewflow to see how that works. django-fsm may work as well...

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/92da4877-c186-4134-9d01-73b443124714%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Monday, June 29, 2015

Django 1.8.2 - handler404 and handler500 refusing to work

Good afternoon all,

Perhaps someone can give me a pointer here:

I'm an old hand at Django (1.0 to 1.6) but now in 1.8.2, the documented process of writing and attaching custom handlers for '404' and '500' appears to have stopped working.

As per the dox, I have added into my ROOT url file, the required overrides:
from django.conf.urls import *
from django.contrib import admin

urlpatterns = [
    url(r'^apikey/', include('apikey.urls', namespace='apikey')),
    url(r'^admin/', include(admin.site.urls)),
]

handler404 = 'apikey.views.custom_handler'
handler500 = 'apikey.views.custom_handler'
I have created the default 404.html template in the apikey/templates directory and updated the site settings file to reflect this
and I can confirm that this default 404.html file is indeed getting rendered, but not by my routine:

views.py
-----------
def custom_handler(request):
    print '——>>> got to here'
    return HttpResponseNotFound('<h1>Boo! - Page not found</h1>')

I've been testing with DEBUG=False under 'python manage.py runserver'.
My custom handler never, *ever* fires when a URL not in my apikey/urls.py file is submitted by a GET and a 404 is supposed to be raised.

I am at a complete loss as to why this isn't working, having had no issues with this custom handler process over the past 5 years :(

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4cea481b-9db4-4eb1-8d7f-57d3e44d60b7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Apps for versioning model fields

Hello, I need to implement versioning of a TextField to an electronic system to manages documents.

Before I try to reinvent the wheel, I'd like to know what are the reusable apps are available that solve this problem.

I have the following model class:
https://gist.github.com/luzfcb/226612d0b98dd4493f9d

I need versioning only the field 'content'

the type of versioning I need is much like the way it is implemented versioning of articles on Wikipedia.

I'm trying to use django-reversion, however, I think it is not designed for this use case.

Would you recommend me look any specific library? If so, what are the pros and cons What do you think of it?

I appreciate the help in advance.


--
Fábio C. Barrionuevo da Luz
Acadêmico de Sistemas de Informação na Faculdade Católica do Tocantins - FACTO
Palmas - Tocantins - Brasil - América do Sul


Blog colaborativo sobre Python e tecnologias Relacionadas, mantido totalmente no https://github.com/pythonclub/pythonclub.github.io .

Todos são livres para publicar. É só fazer fork, escrever sua postagem e mandar o pull-request. Leia mais sobre como publicar em README.md e contributing.md.
Regra básica de postagem:
"Você" acha interessante? É útil para "você"? Pode ser utilizado com Python ou é útil para quem usa Python? Está esperando o que? Publica logo, que estou louco para ler...

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAPVjvMZi%2BgRmiizHErzhCTiGouQNDAB9EENA3S0xS1hUKqnt3w%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Blog post

Hi guys, this is my first time here but I need from your experience and your thoughts about this blog post that I have written: http://wp.me/p5G2dP-2K
I'm from Argentina and I'm really sorry about my English but any feedback from this list could be great!!!

Thanks,
Leandro.-

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a36d2595-7660-4aeb-b697-577a301e005e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Cannot overwrite 'get_fieldsets' in custom UserAdmin

Felippe,

No, it seems, that my"get_fieldsets"  isn't called.

Also when debugging by stepping through the code, as described in my second post, I see when loading the UserChangeForm the 'get_fieldsets' method from django.contrib.auth.admin.UserAdmin is used instead of my custom one.

Regards, Henri


Am Montag, 29. Juni 2015 16:15:16 UTC+2 schrieb Felippe Raposo:
Henri, can you set a "pdb.set_trace" or print something  at the beginning of your "get_fieldsets" to see if it is being called or not?

2015-06-28 6:58 GMT-03:00 Henri <he...@art.bieszczady.pl>:
As I use a custom user model the default django user model is not registered. When I try to unregister it I get an error.

See example in the django docs:
https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#a-full-example.

Regards, Henri

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/b169e3a8-29a5-4d33-b543-06b8d53597f0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/144e1ef9-9116-4e20-be5f-9229e95aea90%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

How to set back the data to ck-editor instance in a Django web app?

I have a Django web app which has various instances of ck-editor instances on a web page.By using on blur event I am saving whole of data of the instance in the database -
{% for editor in editors %}
<div id="{{editor.ck_id}}" name="{{editor.ck_id}}">
</div>
{% endfor %}

<script>
{% for editor in editors %}
   CKEDITOR.appendTo("{{editor.ck_id}}" ,
    {
        on: {
            blur: function(event){
                var data = event.editor.getData();
                console.log("data of {{editor.ck_id}} is " + data);

                 var request = $.ajax({
                     url: "/
editor/save/",
                     type: "
GET",
                     data: {
                         content : data,
                         content_id : "
{{editor.ck_id}}"
                    },
                     dataType: "
html"
                 });
            }
        }

    },


    "
{{editor.data}}"
    );
{% endfor %}

Here ck_id and data are the two database fields of ckeditors.Django model is -

from django.db import models

class ckeditor(models.Model):
    ck_id
= models.CharField(max_length=100,null=False,blank=False)
    data
= models.TextField(null=True,blank=True)

I have stored editor's data as a text field.Now suppose I write this on one instance of ckeditor -

Tony Stark

     
is Iron man.

Editor Image is -





Editor source is - 


It's weird that ck-editor does not have 
tag in source code(HTML format).Now when AJAX call is made I handle it like this -

def save(request):
if request.method == 'GET':
    editor_data
= request.GET['content']
    editor_id
= request.GET['content_id']

   
print "data received"
   
print "editor data is %s" %(editor_data)
   
print "editor id is %s" %(editor_id)
else:
   
print "No Data received"

editor
= ckeditor.objects.get(ck_id=editor_id)
editor
.data = editor_data
editor
.save()

In database data looks like this -


One can see that the html is rendered as text field in the database.Now however when I query editor's data in python shell it shows like this -

One can see now that since it was a text field it has filled some '\n' tags in between.

Now When I re start the server and set the data of every ck-editor instance again then this exception is raised -

Uncaught SyntaxError: Unexpected token ILLEGAL


This happened because the text(editor's data) which I sent got converted into illegal tokens.Do I need to convert text which I am sending into valid html or do I need to encode/decode that text?

Now my question is how to go about this complete procedure of fetching editor's data,storing it in database and then again reset data on restarting server. I have posted this question on several forums but many people have got no clue of what I am asking?

CK-EDITOR team has proudly mentioned that their community has been shifted to SO but I have got no replies from them either. I guess they only give support when user buys their license which costs 299$.

Can anybody please help me out in this? I am literally lost all hopes.I am getting no help for last 1 week and probably I will get some help this time around.

Thanks.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/02d4646d-2435-45e4-8ee6-8859b09c8451%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Cannot overwrite 'get_fieldsets' in custom UserAdmin

Hi Lagovas,

the trace and error message when unregistering the default Django user with your code:

  File "/home/pacha/web/rcl-network.local/private/django/rcl-network/venv/local/lib/python2.7/site-packages/mezzanine/boot/__init__.py", line 78, in autodiscover
    admin_site.lazy_registration()
  File "/home/pacha/web/rcl-network.local/private/django/rcl-network/venv/local/lib/python2.7/site-packages/mezzanine/boot/lazy_admin.py", line 33, in lazy_registration
    getattr(AdminSite, name)(self, *deferred_args, **deferred_kwargs)
  File "/home/pacha/web/rcl-network.local/private/django/rcl-network/venv/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 107, in unregister
    raise NotRegistered('The model %s is not registered' % model.__name__)
django.contrib.admin.sites.NotRegistered: The model User is not registered


Am Sonntag, 28. Juni 2015 09:48:35 UTC+2 schrieb Lagovas Lagovas:
first of all you need unregister default django models and then register yours AdminModel like:  admin.site.unregister(User)  admin.site.register(User, CustomUserAdmin)

пятница, 26 июня 2015 г., 3:16:24 UTC+3 пользователь Henri написал:
I'm using a custom user model and a custom UserAdmin.
I try do overwrite the 'get_fieldsets' method to change some fields and hide some others, bud django admin still uses the  'get_fieldsets' method from django.contrib.auth.admin.UserAdmin.

My CustomUserAdmin Class:

from django.contrib.auth.admin import UserAdmin
from users.models import User  # custom user model


class CustomUserAdmin(UserAdmin):

    add_fieldsets
= (
       
(None, {
           
'classes': ('wide',),
           
'fields': ('email', 'username', 'password1', 'password2')
       
}),
   
)

   
# The forms to add and change user instances
    form
= UserChangeForm
    add_form
= UserCreationForm

   
# The fields to be used in displaying the User model.
   
# These override the definitions on the base UserAdmin
   
# that reference specific fields on auth.User.
    list_display
= ('email', 'username', 'first_name', 'last_name', 'is_active', 'is_staff',
                   
'is_superuser')
    list_filter
= ('is_active', 'is_staff', 'is_superuser')
    search_fields
= ('email', 'first_name', 'last_name', 'username')
    ordering
= ('email',)
    filter_horizontal
= ('groups', 'user_permissions',)


   
def get_fieldsets(self, request, obj=None):
       
if not obj:
           
return self.add_fieldsets

       
if request.user.is_superuser and request.user.pk != obj.pk:
            perm_fields
= ('is_active', 'is_staff', 'is_superuser',
                           
'groups', 'user_permissions')
       
else:
            perm_fields
= ('is_active', 'is_staff', 'groups')

       
return [(None, {'fields': ('email', 'password')}),
               
(_('Personal info'), {'fields': ('first_name', 'last_name', 'username', 'biography')}),
               
(_('Permissions'), {'fields': perm_fields}),
               
(_('Important dates'), {'fields': ('last_login', 'date_joined')})]


admin
.site.register(User, CustomUserAdmin)




Some body have an idea, whats going on?
I'm working on this for days.
Please help.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/c2f195b5-2151-4bbd-ab39-eb978ae5a229%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Re: Canvas OAuth2 From Django View

First let me say that I'm probably making this harder than it needs to be, but I must be missing something in this process.

I'm trying to use the oauth2  process in the Canvas API, and I started working on this back in January, had other priorities that pulled me away from it, so I'm only now able to pursue working on this again.

I seem to be able to successfully send the original oauth2 request to the Canvas API, because I can get back a status code 200 from it.
But at that point everything seems to stop, so I'm not sure exactly what I'm doing wrong.

If after I send the successful response I get back from Canvas (and sending it the redirect_uri, etc.), back to my client, then I don't see any subsequent requests, coming back to the redirect_uri from Canvas, and don't understand why, or can I not normally see them as or when they happen?

If I don't send the successful response back to the client then I also don't see any subsequent requests coming to the view associated with the redirect_uri that I sent to Canvas and my application just fails with a status_code of "500".

So I think I'm probably not grasping exactly how a properly functioning "oauth2" process is supposed to work. 

I would appreciate any help anyone can offer in better explaining how the process works, how django view processing fits into it, and when to send and/or not send a response back to my client.

Thanks for the help.

Henry


On Wednesday, January 21, 2015 at 9:36:08 PM UTC-6, Collin Anderson wrote:
Hi Henry,

You need to send some kind of response back to the browser and the user. Maybe a message? or a maybe redirect to another page?

def final_step(request):
    code
= request.GET['code']
    r
= requests.post('https://<canvas-install-url>/login/oauth2/token', {'code': code, 'client_id': 'etc'}
    access_code
= r.json()['access_code']
   
return HttpResponse('Successfully Logged in! Here's your access_code: %s' % access_code)

Collin

On Sunday, January 18, 2015 at 7:01:12 PM UTC-5, Henry Versemann wrote:
Collin, thanks for the help. My django application as it is already has the "requests" library installed within it and I have already registered it with the API which I'm trying to authenticate to currently using that API's oauth2 web application flow, which is a three step process (see the oauth2 tab for the  Canvas API). I'm able so far to send a redirect-uri to the Canvas Oauth2 api and have it respond back to me with all of the other information I need to get my final access token from then. My application currently uses Python 2.7.8 and Django 1.7 and the piece of the process that I'm having the problem with is sending the final POST request back to the Canvas Oauth2 flow API. The response that up to now I've tried to return back from my django view  has been an HttpResponse which apparently does not allow the sending of a POST request. I've also taken a look at all of the shortcut functions that django offers as options to return back from django views, and none of them appear at least not obviously to offer any options for sending POST requests. Your response below seems to show how I might get the access token back from the final POST request which I need to make to the Canvas Oauth2 flow. Can you show me how to do that POST, and what I need my view to return, to avoid getting and error which says that my view did  not return a valid HttpResponse but instead returned "None" like I've gotten up until now?
Thanks again for the help.

Henry 

On Saturday, January 17, 2015 at 7:33:40 AM UTC-6, Collin Anderson wrote:
Hi,

Use urllib/urllib2 or requests to POST to other websites. Python can do it natively.

try:  # Python 3
   
from urllib import request as urllib_request
except ImportError:  # Python 2
   
import urllib2 as urllib_request
from django.utils.http import urlencode

def my_view(request):
    response
= urllib_request.urlopen('https://endpoint/', urlencode({'mytoken': '12345'}))
    data
= response.read()
   
# etc


or install requests, which is friendlier:

Collin

On Thursday, January 15, 2015 at 11:51:45 AM UTC-5, Henry Versemann wrote:
First let me say that I haven't done a lot of stuff with either Python or Django, but I think I understand most of the basics. 
I am trying to get an access token back from the OAuth2 Web Application Flow of the Canvas' LMS API ( https://canvas.instructure.com/doc/api/file.oauth.html ).
I have successfully sent the request in step 1 of the flow, and received back and extracted out of the response all of the data needed for step 3, which came back in step 2 of the flow.
So now in step 3 of the flow my problem is how to send a POST of the request needed, as described in step 3 of the flow, from a Django View.
I've not found anything definitive saying that I absolutely can't do a POST of a request, from a Django View, and have seen some  items which seem to indicate that I can do a POST from a view, but none of them seem to have detailed code examples or explanations of how to do it if it is possible.
So far I've tried several ways of sending the POST within a returned HttpResponse and have not been successful, and if I understand things correctly HttpResponse doesn't allow it. 
I have also looked at all of the other Django Shortcut Functions documentation, and none of them seem to offer any obvious way of POSTing a request either. 
Can someone please point me to a good example of how to do it if it is possible, and if it is not maybe point me to one or more examples of how I might be able to successfully go through the Canvas OAuth2 Web Application Flow using some other module or package, that I can integrate into my Django application?
Thanks for the help.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/35093689-74ef-4d52-b0df-8a1dd89bc60c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.