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
hey mom its 420
May 12, 2007

Git posted:

That's one hell of an OP. I'll kick off the stupid questions:

I've been coding small Django apps mostly for personal use for a while now and it's awesome. However, I don't think I've ever had cause to use anything other than render_to_response from django.shortcuts. Am I an idiot for using it exclusively? If so, what should I be doing instead?

Yeah mostly you'll use render_to_response, but what you can also do is return 404 errors or 403 redirects. A nice thing to take advantage of is that you can return other views, just with different parameters, which can be very useful sometimes.

Adbot
ADBOT LOVES YOU

hey mom its 420
May 12, 2007

Putting them in separate folders decouples your application from your templates a bit more. For instance, you can release a new version of your application and people who are using it just replace the application folder and the templates stay intact if they are using their own or something.

Have you tried explicitly telling Django where the templates are located by adding an entry to TEMPLATE_DIRS in settings.py?

hey mom its 420
May 12, 2007

If you mean what I think you mean then yeah, because querysets are lazy. They are only evaluated when evaluating them is absolutely necessary (see QuerySets are lazy)

So if you have
code:
my_results = YourModel.objects.all() #not evaluated, no DB access
my_results = my_results.filter(something='blah') #not evaluated, no DB access
my_results = my_results.filter(something_else='foo') #not evaluated, no DB access
result = my_results[0] #evaluated, DB is hit
all_results = list(my_results) #evaluated, DB is hit

hey mom its 420 fucked around with this message at 16:11 on Mar 7, 2008

hey mom its 420
May 12, 2007

How about going with a VPS? I hear slicehost are really good and also I think legalcondom is offering good and cheap VPS hosting for gunes.

hey mom its 420
May 12, 2007

ashgromnies posted:

I think I'm doing something wrong... I just started with Django and got everything set up and got the administrative interface working.

My Project is named "mysite" and my App is "blog". I opened up czubus/settings.py and added "blog" to the INSTALLED_APPS array, but now I get an error:

ImproperlyConfigured: Error importing middleware django.contrib.sessions.middleware: "No module named blog"

It makes me think it's in the wrong namespace or a path is misconfigured somewhere, but I don't know where to start looking.

edit: Ahah, got it... turns out I was right - it was in the wrong namespace, so I had to put "mysite.blog" instead of just "blog" in the INSTALLED_APPS. You might want to change that in the tutorial :)

What does your directory and file layout look like? Because adding just app_name to INSTALLED_APPS wihtout prefixing it with the site name should work, at least it works for me.

hey mom its 420
May 12, 2007

Sure, you can do all of that, take a look at this part of the documentation, it explains how it works quite nicely.

hey mom its 420
May 12, 2007

ashgromnies posted:

