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
Xenos
Jun 17, 2005

jupo posted:

Anyone have any feedback on hosting django with http://webfaction.com ?

Looking to put my first app up and I've only heard good things about these guys so far.

They have an installer that gives you your own instance of Apache + mod_python or mod_wsgi and the Django trunk. You can stop and start Apache at will. WebFaction is one of the best shared Python hosts out there, in my opinion.

Adbot
ADBOT LOVES YOU

Sgt. Raisins
Oct 21, 2007
Damnit

jupo posted:

Anyone have any feedback on hosting django with http://webfaction.com ?

Looking to put my first app up and I've only heard good things about these guys so far.
I love it and can't recommend it enough

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.
Thanks guys, sounds like a winner.

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

bitprophet
Jul 22, 2004
Taco Defender

deimos posted:

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.

My understanding was that they didn't actually add any new docs with this effort, simply switching to a new docs generator, tweaking the presentation a bit, and rearranging some material. That said, yea, I'm not sure I like it either, but hopefully that's just me being used to the old layout :(

Signals: agreed, wish they'd document it already, they're very useful in some situations.

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 :)

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.

evilmonkeh
Apr 18, 2004
meh
I've been passing data to templates in urls.pl like:

'extra_context' : {
'news_articles': Article.objects.all().order_by('date')[:5]
}

but when the news articles are updated, the site isn't. How do I get around this? it only happens on the live server (using apache) and not on the built in dev server.

Thanks!

bitprophet
Jul 22, 2004
Taco Defender

evilmonkeh posted:

I've been passing data to templates in urls.pl like:

'extra_context' : {
'news_articles': Article.objects.all().order_by('date')[:5]
}

but when the news articles are updated, the site isn't. How do I get around this? it only happens on the live server (using apache) and not on the built in dev server.

Thanks!

URLconfs are only loaded once, when the server starts, and therefore any values calculated within them will only be executed that one time. This is commonly seen when you do e.g. {'timestamp': datetime.datetime.now()} for a context dict, and then find out the timestamp never changes :)

So, the only "safe" values to set in URLconfs are ones guaranteed to truly yield their value later on, when called in the related view and/or template...like QuerySets, which are lazily evaluated: they only actually hit the DB and return results at the last possible moment, such as when you iterate over them...or when you slice them. Which is what you did in your code!

All you need to do is have your news article template do the slicing instead of the URLconf, using the 'slice' template filter, and things should work.

If this doesn't make sense, we can explain it further :)

evilmonkeh
Apr 18, 2004
meh

bitprophet posted:

URLconfs are only loaded once, when the server starts, and therefore any values calculated within them will only be executed that one time. This is commonly seen when you do e.g. {'timestamp': datetime.datetime.now()} for a context dict, and then find out the timestamp never changes :)

So, the only "safe" values to set in URLconfs are ones guaranteed to truly yield their value later on, when called in the related view and/or template...like QuerySets, which are lazily evaluated: they only actually hit the DB and return results at the last possible moment, such as when you iterate over them...or when you slice them. Which is what you did in your code!

All you need to do is have your news article template do the slicing instead of the URLconf, using the 'slice' template filter, and things should work.

If this doesn't make sense, we can explain it further :)
That explains it perfectly, thanks a lot for that!

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.

bitprophet
Jul 22, 2004
Taco Defender
Nice job :)

The dict stuff, I can't see any other way to write it that's not equally verbose or more so. It'd be nice if you could make a dict via dict(otherdict, newkey=newval, newkey2=newval2) (i.e. combining the two behaviors of the dict() factory builtin instead of it being mapping-object-or-keys) but this really isn't too bad.

Grey Area
Sep 9, 2000
Battle Without Honor or Humanity

deimos posted:

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.
Using the standard csv module would be more robust.

Allie
Jan 17, 2004

Grey Area posted:

Using the standard csv module would be more robust.

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/

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.

The Real Ambassador
Apr 9, 2005

I'll explain and make it plain, I represent the human race.

deimos posted:

