Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
After .96 all html gets escaped, you need to disable auto-escaping.
See here.

Adbot
ADBOT LOVES YOU

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
Try switching the 0 and 1 to true and false, maybe it forgets to do a type check before turning it into a string. Not sure if SQLite shits itself when you try to set a boolean field to 0 or 1.


also what the christ self._aligns.keys().index(chunks[14]) is just self._align[chunks[14]].

deimos fucked around with this message at 21:45 on Apr 19, 2008

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

ImJasonH posted:

Which 0 and 1s? The only boolean field I have is already set with True and False.

_aligns is a dictionary, and I need to store the index of the matching key, not the value of it. It's a dictionary because later on when I output the results I'll want the full value and not the abbreviated one that's in the logs.

Dict key order is not guaranteed between implementations so you might want to rethink that strategem, make it into a multi-dimensional list. There's no need to turn this data into a number when a 3 character string will do, if you want to normalize normalize right but if you're gonna keep your data denormalized at least do so in a legible manner.

I jumped to conclusions with the 0/1 thing.

Try making the fields of a less restrictive type and see (ie. PositiveInteger instead of PositiveSmallInteger) it might be a bug in the backend.

Your code somewhat stinks of SAVAGELY OPTIMIZED overtones.

deimos fucked around with this message at 23:52 on Apr 19, 2008

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

ImJasonH posted:

You're probably right, I could probably save myself a lot of trouble by just storing strings in the database instead of ints. In fact, yeah, I'm going to tweak this some and simplify.

I am not against storing ints where ints are due, but making them small or large really isn't saving you a lot. Still I'd love to know if it's some sort of backend issue with django so that a proper ticket can be opened.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

jarito posted:

Sounds great. That should tide me over until the schema gets a little more definite. Got another stupid admin question. I have this in my models.py:

But for some reason, the Admin interface still requires that I select an emergency_contact, even though it is marked as nullable (both in the models.py and the database). I was using this example which has this code:


Am I going about this the wrong way?

generally speaking you don't want nulls in tables, it does funky stuff with some queries and generally acts weird depending on implementation.

As to your problem, you also need blank=True. blank controls Admin.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

king_kilr posted:

Not for much longer! On This Week in Django(great podcast), Malcom Tredinick(core commiter), said queryset-refactor will be getting merged sometime this week/next week, that branch fixes tons of SQL construction issues(including NULLS, joins, and about a billion other things).

Ohh lordy lordy, this is excellent news.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

king_kilr posted:

And queryset-refactor just hit trunk: http://code.djangoproject.com/changeset/7477 YAY!

Quite possibly the best merge since the magic removal branch hit trunk.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Bonus posted:

:words:


code:
python manage.py sqlreset
python manage.py loaddata data

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Wulfeh posted:

code:
def clean(self):
	if 'bool_field' in self.cleaned_data:
		if self.cleaned_data['bool_field']:

Gah, this is a pet peeve of mine, it's a bit wasteful and IMO makes it harder to read when you have a single method that does both: self.cleaned_data.get('bool_field', False) works fine to replace both of those.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Sock on a Fish posted:

I've Googled around, and can't find an answer -- is there any significant performance boost from using a SmallIntegerField in my models instead of an IntegerField? One of my models is going to have about 100 attributes, only a handful of which are going to be negative or possibly exceed 65,535. However, I'd rather not make my model less flexible unless I'm going to get something for it.

Performance? none. The advantage comes when you have millions (or even billions) and it nets you a slight storage improvement.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
make sure you're using .97 (SVN) otherwise Admin won't work right with unicode.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

StickBoy posted:

TypeError at /admin/main/name/4/
Cannot resolve keyword 'name' into field

Here is my model for it:
code:
<snip>

Are you using postgreSQL by any chance?

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
Does anyone have any good resources for running django on CentOS under WSGI? I am having trouble getting it to work.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Space Kimchi posted:

I managed to get apache/modpython working on CentOS but I'm starting to regret it a little as it likes to do things like cache error messages and never ever let them go (although restarting apache seems to clear things up). I can't find any information on where the cache is or how it works or how to tweak or disable it, it's kind of frustrating :(

