Empty context within template tag render() method after using django.test.client.Client.login() method

2013-09-22 Thread jondbaker
Within my integration tests, it appears that after using the login() method 
of django.test.client.Client the context dict consists only of: 

[{'False': False, 'None': None, 'True': True}, {}, {}].

If I remove the use of login(), then the request dict consists of:

[{'False': False, 'None': None, 'True': True}, {'object': , 'user': , u'view': 
}, {u'csrf_token': 
}, {'perms': 
, 
'user': }, 
{}, {u'MEDIA_URL': '/media/'}, {'messages': 
}, {u'request': ,
POST:,
COOKIES:{'sessionid': 'q27przqeidsnfykuufu7m6lo7nw606qw'},
META:{u'CONTENT_TYPE': 'text/html; charset=utf-8',
 u'CSRF_COOKIE': u'9mWW7nGMJQAgbs3KBB3oEPofbLBCkLW2',
 u'HTTP_COOKIE': u' sessionid=q27przqeidsnfykuufu7m6lo7nw606qw; 
Domain=None; expires=None; Max-Age=None; Path=/; secure',
 u'PATH_INFO': u'/accounts/',
 u'QUERY_STRING': '',
 u'REMOTE_ADDR': '127.0.0.1',
 u'REQUEST_METHOD': 'GET',
 u'SCRIPT_NAME': u'',
 u'SERVER_NAME': 'testserver',
 u'SERVER_PORT': '80',
 u'SERVER_PROTOCOL': 'HTTP/1.1',
 u'wsgi.errors': <_io.BytesIO object at 0x2358050>,
 u'wsgi.input': ,
 u'wsgi.multiprocess': True,
 u'wsgi.multithread': False,
 u'wsgi.run_once': False,
 u'wsgi.url_scheme': 'http',
 u'wsgi.version': (1, 0)}>}, {u'STATIC_URL': '/static/'}, {}]

I noticed the problem when a template tag was trying to access 
context["request"].path and a KeyError was raised after using login. Both 
outputs above are the result of printing the context var from within the 
render() method of a template tag. Any help would be greatly appreciated, 
as I'm a bit stumped.

Thanks,
Jonathan

-- 
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+unsubscr...@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.
For more options, visit https://groups.google.com/groups/opt_out.


URL is successfully reversed and then not found