:woop:

FINALLY got django working with MS SQL Server from a CentOS host.
I dare you to get blob fields to work.

mwarkentin
Oct 26, 2004
Beta 2 is out.. feature freeze for 1.0.

http://www.djangoproject.com/weblog/2008/aug/27/10-beta-2/

Space Kimchi
Jan 7, 2007

by Peatpot
When 1.0 rolls out, is it likely that if I upgrade my existing applications will work just fine (none of them use any particularly fancy or hackish features) or will there likely be some problems to crop up?

Sivart13
May 18, 2003
I have neglected to come up with a clever title

Space Kimchi posted:

When 1.0 rolls out, is it likely that if I upgrade my existing applications will work just fine (none of them use any particularly fancy or hackish features) or will there likely be some problems to crop up?
How far behind are you? If you didn't track the Newforms-Admin merge you've almost certainly got some stuff to do: http://oebfare.com/blog/2008/jul/20/newforms-admin-migration-and-screencast/

From my perspective a lot of stuff is breaking, and I don't even have a big website to maintain, just a silly blog. I imagine the hardest part is that given the non-compiledness of Python, if you use some feature that's been removed, you won't know until you hit the specific area of a view that exercises it. A good argument for unit testing, I guess.

Typh
Apr 18, 2003

LAY EGG IS TRUE!!!

Space Kimchi posted:

When 1.0 rolls out, is it likely that if I upgrade my existing applications will work just fine (none of them use any particularly fancy or hackish features) or will there likely be some problems to crop up?
There will be problems because of newforms-admin.

I'm running trunk for new development and the pre-newforms-admin tag for everything before the merge (http://code.djangoproject.com/svn/django/tags/notable_moments/pre-newforms-admin/). I just symlink (well, junction on windows) to a different version when I need to.

bitprophet
Jul 22, 2004
Taco Defender
They're correct. The whole deal with Django 1.0 is that after 1.0, they'll be trying very hard to maintain backwards compatibility, such that users do not have to worry about stuff breaking when they upgrade to e.g. Django 1.1.

Because of this, they've been breaking stuff left and right before 1.0 comes out, since they obviously can't do that nearly as much afterwards. Ergo, we've seen huge sweeping changes such as aforementioned newforms-admin, and lesser (but still backwards incompat) changes such as minor alterations to the file upload API.

The semi canonical source for What's Broken is the BackwardsIncompatibleChanges page on the Django wiki. Give it a close read if/when you upgrade.

Space Kimchi
Jan 7, 2007

by Peatpot
Hmm. I'll take a look at that link. I'm not using newforms admin but on the bright side, I don't use the old one very much either, just for a few types of data objects that only need simple CRUD interfaces. Hopefully that will make things simple.

The Real Ambassador
Apr 9, 2005

I'll explain and make it plain, I represent the human race.

Space Kimchi posted:

When 1.0 rolls out, is it likely that if I upgrade my existing applications will work just fine (none of them use any particularly fancy or hackish features) or will there likely be some problems to crop up?

Trunk has broken my projects at least 6 times in the past couple months as they've been trying to clean up the codebase.

bitprophet
Jul 22, 2004
Taco Defender

Space Kimchi posted:

Hmm. I'll take a look at that link. I'm not using newforms admin but on the bright side, I don't use the old one very much either, just for a few types of data objects that only need simple CRUD interfaces. Hopefully that will make things simple.

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.

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.

Senso
Nov 4, 2005

Always working
Ok, I'm going crazy here. I've setup Django correctly, my small test project loads and works fine with the built-in Django server. My problem is with Apache - it just won't work.

I get this error in Apache:
code:
MOD_PYTHON ERROR

ProcessId:      27457
DocumentRoot:   '/var/www/'

URI:            '/'
Location:       '/'
Directory:      None
Filename:       '/var/www/'
PathInfo:       ''

Phase:          'PythonHandler'
Handler:        'django.core.handlers.modpython'