It's not "not letting them go" each apache child has it's mod_python which has it's corresponding copy of the source running, you have to apache2ctl force-reload (pretty sure force-reload works, but might actually need a restart).

This is why if you make a site-breaking mistake it can take several refreshes to reflect it on Apache.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Git posted:

Sounds like you guys need to play with Apache's MaxRequestsPerChild option. I'm pretty sure the Django docs recommend giving it a value of 1 for development so code changes are reflected instantly.

I don't even use apache for development. I use ./manage.py runserver <ip>:8000 when testing the mod_python config I just /etc/init.d/apache2 restart on the test install if I made a mistake then pushed live.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

king_kilr posted:

new docs stuff just hit django, you can check out the hotness at http://docs.djangoproject.com/

I can't say I like this presentation better than the other. The old version was a bit clearer to me. Took me a while to even begin looking for the templates reference. (And there are like 5 links for templates)

More gripes:
Still no official signals documentation.
Still no clear "views" docs other than the stuff intermixed in the tutorial.
Still no middleware dev docs.


I do like that it has breadcrumbs now and that the template docs are slightly more organized.

deimos fucked around with this message at 09:54 on Aug 24, 2008

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

bitprophet posted:

There are clear "views" docs, the deal is that views are just Python functions...ones that take in requests and return responses, and thus the request/response docs are what you actually want.

Middleware dev docs: right here :)

While I agree that the "views" docs are the request/response docs, it's not as easy for a newbie, can't just tell them "look at the request/response docs".