2013-04-10 Thread jondbaker
I'm working on tests for a Django app that I'm contributing to the 
community (https://github.com/jondbaker/django-critique) and have become 
stuck on a problem. After I perform a GET request for the app's sole URL 
within my integration tests:

response = self.client.get(reverse("critique_create"))

The response.status_code is 404 and the content:

"The requested URL /critique/create/ was not found on this server."

As you can see, the URL is being successfully reversed, but then it 404s. 
I've created a separate test URL/view/template that plays nicely, but I 
can't figure out what's going on with the /critique/create/ URL.

Any help would be greatly appreciated.

*tests/urls.py*
try:
from django.conf.urls import include, patterns, url
except ImportError:  # django < 1.4
from django.conf.urls.default import include, patterns, url

from .views import TestView

urlpatterns = patterns(
"",
url(r"^test/$", TestView.as_view(), name="test_view"),
url(r"^", include("critique.urls")),
)

*critique/urls.py*
try:
from django.conf.urls import patterns, url
except ImportError:  # django < 1.4
from django.conf.urls.default import patterns, url

urlpatterns = patterns(
"",
url(r"^critique/create/$", "critique.views.create", 
name="critique_create"),
)

-- 
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+unsubscr...@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?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.




psycopg2.DataError

2012-10-30 Thread jondbaker
When I run 'python manage.py validate' the following error is returned:

*psycopg2.DataError: invalid value for parameter "TimeZone": "UTC"*
*
*
settings.py
TIME_ZONE = 'America/Denver'
USE_TZ = True

I'm using Django 1.4.2 with Postgres 9.1/PostGIS on OSX.

To test, I went back and commented out my custom apps in INSTALLED_APPS, 
but the error is still there. If I set USE_TZ to False, then the error 
becomes:
*psycopg2.DataError: invalid value for parameter "TimeZone": 
"America/Denver"*

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/zi-34uY9WKMJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Django-SEO issue

2012-08-17 Thread jondbaker
I've successfully installed Django-SEO, but when I try to limit the number 
of backends (I only need/want my admin to have 'path' and not the other 
three) I am met with the following error:
AttributeError at /admin/'NoneType' object has no attribute '_meta'

I am using the documentation here: 
http://django-seo.readthedocs.org/en/latest/reference/definition.html#Meta.backends

*seo.py*
from rollyourown import seo

class AppMetadata(seo.Metadata):
title = seo.Tag(head=True, max_length=68)
description = seo.MetaTag(max_length=155)

class Meta:
backends = ('path',)
#backends = ('path', 'modelinstance', 'model', 'view',) This works 
but includes all default backends

*admin.py*
from django.contrib import admin
from rollyourown.seo.admin import register_seo_admin

from localsite.seo import AppMetadata

register_seo_admin(admin.site, AppMetadata)

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/B1W0iR7aNokJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



TinyMCE config

2012-08-01 Thread jondbaker
I'm trying to install django-tinymce so that I can use utilize it within 
the admin when editing flatpages and flatblocks. I've been following the 
instructions at 
http://django-tinymce.readthedocs.org/en/latest/installation.html, but I 
can't seem to get TinyMCE to display. django-tinymce has been installed via 
pip, and here are the relevant snippets of code:

*settings.py*
INSTALLED_APPS = (
...
'tinymce',
)
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
TINYMCE_JS_URL = os.path.join(PROJECT_ROOT, 
'templates/static/js/tiny_mce/tiny_mce.js')
TINYMCE_JS_ROOT = os.path.join(PROJECT_ROOT, 'templates/static/js/tiny_mce')
* I have a hunch that here is where I'm going wrong. The instructions 
indicate that the tiny_mce js dir should reside in MEDIA, but I was under 
the impression that MEDIA is to be used for user-uploaded content, while 
STATIC is for assets like JS and CSS. That's why I put the tiny_mce lib in 
STATIC instead of MEDIA.
*
urls.py*
urlpatterns = patterns(''
...
url(r'^tinymce/', include('tinymce.urls')),
)
* If i visit 'http://127.0.0.1:8000/tinymce/flatpages_link_list/' in the 
browser, 'var tinyMCELinkList = []' is rendered.

Any help would be greatly appreciated. Thanks.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/LzurKyPvBdAJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Return SQL calculation within queryset

2012-07-24 Thread jondbaker
I've implemented the spherical law of cosines to aid in proximity-based 
searching. Everything works correctly, but I'm a bit stumped as to how I 
can return the calculated distance for a record given that it's not a field 
in the model. In the Model Manager below, row[1] represents the dynamically 
calculated distance, but I need to find a way to "attach" each calculation 
to it's corresponding record so that I can print the distance in a template.

class LocationManager(models.Manager):
'''
'''
def nearby_locations(self, latitude, longitude, radius):
'''
'''
cursor = connection.cursor()
if settings.DATABASES['default']['ENGINE'] == 
'django.db.backends.sqlite3':
# sqlite doesn't natively support math functions, so add them
connection.connection.create_function('acos', 1, math.acos)
connection.connection.create_function('cos', 1, math.cos)
connection.connection.create_function('radians', 1, 
math.radians)
connection.connection.create_function('sin', 1, math.sin)

sql = """SELECT id, (3959 * acos(cos(radians(%f)) *
  cos(radians(latitude)) * cos(radians(longitude) - 
radians(%f)) +
  sin(radians(%f)) * sin(radians(latitude
  AS distance FROM locations_location
  GROUP BY id HAVING distance < %d
  ORDER BY distance ASC""" % (latitude, longitude, latitude,
  int(radius))
cursor.execute(sql)
data = [(row[0], row[1]) for row in cursor.fetchall()]
ids = [i[0] for i in data]
return self.filter(id__in=ids)

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/pfZSZB1nLVIJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Saving test user as a foreign key in unit tests

2012-04-11 Thread jondbaker
Problem solved. Within my view I needed use the following:

def create_tasting(request):
if request.method =='POST':
form = TastingForm(request.POST)
if form.is_valid():
*obj = form.save(commit=False)*
*obj.author = request.user*
*obj.save()*
return HttpResponseRedirect('/tastings/')
else:
form = TastingForm()
return render_to_response('tastings/create.html', {
'form': form
}, context_instance=RequestContext(request))

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/Q6I4oSuCsTIJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Saving test user as a foreign key in unit tests

2012-04-11 Thread jondbaker
I have a Tasting model with an 'author' field that is a ForeignKey to the 
User model. Within my unit test I'm attempting to create a test user, and 
pass that user object as the author of a test Tasting, but I keep getting 
the following error: "IntegrityError: tastings_tasting.author_id may not be 
NULL"

*models.py*
class Tasting(models.Model):
notes = models.TextField(blank=True)
author = models.ForeignKey(User, editable=False)

*forms.py*
class TastingForm(ModelForm):
class Meta:
model = Tasting

*views.py*
def create_tasting(request):
if request.method =='POST':
form = TastingForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/tastings/')
else:
form = TastingForm()
return render_to_response('tastings/create.html', {
'form': form
}, context_instance=RequestContext(request))

*test_views.py*
class TestPostCreateTasting(TestCase):
def test_auth_response_valid_data(self):
client = Client()
user = User.objects.create_user('test', 't...@test.com', 
'testPassword')
client.login(username='test', password='testPassword')
tasting = {
'notes': 'What a great beer',
'author': user,
}
response = client.post('/tastings/create/', tasting)
self.assertEquals(response.status_code, 200)
tastings = Tasting.objects.all()
self.assertEquals(len(tastings), 1)
client.logout()

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/tSmxysZVgYAJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



django.contrib.auth.views.login no response

2012-03-28 Thread jondbaker
I'm trying to build a login form by following the instructions on this page 
https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.views.login.
 
The form is rendered in the template with a username and password field, 
but the hidden "next" field has no value, the form does not return error 
messages and there's no response on submit. Here is my code:

*urls.py*
urlpatterns = patterns('',
url(r'^accounts/login/$', 'django.contrib.auth.views.login', {
'template_name': 'accounts/login.html'
}
)

*templates/accounts/login.html*
{% extends 'base.html' %}
{% load url from future %}

{% block content %}

{% if form.errors %}
Your username and password didn't match. Please try again.
{% endif %}


{% csrf_token %}

{{ form.username.label_tag }}
{{ form.username }}


{{ form.password.label_tag }}
{{ form.password }}





{% endblock %}

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/g3sCK82eI0gJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: TestCase Client.login() fails

2012-03-28 Thread jondbaker
Thanks for all the responses. I actually solved the problem about 15 
minutes after posting this question and indicated so in the first reply. 
Perhaps that reply did not go out in time? Anyway, thanks for the help!

On Wednesday, March 28, 2012 1:28:56 AM UTC-6, rudyryk wrote:
>
> Hello, Jonathan!
>
> I think issue is in the fragment 'password=user.password' in the line:
>
> > response = self.client.login(username=user.username,
> > password=user.password)
>
> 'user.password' - is not plain text password, it's encrypted and it's
> not equal 't3stp@s$' !
>
> Alexey rudyryk
> ///
>
> On Wed, Mar 28, 2012 at 10:05 AM, jondbaker
> <jonathandavidba...@gmail.com> wrote:
> > I'm trying to write a unit test that will verify that the login form
> > authenticates a user. Whenever I run 'manage.py test' the runner fails 
> with
> > this message:
> > AssertionError: False is not True
> >
> > tests.py
> > from django.test import TestCase
> > from django.test.client import Client
> > from django.contrib.auth.models import User
> >
> > class TestAccountLogin(TestCase):
> > def setUp(self):
> > self.client = Client()
> >
> > def test_login(self):
> > user = User.objects.create_user('test', 't...@test.com', 
> 't3stp@s$')
> > response = self.client.login(username=user.username,
> > password=user.password)
> > self.assertTrue(response)
> >
> > After creating the user, I can verify that user.is_active is in fact 
> True,
> > but unfortunately response returns False. Both
> > 'django.contrib.auth.middleware.AuthenticationMiddleware' and
> > 'django.contrib.auth' are declared in settings.py.
> >
> > Any thoughts?
> >
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Django users" group.
> > To view this discussion on the web visit
> > https://groups.google.com/d/msg/django-users/-/5zI85qKS4acJ.
> > To post to this group, send email to django-users@googlegroups.com.
> > To unsubscribe from this group, send email to
> > django-users+unsubscr...@googlegroups.com.
> > For more options, visit this group at
> > http://groups.google.com/group/django-users?hl=en.
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/-urgiz-8OQwJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: TestCase Client.login() fails

2012-03-28 Thread jondbaker
Problem solved. I forgot that .create_user will create and return a hashed 
password, which obviously won't work if said returned object password 
property is entered into the password field of the login form.

On Wednesday, March 28, 2012 12:05:49 AM UTC-6, jondbaker wrote:
>
> I'm trying to write a unit test that will verify that the login form 
> authenticates a user. Whenever I run 'manage.py test' the runner fails with 
> this message:
> *AssertionError: False is not True*
>
> *tests.py*
> from django.test import TestCase
> from django.test.client import Client
> from django.contrib.auth.models import User
>
> class TestAccountLogin(TestCase):
> def setUp(self):
> self.client = Client()
>
> def test_login(self):
> user = User.objects.create_user('test', 't...@test.com', 
> 't3stp@s$')
> response = self.client.login(username=user.username, 
> password=user.password)
> self.assertTrue(response)
>
> After creating the user, I can verify that user.is_active is in fact True, 
> but unfortunately response returns False. Both 
> 'django.contrib.auth.middleware.AuthenticationMiddleware' and 
> 'django.contrib.auth' are declared in settings.py.
>
> Any thoughts?
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/6PqfFCkJUz0J.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Need help creating model.

2012-03-28 Thread jondbaker
I think the Foreign Key route is the way to go. After setting up the fields 
on both the Student and Point models and establishing the FK relationship 
between the two, you could write a table-level method that returned the 
number of corresponding Points.

On Tuesday, March 27, 2012 7:18:12 PM UTC-6, Zach wrote:
>
> I have the following in my Student model. I am wanting to track the 
> date of each point given to each student. The idea would be so that I 
> could see not only how many points each student has, but also see the 
> date each point was given. In the future I want to see the trend of 
> each students' points.   How should I go about this? Should I use a 
> Foreign Key in another class. I am new to this so thanks for reading. 
>
>
> class Student(models.Model): 
>
>   CLASS_CHOICES = ( 
> (u'Yoga','Yoga'), 
> (u'Spanish', 'Spanish'), 
> (u'French', 'French'), 
> (u'Dance', 'Dance'), 
>   ) 
>
>   name = models.CharField(max_length=30) 
>   points = models.IntegerField(max_length=4) 
>   classname = models.CharField("Class Name",max_length=20, choices = 
> CLASS_CHOICES) 
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/sV-KrZWV8KMJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



TestCase Client.login() fails

2012-03-28 Thread jondbaker
I'm trying to write a unit test that will verify that the login form 
authenticates a user. Whenever I run 'manage.py test' the runner fails with 
this message:
*AssertionError: False is not True*

*tests.py*
from django.test import TestCase
from django.test.client import Client
from django.contrib.auth.models import User

class TestAccountLogin(TestCase):
def setUp(self):
self.client = Client()

def test_login(self):
user = User.objects.create_user('test', 't...@test.com', 't3stp@s$')
response = self.client.login(username=user.username, 
password=user.password)
self.assertTrue(response)

After creating the user, I can verify that user.is_active is in fact True, 
but unfortunately response returns False. Both 
'django.contrib.auth.middleware.AuthenticationMiddleware' and 
'django.contrib.auth' are declared in settings.py.

Any thoughts?

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To view this discussion on the web visit 
https://groups.google.com/d/msg/django-users/-/5zI85qKS4acJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Django ManyToManyField JSON Fixture

2012-01-28 Thread jondbaker
Hi - I'm working on my first Django project and am trying to set up
the fixture data for my blog app using JSON. Everything works
correctly until I try to set up 'tags' on a 'post' which is a
ManyToManyField. When I run '>>> python manage.py sqlall blog' and
check out the proposed SQL, the table 'blog_post_tags' is listed and
defined correctly. However, when I try to run '>>>python manage.py
syncdb' I am met with the error: 'DatabaseError: no such table:
blog_post_tags'.

model:
class Tag(models.Model):
title = models.CharField(max_length=30)
date_created = models.DateField(auto_now_add=True)
date_updated = models.DateField(auto_now=True)

class Post(models.Model):
...
tags = models.ManyToManyField(Tag)
...

fixture:
[{
"model": "blog.Post",
"pk": 1,
"fields": {
"title": "Demo Post 1",
"category": 3,
"tags": [1],
"body": "This is a sample body.",
"is_published": "1",
"date_created": "2012-01-28",
"date_updated": "2012-01-28"
}
}]

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Parsing HTML

2012-01-28 Thread jondbaker
Thanks, that's good to know. I'm just a few months into using Python
(and weeks with Django), hence the familiarity with that one book and
not real-world application just yet.

On Jan 28, 9:45 am, Masklinn <maskl...@masklinn.net> wrote:
> On 2012-01-27, at 23:40 , jondbaker wrote:
>
> > Chapter 8 of Dive Into Python demonstrates what you're describing
> > using sgmllib.
> >http://www.diveintopython.net/
>
> None of these libraries is very good at parsing "real-world" (broken) HTML 
> though, for that you'd better go with html5lib, lxml.html or BeautifulSoup 
> (in decreasing order of recommendation, lxml.html is probably the fastest but 
> I don't think it implements the HTML5 parsing rules)

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.



Re: Parsing HTML

2012-01-28 Thread jondbaker
Chapter 8 of Dive Into Python demonstrates what you're describing
using sgmllib.
http://www.diveintopython.net/

On Jan 27, 3:31 pm, Dennis Lee Bieber  wrote:
> On Fri, 27 Jan 2012 13:35:42 +0700, ddtopgun  wrote:
> >i'am new to django and i want to try get the content of HTML.
> >can help me how to get the content of html.
>
>         
>
>         Django is meant to generate HTML pages, not parse HTML content.
>
> >f=urllib.request.urlopen("http://site_name.com;)
> >s=f.read()
> >f.close()
>
> >but the code is display all code html. i want to just take the contents
> >of tag html.
>
>         You'll have to do better to define "contents". Only stuff inside
>  tags (and you then may have to worry about old HTML that doesn't
> using closing  tags)? Is an image reference (  src="somefile.name"> ) content or only the text between the tags?
>
>         If the HTML is well-formed, you might be able to use ElementTree to
> traverse the nodes. Or define callbacks for HTMLParser or htmllib (see
> section 19 [for Python 2.7]: Structured Markup Processing in the
> Standard Library reference manual) to capture the portion in which you
> are interested.
> .
> --
>         Wulfraed                 Dennis Lee Bieber         AF6VN
>         wlfr...@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.