Traceback (most recent call last):

  File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1537, in HandlerDispatch
    default=default_handler, arg=req, silent=hlist.silent)

  File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1229, in _process_target
    result = _execute_target(config, req, object, arg)

  File "/usr/lib/python2.5/site-packages/mod_python/importer.py", line 1128, in _execute_target
    result = object(arg)

  File "/usr/lib/python2.5/site-packages/django/core/handlers/modpython.py", line 177, in handler
    return ModPythonHandler()(req)

  File "/usr/lib/python2.5/site-packages/django/core/handlers/modpython.py", line 145, in __call__
    self.load_middleware()

  File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 22, in load_middleware
    for middleware_path in settings.MIDDLEWARE_CLASSES:

  File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 28, in __getattr__
    self._import_settings()

  File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 55, in _import_settings
    self._target = Settings(settings_module)

  File "/usr/lib/python2.5/site-packages/django/conf/__init__.py", line 83, in __init__
    raise EnvironmentError, "Could not import settings '%s' 
(Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)

EnvironmentError: Could not import settings 'project.settings' 
(Is it on sys.path? Does it have syntax errors?): No module named project.settings
So it's not finding project.settings. :wtf:
code:
mlan:~/proj$ python
Python 2.5.1 (r251:54863, Jul 31 2008, 23:17:40) 
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import project.settings
>>> 
It's RIGHT THERE in my PythonPath!

Here's my relevant Apache config:
code:
<virtualhost *>
        ServerAdmin [email]hurr@durr.com[/email]

        DocumentRoot /var/www/
        <Location />
                PythonHandler django.core.handlers.modpython
                PythonPath "['/home/mlan/proj'] + sys.path"
                SetEnv DJANGO_SETTINGS_MODULE project.settings
                SetHandler python-program
                PythonDebug On
        </Location>

        ErrorLog /var/log/apache2/error.log

        LogLevel warn

        CustomLog /var/log/apache2/access.log combined
        ServerSignature On
</virtualhost>
The permissions are correct, www-data has rx rights on the whole project tree. I don't know now... It works perfectly well with "python manage.py runserver".

Even the env variable is set correctly...
code:
mlan@:/home/mlan# echo $PYTHONPATH
/home/mlan/proj
I have Apache 2.2.4 on Ubuntu. Has anybody run into that before? :bang:


EDIT: Huuuh, I moved everything outside my home and put it in /opt, changed all the path definitions and now it works. Djangooooo :argh:

Senso fucked around with this message at 22:11 on Aug 28, 2008

No Safe Word
Feb 26, 2005

Senso posted:

EDIT: Huuuh, I moved everything outside my home and put it in /opt, changed all the path definitions and now it works. Djangooooo :argh:
Was it maybe permissions?

bitprophet
Jul 22, 2004
Taco Defender

Senso posted:

It's RIGHT THERE in my PythonPath!

Senso posted:

Even [my] env variable is set correctly...

Your PythonPath and shell environment != Apache's PythonPath and shell environment. Two totally different things.

That said, since you were adding the project directory (and, I assume /home/mlan/proj/project was your Django project root, and not /home/mlan/proj, otherwise that would be another problem) to Apache's PythonPath in your conf, I think NSW is correct, it was probably permissions.

For example, even if your project has the right permissions, if your home directory does NOT, you're still hosed. So you'd need to make sure that www-data has +rx on /home, /home/mlan, and /home/mlan/proj, as well as the project dir.

Moving it to /opt probably solved that problem for you (and fwiw it's nicer to keep stuff in /opt or /srv anyways :)).

Senso
Nov 4, 2005

Always working

bitprophet posted:

Your PythonPath and shell environment != Apache's PythonPath and shell environment. Two totally different things.

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.

bitprophet posted:

That said, since you were adding the project directory (and, I assume /home/mlan/proj/project was your Django project root, and not /home/mlan/proj, otherwise that would be another problem) to Apache's PythonPath in your conf, I think NSW is correct, it was probably permissions.

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.

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!

bitprophet
Jul 22, 2004
Taco Defender

Senso posted:

It probably was permissions after all. But the thing is, the django folders in /opt and in /home/mlan have the same permissions...

Did you read the last couple sentences of my post? :) even if the Django folders have the same perms, that doesn't mean jack if the parent directories are more restrictive (at least, in my experience and double-checking I did before posting to make sure I wasn't misremembering...).