With regards to the middleware docs: So that's where they went. I knew they were there before, now it's 3 clicks in with no reference to them within the front page. Usability overall of this iteration of the docs is... meh.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
I love django. I was asked to make a CSV available of data for a date. Took less than 20 lines of code, illustrated here so that if anyone wants to use it they can (and if they can come up with a better way of doing the info_dicts they can tell me, I feel it's ugly):

code:
### urls.py
shared_info_dict = {
	'queryset' : Entity.objects.all(),
	'date_field' : 'updated',
	'mimetype':'text/csv',
	'template_name' : 'question.csv',
}
info_dict = dict(shared_info_dict)
info_dict['month_format'] = '%m'

year_info_dict = dict(shared_info_dict)
year_info_dict['make_object_list'] = True

urlpatterns += patterns('django.views.generic.date_based',
   (r'^csv/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\w{1,2})/$', 'archive_day',
        info_dict),
   (r'^csv/(?P<year>\d{4})/(?P<month>[0-1]\d)/$','archive_month', info_dict),
   (r'^csv/(?P<year>\d{4})/$','archive_year',  year_info_dict),
)
code:
#question.csv
&#65279;"ColA","ColB","ColC"
{% for row in object_list %}"{{ row.a|addslashes }}", "{{ row.b|addslashes }}", 
"{{ row.c|addslashes }}"
{% endfor %}
Note: question.csv needs to have a BOM as the first character otherwise Excel will poo poo itself on unicode characters. Also, I broke the lines here but not in the file itself.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Milde posted:

I don't think it handles what he's talking about by default, but he could use a custom dialect/writer like this: http://www.djangosnippets.org/snippets/993/

Nice link. And yeah the default CSV sucks at utf-8, I got tired of hacking it on a previous project so I went for the common case since everyone that's gonna use the app is gonna use it with excel. It was hacky but ffffff that.

Also technically what I would need to write is a custom template filter and/or loader if I wanted to still use generic views, which was part of the point of this exercise.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
:woop:

FINALLY got django working with MS SQL Server from a CentOS host.

Recipe:
code:
sudo yum -y install unixODBC unixODBC-devel freetds freetds-devel
Edit /etc/freetds.ini and add (should only need to uncomment):
code:
[MyServer]
  host = myserver.domain.com
  port = 1433
  tds version = 8.0 
  client encoding = UTF-8
Edit /etc/odbcinst.ini and add:
code:
[TDS]
Description = FreeTDS Driver
Driver = /usr/lib/libtdsodbc.so
Setup = /usr/lib/libtdsS.so
UsageCount = 1
Edit /etc/odbc.ini and add:
code:
[MyServerDSN]  <--- rename that to whatever you want, but this is gonna be your DSN
Description = My DSN (call this whatever I want)
Driver = TDS (SAME AS THE LABEL ABOVE in obdcinst.ini)
Database = my_database
ServerName = MyServer (SAME AS THE LABEL ABOVE in freetds.ini)
code:
mkdir ~/tmp
cd ~/tmp
wget [url]http://internap.dl.sourceforge.net/sourceforge/pyodbc/pyodbc-2.0.58.zip[/url]
unzip pyodbc-2.0.58.zip
cd pyodbc-2.0.58
sudo python setup.py build
sudo python setup.py install
mkdir -p /usr/local/lib/python/
cd /usr/local/lib/python/
svn co [url]http://django-pyodbc.googlecode.com/svn/trunk/[/url] django-pyodbc
cd django-pyodbc
wget -O utf.patch "http://pastebin.com/pastebin.php?dl=f606eb107"
patch -p0 < utf.patch
Afterwards just add /usr/local/lib/python/django-pyodbc to your PYTHONPATH variable (I do it in httpd.conf for wsgi). Create a new project change settings.py according to the django-pyodbc homepage.

Adapted to the names above:
code:
DATABASE_ENGINE = 'sql_server.pyodbc'
DATABASE_ODBC_DSN = 'MyServerDSN'
DATABASE_ODBC_DRIVER = 'FreeTDS' # ODBC driver name, 
                                 # TDS works too because that's how we defined it above.
DATABASE_ODBC_EXTRA_PARAMS='' 
DATABASE_NAME = 'my_database'
DATABASE_USER = 'user' #whatever
DATABASE_PASSWORD = 'pass' #whatever
DATABASE_HOST = 'myserver.domain.com' # actual host, pyodbc is pretty stupid about FreeTDS, 
                                      #I might be wrong
DATABASE_PORT = '' # leave blank for default
Links:
django-pyodbc - This site is almost empty of content.
pyodbc - Has documentation of all the wrong things.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

The Real Ambassador posted:

I dare you to get blob fields to work.

One more thing to test. I've been running through django's test suite trying to fix stuff.

bitprophet posted:

It's not just the admin -- if you're still using oldforms at all, that's out the window now (but good riddance!). Hopefully not, I think regular newforms hit trunk like a year+ ago, and it's just newforms-admin that hit more recently. It's all a blur at this point, I've seen so many big changes to the codebase I can't keep it straight :downs:

Again, just skim down that list on the wiki page, it'll give you a good idea.

queryset-refactor bit me in the rear end even though I thought it was gonna be transparent.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Senso posted:

I know that but as you can see, I didn't take chances. PythonPath is defined in the VirtualHost Apache definition but I also defined it in bash, just to make sure.


Right, in the code I pasted, /home/mlan/proj was the Django root. /home/mlan/proj/myproject was the actual project. I read about that and I knew that I shouldn't give it the path of a single project.

It probably was permissions after all. But the thing is, the django folders in /opt and in /home/mlan have the same permissions... And I'm a loving Linux sysadmin, I'm ashamed! Oh well, it works now.

Sticky bit strikes again!

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

NadaTooma posted:

I'm about to start a new project, and trying to decide if I should use the built-in authentication system vs. rolling my own. I want two different account types: One for adults (requiring e-mail validation), and one for kids (no e-mail required), where each child's account is tied to one or more parent accounts, so that a parent can change manage their son or daughter's setup. This would imply a many-to-many relationship in the original Django "User" table, and I'm not sure it's designed for that. If I roll my own, I'm actually considering making it two tables (one for each account type), just to keep the DB design simpler. The built-in administrative pages, while awesome, aren't an issue here, because I'll be the only person using them in this case.

Any thoughts? Roll my own, or start hacking the hell out of the built-in authentication system?

You could inherit User into an AdultUser and ChildUser model and use them that way.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
While I dislike the mascot choice (a pink pony?) this is a neat representation.

mwarkentin posted:

You know the pink "magical pony" thing is a joke, right?

It's a djangocon thing.

deimos fucked around with this message at 23:05 on Sep 15, 2008

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

dimebag dinkman posted:

The Django docs make a big deal out of the fact that you shouldn't serve static files through Django. That makes sense, but what if I want to only allow the download of a large static file for people authenticated and in a certain group etc.? Is there actually any satisfactory way of having Django handle a request initially, and then have it pass control over the fastest method available to send a static file? (I'm using lighttpd + FastCGI, currently.)