Why not? I want the question mark to be optional. In most regular expression engines(including Python's), the question mark means to match the preceding character zero or one times.

That's technically correct but I've found that it works best if you don't put the question mark after the slash and then Django will automatically append a slash if you haven't explicitly told Django not to (i.e. don't set APPEND_SLASH = False in settings.py)

edit: ugh beaten. f u bitprophet

hey mom its 420
May 12, 2007

Putting a Meta inner class inside a model and assigning unique_together fields effectively achieves the same thing as composite primary keys. They're not composite primary keys in the DB, but there's an index over both of them, so effectively it's the same.

hey mom its 420
May 12, 2007

FrontLine posted:

Ideas?
Kind of that ashgrommies said, only I wouldn't try to shoehorn it into a class if it doesn't need to be a class. If it's just a script that does something when execute it, I'd wrap that functionality into a function call inside the script and then in Django you can just do
code:
form your_script import the_function
and use that function in your views

hey mom its 420
May 12, 2007

Oh, well then yeah, just import the stuff you need from the script and that's it. Unless I'm misunderstanding your problem somehow.

hey mom its 420
May 12, 2007

Yeah, sure. At the beginning of your views.py, just have an import statement that imports your script, example (making stuff up here):
code:
from your_script import ImageManipulator
and then in the views themselves you call what you imported, maybe like so
code:
def display_some_results(request):
    results = ImageManipulator().get_results_for_image('some/path/image.jpg')
    # do some more parsing or whatever
    return render_to_response('some_template.html', {'results':results})

hey mom its 420
May 12, 2007

On our Django project, we're using jQuery and stuff works out just fine. You make views that serve the data that's requested asynchronously and then just write the jQuery to call them. Like king_kilr said, you can also use Django's serialization features in the views that are served up asynchronously. I like either serializing stuff into JSON and then reading it with the javascript or just directly sending html.

hey mom its 420
May 12, 2007

Yeah, just use the SVN version, I don't recall anything getting borked when upgrading and if they change something (like when they changed the maxlength model field option to max_length), they usually keep the old behavior and issue a deprecation warning upon usage.
Also, Django has a very good extension to the unittest module and it's pretty easy to make some basic test coverage for your code so you know immediately if something major gets broken.

hey mom its 420
May 12, 2007

What I usually use when I want the database nuked and then resynced is a script that I run. I usually have an sqlite database on my development machine. Here's what it usually contains
code:
rm db.db
touch db.db
yes "no" | python manage.py syncdb
python manage.py loaddata data
The first two lines delete and then make a file, the third runs syncdb and keeps yelling no at it because syncdb will ask you if you want to create the superuser accounts. The fourth line loads the data I have in a file called data.json. When it's an early phase of an app and the models are still changing, it's usually just the data that has the superuser account. I make that data by creating a superuser account and then doing python manage.py dumpdata > data.json

What I'm having the most problems with is keeping test data in the face of changing models. Say I have some tests and some test fixtures which the tests load when they begin running so they have something to operate on. Now if I change the models and run the tests, all of a sudden the test data can't be loaded in by the tests because the models are different than what the test fixture was made for. I usually have a test fixture in JSON. So anyone know a good way around that?

hey mom its 420
May 12, 2007

Yes but you see, this way I get to use the awesomely cool yes program.

hey mom its 420
May 12, 2007

deimos posted:

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

Just another response to this: I remember trying sqlreset before but couldn't remember why I'm not using that command. Tried it again today. The thing with sqlreset is that you have to specify all the app names that you want to reset. That's a bit of a hassle when your project is decoupled into a bunch of apps. So I guess I'm still sticking with my yes "no" script :)

hey mom its 420
May 12, 2007

Use a double underscore to follow foreign key relationships when filtering, selecting, etc.
code:
Entry.objects.filter(user__username='zenobia')
Basically the form is <FK field>__<property> and with that you can also follow them as far as you want, like
code:
Employee.objects.filter(company__country__label='US')
On an unrelated note, I'm implementing a back end for a site for a client right now and because I don't have Django support on my reseller account (hopefully I'll have it soon though), I've spent like three days implementing something in PHP that I could have done in one day with Django. Just goes to show, don't take awesome things like Django for granted.

hey mom its 420
May 12, 2007

Wouldn't you want to and_ them together in that case?

hey mom its 420
May 12, 2007

Yeah, that's cause reduce will fail if it gets an empty sequence with no initial value. In your case that happens when query == ''. I think you could pass a third argument, Q() to that reduce to avoid getting that error on an empty string, but I'm not really sure. However, I think anding the Q objects together won't work like expected because that just checks that the field contains all those letters. It doesn't check their order or how many of them there are.

I think you might be able to achieve what you want by using the iregex field lookup and specify the regex so that it ignores the characters you want.

hey mom its 420
May 12, 2007

Yeah, ummm, do you mean like version control? Like mercurial, git, svn, etc.

hey mom its 420
May 12, 2007

Ooh, you mean like revisions are stored in wiki pages, kind of like that? Ah, I don't know, but it seems like the cool triple post nailed it. lol

hey mom its 420
May 12, 2007

Because then you don't get to use some the nifty features that contrib.auth offers, like messages and getting the user directly from request. The proper way to extend the User model is described here.

hey mom its 420
May 12, 2007

Yeah saw this today, looks pretty cool. I just hope that after 1.0 they'd release versions more often. I might even contribute a bit over the summer, try fixing some bugs, etc.

hey mom its 420
May 12, 2007

What does the method look like, exactly? Also make sure you are using unicode strings when returning. So don't return 'something', instead, return u'something'. The u in front of the quote means it's a unicode string.

hey mom its 420
May 12, 2007

Yes, definitely! Get the SVN release, 0.96 is pretty much archaic. I bet upgrading to the latest version will fix that for you or I'll eat a spider. Don't toxx me on that though.

hey mom its 420
May 12, 2007

checkeredshawn posted:

It's your lucky day! Unless you enjoy eating spiders, that is. I checked out the latest version and now I've got 0.97-pre-SVN-unknown.

Although I'm confused why http://www.djangoproject.com/documentation/install/ tells you to check out django-trunk then make a symbolic link in Python's site-packages directory to the directory you checked out django's code into, when you can just check out the code and copy django-trunk/django into /usr/local/python2.5/site-packages and then copy django/bin/django-admin.py into /usr/bin. I wonder if I'll still be able to update the code using svn update this way?
Haha! Nice.

It's better to make a symbolic link from the site-packages directory because then uninstalling Django is as easy as removing the symbolic link and you can update your copy of Django from the trunk without being a super user, you just go into the trunk directory and do svn update.

hey mom its 420
May 12, 2007

No, that's an old rear end version, no one should really be using it. Use the SVN version. To do that just checkout the latest changeset by doing svn co http://code.djangoproject.com/svn/django/trunk/ and then installing it.

hey mom its 420
May 12, 2007

1.0 is supposed to come out on September the 2nd. Read more about the schedule here

hey mom its 420
May 12, 2007

Use the template inheritance functionality along with the auth context manager. First off, in your settings.py, check that django.core.context_processors.auth is in the variable TEMPLATE_CONTEXT_PROCESSORS. Then in every view, give it a request context like this.
code:
from django.template import RequestContext

....

def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))
See that variable you give to the template, that's the request context.