Senso posted:

I also defined it in bash, just to make sure.

If you're really a Linux sysadmin by trade, you should probably brush up on how the system works, to a decent level :( Your bash environment is in no way connected to the environment Apache runs in, unless you're running in something like sudo -u www-data /bin/bash, and even that isn't necessarily going to give you the 100% same environment, unfortunately.

duck monster
Dec 15, 2004

Yeah the python path thing can be whack. All sorts of python frameworks do it to (Webware for python, a tomcat style stack , does the same) but it really is for the best.

The best thing you can do for your security is to keep the python path AWAY from your main module hidey hole , and just bring in the standard modules it needs. That way if someone somehow manages to code inject or exploit an exec or something then you at least minimise the damage. Its only a mild protection, but if you combine it with , say , a chroot jail, you can pretty much wall off a section of your server thats public facing.

Of course all the cool kids serve out of vhosts these days anyway, so its probably moot.

mwarkentin
Oct 26, 2004
Thought I'd bump this for RC1! http://www.djangoproject.com/weblog/2008/sep/02/10-rc1/

Also, I've got a question regarding payment gateways.. I need to integrate one into a project I'm working on.. are there any out there that I can just plug in?

What's the easiest to integrate with? Paypal? Authorize.net?

Pros & cons?

king_kilr
May 25, 2007

mwarkentin posted:

Thought I'd bump this for RC1! http://www.djangoproject.com/weblog/2008/sep/02/10-rc1/

Also, I've got a question regarding payment gateways.. I need to integrate one into a project I'm working on.. are there any out there that I can just plug in?

What's the easiest to integrate with? Paypal? Authorize.net?

Pros & cons?

I don't know about the pros and cons of each but satchmo(django store app)(satchmoproject.com) has a ton of support for various gateways built in, so you can probably steal code from them for whatever you are working on.

The Real Ambassador
Apr 9, 2005

I'll explain and make it plain, I represent the human race.

mwarkentin posted:

Thought I'd bump this for RC1! http://www.djangoproject.com/weblog/2008/sep/02/10-rc1/

Also, I've got a question regarding payment gateways.. I need to integrate one into a project I'm working on.. are there any out there that I can just plug in?

What's the easiest to integrate with? Paypal? Authorize.net?

Pros & cons?

I use: http://pypi.python.org/pypi/zc.authorizedotnet/1.3

I had to write a hack to be able to do AUTH_CAPTURE transactions though:

code:
from zc.authorizedotnet.processing import CcProcessor

class MyCcProcessor(CcProcessor):
    def authorizeAndCapture(self, **kws):
        if not isinstance(kws['amount'], basestring):
            raise ValueError('amount must be a string')
        return self.connection.sendTransaction(type='AUTH_CAPTURE', **kws)

No Safe Word
Feb 26, 2005

Django 1.0 is final

Release notes with what's new

edit: also Blog post!

No Safe Word fucked around with this message at 02:24 on Sep 4, 2008

The B Man
Mar 21, 2007
'Cause life's too short to play Freebird
I've had an idea for a web application for a while and I've finally gotten around to trying to build it. I've also been meaning to play around with Django so I've killed two birds with one stone. The past two days or so I've been playing around with bits and pieces for Django and I think I'm starting to get a handle on things, the documentation that is available is wonderful.

Basically my application allows musicians to work on songs. Each song is comprised of various snippets, the ordering of the snippets would allow multiple instances in the song (eg chorus) and not all snippets would make it into the final version. I'm having a bit of troubling coming up with how to handle the song ordering in my model.

This is what I have at the moment:
code:
class RunOrder(models.Model):
    Song = models.ForeignKey(Song)
    Snippet = models.ForeignKey(Snippet)
    Position = models.IntegerField()
    unique_together = (("Song", "Position"),)
    class Admin:
        list_display = ['Song','Position','Snippet',]
        list_filter = ['Song',]
        
    class Meta:
        ordering = ['Song','Position',]
The idea is that for now the ordering of songs would be done by presenting the user with two list boxes, one with all available snippets for that song and another with the current running order allowing the user to move them up/down and add/delete snippets to the order.

The admin interface is allowing me to add two items in the same position and ordering by song only. Am I going about this the right way?

bitprophet
Jul 22, 2004
Taco Defender
First off, you seem to be using Django 0.96, you should almost definitely get 1.0 which just came out. Gigantic differences. 0.96 is approaching two years old at this point.

Second, unique_together (if it's still valid, I don't recall if it got axed/changed since then) should be in your Meta class. The only stuff that's not a function or inside Admin/Meta classes, are fields, and I don't think you mean to have a field called "unique_together" :)

m0nk3yz
Mar 13, 2002

Behold the power of cheese!
Ok. Python Oldie, but Django newbie question ahead:

I'm building a django app that will have a series of test cases tracked within it (yay it will be open source). Each test case has a an object (from the model) that looks like this:

code:
class TestCase(models.Model):
    VALID_STATES = ( ('N', 'NEW'),
                     ('A', 'ACTIVE'),
                     ('I', 'INACTIVE'),
                    )

    shortname = models.CharField(max_length=150)
    expected_result = models.TextField()
    author = models.ForeignKey(User, to_field="username")
    component = models.ForeignKey(Components)
    last_modified = models.DateField(auto_now=True)
    created = models.DateField(auto_now_add=True)
    state = models.CharField(max_length=10, choices=VALID_STATES)
    automated = models.BooleanField()
    manual = models.BooleanField()
    procedure = models.ManyToManyField(ProcedureSteps)
    # TBD: replace with tagcloud impl.
    attributes = models.CharField(max_length=150)
    notes = models.TextField()

class ProcedureSteps(models.Model):
    category = models.CharField(max_length=30)
    text = models.TextField()

    def __str__(self):
        return self.text
The question I have is this - for the procedure field, it actually points to a ProcedureSteps object that has category and name attributes.

A "procedure" (as related to the test case) can have multiple ProcedureSteps associated with it. A procedure "step" could be related to multiple test cases. This is "easy" in that I can just add a bunch of ProcedureSteps to the table, and use the Django admin to create a select box. However, what I need is to keep the list of ProcedureSteps for the TestCase enumerated - step 1 must always be step 1. I also want to create an admin form which starts with 2 "edit" rows for the procedure attribute of the test case, and users can "add" a step. I also don't want to create a "procedure table" for each test case - that seems excessive for something that could have 100k+ entries in the test case table.

The steps then must be stored and then displayed in the same order they were added to the test case. I want to shared all previously entered ProcedureStep with all new and old test cases, so people can pick from a category of steps, then select a pre-entered ProcedureStep.

So, I'm not terribly good with databases - or django. Any of you have a suggestion on how to structure the model and possibly render this in the admin? I feel stupid.

m0nk3yz fucked around with this message at 18:49 on Sep 4, 2008

Adbot
ADBOT LOVES YOU

The B Man
Mar 21, 2007
'Cause life's too short to play Freebird

bitprophet posted:

First off, you seem to be using Django 0.96, you should almost definitely get 1.0 which just came out. Gigantic differences. 0.96 is approaching two years old at this point.

Second, unique_together (if it's still valid, I don't recall if it got axed/changed since then) should be in your Meta class. The only stuff that's not a function or inside Admin/Meta classes, are fields, and I don't think you mean to have a field called "unique_together" :)

Ughh, I can't believe I actually posted that, I had read and understood that was the point of the Meta class but acting on that information seemed to be a stumbling block.

I was using 0.96, I was kind of scared that upgrading would break everything that I had done the day before but I've done so now and figured out all the new stuff.

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