http://trac.lighttpd.net/trac/wiki/Docs:ModSecDownload

http://wiki.codemongers.com/NginxXSendfile


Basically you change the headers and shazzam proxied download. (actually lighty's is a bit more complicated but who cares, use nginx)

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

duck monster posted:

Mod python

gently caress mod_python TBH. Seriously, don't use it.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Milde posted:

deimos obnoxiously alluded to it

Eh? how was I obnoxious? I gave him relevant links and gave a very concise explanation of how the technique works (for nginx), neither link lacked explanations as to how they worked so there was no need to write :words:.


bitprophet posted:

To be fair, use of WSGI, with any server (i.e. mod_wsgi with Apache, or whatever the nginx equiv is) is becoming more popular lately, and a decent number of people also use FCGI.

WSGI is the best thing for hosting django apps. The only problem is that the django devs say it's the best way to host django apps (just go to #django or the django-users mailing list), but it seems they don't want to put it on the docs because not all web servers have WSGI available to them.

There are very few reasons to use mod_python, and none of them really make sense to me, because most of them involve using parts of Apache that are normally not exposed to web apps. I would personally forego apache/django and switch to twisted/nevow for that degree of control, or, I would separate the things that require you to control apache into their own applications. But I can see a very small subset of projects needing it.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

bitprophet posted:

duck monster posted:

Set it up so that if it 404s , it will fall back to the code that generates the image, which would then serve the image up for it (and supress the 404 code from being sent to the browser, because thats bad mojo) and then in future django wouldnt even need to be hit for it.
This isn't really possible with Django, insofar as you have to load up Django at least a little bit before Django can know whether it's needed! But, as above, you can have Django skip the image creation code unless a new image needs to be generated, which will still be a big time saver. (Yes, you could write a new mod_python handler or modify Django's default one, but I'm guessing that's a bit over ijustam's head if he's still not 100% comfortable with HttpRequests :))

If you have lighty or nginx in front of django (which you should) you can still allow them to serve the graphic by using the header trickery I posted a while back for sending FS files.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

hitze posted:

code:
				{% for Song in song_results %}
I can't seem to get the songs to list or get called, so i'm hoping i'm missing something that should be really obvious. Any help would be appreciated :)

try
code:
				{% for Song in Album.song_set %}

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

bitprophet posted:

:words:

Thanks for actually verbalizing my post. I didn't have time to write a full answer when I posted that.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

hitze posted:

Well after rereading the docs for models and page 3 of the tutorial (for the upteenth time) I came up with this:

Gah, go back and re-read the tutorial and documentation, specifically this page.

1. Why do you insist on setting the albums and songs to a variable.
2. Why are you using get() when stuff might return more than one value? You use get to get a single instance.


For #1 you do not need to be declaring all those variables on your view.

Try this as your view:
code:
def artist_page(request, artist_slug):
	artist = get_object_or_404(Artist, Slug=artist_slug)
	return render_to_response('main/artist_page.html',
		{
			'artist_results': artist,
		},
		context_instance = RequestContext(request)
		)
And this for your template:
code:
{% for Album in artist_results.album_set %} 
	{{ Album.Name }}
	{% for Song in Album.song_set %} 
		{{ Song.Name }}
	{% endfor %}
{% endfor %}

quote:

code:
AttributeError at /artist/led-zeppelin/
'Album' object has no attribute 'album_set'

That's because Album indeed does not have an album_set; artist has an album_set and each album in the album_set has a song_set.

deimos fucked around with this message at 17:31 on Nov 16, 2008

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
:argh: THEY CHANGED THE DOCS INDEX PAGE AGAIN

You're gonna have to create a custom field (inherit from forms.ModelChoiceField) or use a form validator on whichever form you use to create the categories. All you have to do is check that the id field of the object doesn't match the foreign key id.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

The Red Baron posted:

My seemingly decently elegant django.contrib.comments signal-based reCAPTCHA implementation, which I posted a link to earlier in this thread, suddenly got some serious egg on its face when someone pointed out that the comment framework's signal handling only allows for returning a HTTP 40x error when a signal handler returns false rather than redisplaying the form with a message. As a result, people mistyping the captcha get some seriously crappy feedback (or lack thereof). For reference, here's the link.

Is there no way of handling this with the current framework without subclassing the comments form and implementing custom logic? I was hoping that wouldn't be necessary :(

You could monkeypatch CommentForm.__new__ to apply a decorator on the security_errors function to check for recaptcha errors.

deimos fucked around with this message at 18:16 on Dec 10, 2008

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
Washington Times just released some pretty awesome django projects:
http://opensource.washingtontimes.com/blog/post/coordt/2009/02/washington-times-releases-open-source-projects/

edit: Forgot to mention that I started playing with django-projectmgr and it is pure awesome.

deimos fucked around with this message at 02:05 on Feb 20, 2009

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
As a sidenote, what's the state of django on Windows? I haven't tried it at all. I need to connect to SQL Server and last I checked the only reliable way was running django on Windows through Apache and :downs: mod_python.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Crazak P posted:

Awesome, thanks man. I knew I had to use divisbleby somewhere, but I was thinking more along the lines of declaring a variable, which I don't think you can using the template language.

The loop variables are really great, make sure you learn them because they're very useful here.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

bitprophet posted:

I saw the feature list for that and basically creamed myself, it's got a LOT of ideas I was hoping to put into a tiny fledgling Django app I have going in the same vein. Plan to check out the source sometime soon.

The source is gorgeous. It's really clean code and from what I have browsed so far, I've already learned a couple of new things.

You actually need to dive into the code to see some of the really neat stuff it does like notifications using django-notification.

Ohh and MPTT is my new most favorite thing ever.

deimos fucked around with this message at 05:45 on Feb 21, 2009

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

king_kilr posted:

Somehow I imagine m0nk3yz jumping straight up to Marty's book within a week.

I picked up Marty's book and I really really like his explanations of django's metaclass voodoo. It never really clicked until I read the chapters explaining it. I mean I sort of got it but it wasn't all there. That alone made it worth the price of admission.

Speaking of metaclass voodoo, now that I actually understand it 100% I am gonna try replacing django's sessions with a redis backend. Should aleviate the DB hammering when using sessions (this is inspired by Cal Henderson's rant about hitting the DB for a session on almost every view).

As an aside, redis is sex.

deimos fucked around with this message at 03:10 on Mar 18, 2009

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

ToxicFrog posted:

I also have a question about mod_python, in case anyone here can answer this: is there a way to turn off cacheing or flush the cache, assuming I don't have root (and thus can't restart apache, which seems to be the 'official' way to do this)? The Django test server is a godsend, because whenever we test it on the deployment server, it's pretty much guaranteed to cache an incomplete or nonworking version of the site and then we have to wait for the cache to expire.