Once you've done that, you can do stuff like
code:
{%if user.is_authenticated%}
  //Login form goes here
{%else%}
  //Link to logout or something
{%endif%}

hey mom its 420 fucked around with this message at 18:17 on Jul 8, 2008

hey mom its 420
May 12, 2007

Yeah, you usually do that by overwriting the save method or by using signals. The way to overwrite the save method is pretty straightforward.
code:
class Car(models.Model):
    manufacturer = models.CharField(_('Manufacturer'), max_length=30)
    model = models.CharField(_('Model'), max_length=20)
 
    def save(self):
        #stuff that will happen before the save goes here
        super(Car, self).save() #don't forget this line!
        # stuff that will happen after the save goes here
As for when to use signals and when to override the save method, well, you usually want to overwrite the save method when it's about something that's closely related to the model (like making a folder on save, auto populating some fields, etc.) and you probably want to use signals when you're sending off emails, doing some sort of reporting or just generally stuff that isn't so closely tied to the model itself.

hey mom its 420 fucked around with this message at 22:31 on Jul 9, 2008

hey mom its 420
May 12, 2007

Hehe, no problem. If you have a ModelForm, you can pass a keyword argument of commit=false when you call its save method.
code:
f = CarForm(request.POST)
car = f.save(commit=false)
car.owner = request.user
car.save()
For more info, check out the docs on model forms.

hey mom its 420
May 12, 2007

Give this a read: http://docs.djangoproject.com/en/dev/intro/tutorial02/#intro-tutorial02
You don't make models part of the admin interface by putting an inner class of Admin in the models anymore.

hey mom its 420
May 12, 2007

Congrats man! When I get some cash, I'll pick this up!

hey mom its 420
May 12, 2007

You can override the manager's __init__ method and give it an extra argument and then save that argument as an instance variable and then call the superclass __init__. That way you can do something like characters.mine(request.user).all()

hey mom its 420
May 12, 2007

Explicitly referring to your project name from your apps is generally discouraged because it reduces the portability of your apps. Even if your apps aren't meant to be portable, I still wouldn't use it.

Adbot
ADBOT LOVES YOU

hey mom its 420
May 12, 2007

Hey y'all, what do your fabric scripts for deploying look like? This is mine, and it seems awfully simple, is there something that I'm missing or is this OK as far as deployment goes? We still don't have tests so there's no testing, but I'll add those as well.

code:
from __future__ import with_statement
from fabric.api import *

env.hosts = ['django@server.com']

def deploy(rev='tip'):
    with cd('/srv/django-projects/toliman'):
        run('hg pull') #pulls from repo to production repo
        run('hg update %s' % (rev,))
        run('python manage.py migrate musicdiscipline')
        run('python manage.py collectstatic --noinput')

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