The quick answer: PythonAutoReload On may or may not work.

The correct answer: don't use mod_python, use mod_wsgi.

ToxicFrog posted:

The way I'm currently handling this is that each of these is its own model; Sponsor, Protocol, and PurposeList are each a Model in their own right, with a ForeignKey dependency on RequestForm. The view uses this to retrieve them, splices them into the RequestForm object, and proceeds from there.

So:
- can I move this into RequestForm's __init__() and save() methods, so that it happens automatically when a RF is created from the database/saved to the database and the view doesn't have to worry about it at all, just asking for (say) form.sponsors?
- is this a reasonable design, or am I doing things completely wrong and Django actually has some built in feature to handle things like dictionaries automatically?

I am really not understanding your models, maybe because you keep calling them things that generally conflict with what models are. A model is a model and there should not be List or Form in their classnames IMHO. A Sponsor model is a representation of a sponsor and a Purpose and not a PurposeList should be a representation of a purpose.

That having been said, django does provide you with ModelForms which do all the form dirty work for you. Might want to start there.

deimos fucked around with this message at 05:04 on Mar 18, 2009

Adbot
ADBOT LOVES YOU

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

ATLbeer posted:

MySQL doesn't support hour in it's datetime implementation. :(

I might write up a custom model. I've basically added the logic adhoc in a model manager off a DecimalField.

MySQL has HOUR() which when applied to a datetime value gives you the hour.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply