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
ImJasonH
Apr 2, 2004

RAMALAMADINGDONG!

deimos posted:

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.

Not a backend issue, just my own stupidity. I was passing a list of strings to killed_by because i r dum.

Adbot
ADBOT LOVES YOU

jarito
Aug 26, 2003

Biscuit Hider
Is there anyway to have syncdb just drop all the tables and reinsert them? At least for one application? I am porting an existing app and when I mod a table to add fk relationships, etc. it is really annoying to have to delete the tables by hand and then let django re-add them.

Perfect would be leaving the django stuff alone (admin, auth, etc) but dropping all tables related to a specific app and re-adding them.

bbq
Jan 21, 2006

get funky.
syncdb can't do it, but your best bet is probably manage.py sqlclear and sqlall:

sqlall [appname ...]
Prints the CREATE TABLE, initial-data and CREATE INDEX SQL
statements for the given model module name(s).

sqlclear [appname ...]
Prints the DROP TABLE SQL statements for the given app name(s).

You can make a shell script to pipe the output of these into your database's command line client

No Safe Word
Feb 26, 2005

jarito posted:

Is there anyway to have syncdb just drop all the tables and reinsert them?
Yes, it's called initial fixtures, and basically you have to dump a serialized copy of the data into some files and put them in your FIXTURES_DIR and syncdb will pick them up (or loaddata).

loaddata docs have the information on how to create these fixtures here

the syncdb docs state:

quote:

syncdb will also search for and install any fixture named initial_data with an appropriate extension (e.g. json or xml). See the documentation for loaddata for details on the specification of fixture data files.

jarito
Aug 26, 2003

Biscuit Hider
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:

code:
class Contact(models.Model):
    title = models.CharField(max_length=8, blank=True)
    first_name = models.CharField(max_length=50)
    middle_name = models.CharField(max_length=50, blank=True)
    last_name = models.CharField(max_length=50)
    suffix = models.CharField(max_length=10, blank=True)
    other_languages = models.CharField(max_length=255, blank=True)
    
    class Admin:
        pass
  
    def __unicode__(self):
        return '%(last)s, %(first)s' % { 'last': self.last_name, 'first': self.first_name }

class Patient(models.Model):
    birthdate = models.DateField()
    contact = models.ForeignKey(Contact)
    emergency_contact = models.ForeignKey(Contact, related_name='emergency_contact', null=True)
    
    class Admin:
        pass
  
    def __unicode__(self):
        return contact
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:

code:
class Reporter(models.Model):
    name = models.CharField(max_length=30)

    def __unicode__(self):
        return self.name

class Article(models.Model):
    headline = models.CharField(max_length=100)
    reporter = models.ForeignKey(Reporter, null=True)

    class Meta:
        ordering = ('headline',)

    def __unicode__(self):
        return self.headline
Am I going about this the wrong way?

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.

king_kilr
May 25, 2007

deimos posted:

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.

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

ATLbeer
Sep 26, 2004
Über nerd
Figure I'd post this here first since I'm looking for people that would be reading this thread anyhow.

Any Django programmers in the greater Atlanta area?

I have a pile of programming work on my desk that is going to be impossible for me to do in this lifetime and I need some help doing the heavy lifting in the form of a contractor(s). I'm looking for

Python
Django (If you have good experience working in WebDev with other frameworks but, are learning Django thats fine too)
HTML / CSS Experience
Javascript / AJAX Experience a plus
MySQL experience a necessity.


We are doing very rapid application development for a big company. Not everything you do will see the light of day (public) and you WILL have to sign a NDA. This is a non-negotiable, sorry. Only get in contact with me if you understand what this means and are comfortable working with a NDA. You really have to be based in the ATL area. This can't be a telecommute thing, sorry (unless you live in a really cool exotic local and I can get my company to cover my T&E there... You better be a rockstar though :D) (about 99% kidding there)

GTech students. I know your probably the in the middle of your senior design work or exams. Don't worry, go ahead and shoot me an email and a resume (if you have one) as well. If your work is good enough and I can wait a bit for the semester to be over.

atlbeer (at) gmail.com
Things to include:
- Resume
- Current / previous websites with a short description of what your work for the site was, a bit about it's architecture
- Open Source projects?
- Have you written any Django or Python modules? Include some links.
- Have you worked with other types datastores (BigTable, CouchDB, etc?) mention it
- Have you had any work with Hadoop? mention it.

WickedMetalHead
Mar 9, 2007
/dev/null
Why's there never any Django jobs near Philly !

duck monster
Dec 15, 2004

Oh hey my perfect Job. Django with posibility of working with "quirky" backends. (Hadoop & Couch.).

pls move the job to Western Australia thanks.

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.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC
Totally forgot about this, but since I did get this fixed I thought I should mention what was causing it.

Wulfeh posted:

I know this is a big vague, but hopefully someone may have an idea

code:
def contact_delete(request, file, contact_id): 
	
	contact_record = Contact
	contact_record = get_object_or_404(Contact, id=contact_id)
	contact_record.delete()
	
	return HttpResponseRedirect('/IR/' + file + '/contacts/')		
this raises an error stating "__init__ takes 2 args, but only 1 is given". I am not sure why/how 2 args are needed for deletion since all the examples show object.delete() as the way to delete

http://dpaste.com/45018/ - Full error message
http://dpaste.com/45019/ - My views, line 100 is the delete part

I had my objects set to a custom search manager in my models, and when I was trying to delete the model it was trying to use the search managers args, which I wasn't passing. Anyway long story short I now have:

code:
objects = models.Manager
fulltext = SearchManager(('first_name','last_name','file'))

ATLbeer
Sep 26, 2004
Über nerd

duck monster posted:

Oh hey my perfect Job. Django with posibility of working with "quirky" backends. (Hadoop & Couch.).

pls move the job to Western Australia thanks.

So just humorously I checked to see what it would take to fly out to the underside of the world (never been there before :D)

From Atlanta the cheapest flight (business class :v: )..

Atlanta -> Los Angeles (4hr 52m) (+2hr layover)
Los Angeles -> Bangkok (17hr 30m) (+16hr layover)
Bangkok -> Perth (6hr 15m)

And the return trip
Perth -> Phuket (6h 15m)
Phuket -> Bangkok (1h 25) (+8hr layover)
Bangkok -> New York (17h 30m) (I think that's actually an over the north pole flight, kick rear end)
New York -> Atlanta (2h 41m) (+4 hr layover)

NINETY HOURS OF TRAVEL... for only $9k USD...

My rear end feels sore just thinking about that..

Although for $17kUSD I can fly on Thai Airways...

Sorry man.. It's small planet with airplanes but, that's so far away.. Hahah..

If there's anyone else in this thread that's interested I'd send an email this weekend because Monday I'm going to post a SH/SC thread and start expanding my search options.

gabensraum
Sep 16, 2003


LOAD "NICE!",8,1
I believe that Perth is considered the world's most remote city of its size. It's a long flight even from the other big Australian cities. It's a pretty cool distinction, I think.

pls move the job to Tasmania thanks (we're closer because you can trvael via Melbourne :v: )

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Learning to use Django is hard, can you recommend me a book to read apart from 'The Django Book'?

WickedMetalHead
Mar 9, 2007
/dev/null
If you know python, the Docs are incredibly awesome and the tutorials get you 90% of the way there.

If you don't know python, pick up a book on python.

Typh
Apr 18, 2003

LAY EGG IS TRUE!!!
I read Dive Into Python, the Django docs, and the first seven chapters of The Django Book. Now there's not much I can't do or figure out using the docs and the IRC channel.

duck monster
Dec 15, 2004

I'm starting to fairly hum in this little system :cool:

The fun part is using pythons wierd little libraries in unexpected ways in django.

Is there a way in Django to launch a persistant process, or ought I just fork some poo poo out the side of manage.py (yes. brutal. I know.)

I wanna be able to run shortest-path searches along a dataset of around 4000 points in a digraph topology. Its not that the algorithm is slow, its bitching fast. Its loading and organising the goddamn dataset.

king_kilr
May 25, 2007
And queryset-refactor just hit trunk: http://code.djangoproject.com/changeset/7477 YAY!

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.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Upon further reading, it seems the documentation (which I was reading before) when coupled with 'The Django Book' make for a good amount of well written documentation. I think I'm starting to understand what's going on.

The confusion came from how different the scope is here, Rails really does tie you down and make things difficult in a lot of respects. Django only loads what it is using on each page? Rails doesn't require you to load/initialize/import anything at all, I suspect that makes each Rails app somewhat resource intensive in comparison.

I see other benefits to the way Django is doing it, I'm just surprised. That amount of control and manual 'work' is unheard of in the Rails community.

bitprophet
Jul 22, 2004
Taco Defender

Nolgthorn posted:

[...]
I see other benefits to the way Django is doing it, I'm just surprised. That amount of control and manual 'work' is unheard of in the Rails community.

The way I've seen it, without having used Rails much but working at a shop where it's used by 50% of the dev team, is that Rails goes the extra mile in terms of leveraging cleverness and magic and making decisions on your behalf. The benefit of this is that it's less work in those cases where Rails' decision-making lines up with your needs, and/or where you don't run into bugs that are made difficult to fix due to having to track down said magic.

However, if you want/need to differ from Rails' opinions on things, then you have to struggle with the framework to get things done, and/or omit large gobs of functionality.

Django, on the other hand, tends to not offer as much extra stuff, but that's because it wants to avoid that above situation where the user then has to fight the framework to get things done their way (with the exception of Django's ORM, which is used for the admin and generic views; but that's more of a technical constraint rather than an explicit choice made by the core team).

For example, Rails tends to tie you to Prototype for Ajax stuff, insofar as its JS helper code uses Prototype only (or so I'm told); Django doesn't offer such helpers, so you can use whatever Ajax library you want.


So, yea, neither approach is inherently wrong, it's just two different philosophies at work.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Most notably chapters 8 and 9 of the Django Book are being really helpful, these are answering a lot of questions I had which were slowing down my learning process. Things like "Why are some of these in quotes and others not?" or "Why do some methods need to be explicitly imported and others are just magically working, how does it do that?"

I generally had this feeling like I needed an instructor or a book to explain what I wasn't getting. I am loving this now, those new to this should be sure and read those chapters.

Hah! I'm building my personal project in Django.
It's going to be a content driven comedy web site updated and moderated by it's users, move over sa. Hahahaha!

politicorific
Sep 15, 2007
Are there any more tutorials on how to write views/urls? Or any really good examples available in the djangosites w/sources?

I've linked up a pre-existing database to my django code. The admin app has incredible power, which demonstrates most everything I want my users to be able to view (search, sort by category). I have about 5,000 records that I want to be able to cross-reference with links inside records. First I'm trying something easier - I want to create a url/view so that https://www.mysite.com/english/x/ where x is a letter a-z returns all entries starting with that letter. Writing 26 different urls sounds stupid, plus I two other similar patterns with another ~250 entries.

why doesn't this work?

views.py
code:
def englishdictionary(request):
    query = request.GET.get('q', '')
    if query:
        qset = (
            Q(english__startswith=englishdictionary)
            )
        results = Entry.objects.filter(qset).distinct()
    else:
        results = []
    return render_to_response("c:/django/words/templates/search.html", {
        "results": results,
        "query": query
    })
urls.py
code:
from django.conf.urls.defaults import *
from words.display.views import englishdictionary

urlpatterns = patterns('',
    (r'^admin/', include('django.contrib.admin.urls')),
    (r'^search/', 'words.display.views.search'),
(r'^english/[A-Za-z]/', englishdictionary))
I can define "englishdictionary" in views.py to be any letter I want, but how do I get django to determine the variable based on the url?

ImJasonH
Apr 2, 2004

RAMALAMADINGDONG!

politicorific posted:

I can define "englishdictionary" in views.py to be any letter I want, but how do I get django to determine the variable based on the url?

I think Named Groups is the solution, read the section on them here

Basically, change the line in urls.py to:
code:
(r'^english/(?P<letter>\w)/', englishdictionary))
And now the letter in /english/x/ will be available as a parameter in your view:

code:
def englishdictionary(request, letter):
    pass
edit: This may not be perfect because I'm pretty new to Django and horrible at regexps, but you get the point.

ImJasonH fucked around with this message at 05:33 on May 4, 2008

politicorific
Sep 15, 2007
awesome! That worked perfectly

politicorific
Sep 15, 2007
okay two questions and this is more just to show off...
urls.py
code:
(r'^\xD7\xA2\xD7\x91\xD7\xA8\xD7\x99\xD7\xAA',englishdictionary2))
I'm trying to make a unicode/foreignlanguage URL - I have an English dictionary, and this is for a foreign language. If you think you suck at regular expressions - I can't be that much better.
Basically I'd like to do the same thing as before
code:
(r'^tablenumber/(?P<digit>\d+\w)/', tablenumber)
yet, I believe I looked at the documentation, but I can't use a named group - basically another 22 letters to pass to an index


Next question regarding views/models.
__str__ in model constructs the output of the database search into a single string. I need to manipulate this data separately - each piece goes to a different place. I suppose I could use .split() and create another list, but that just doesn't seem elegant enough.

code:
def __str__(self):
                return ("""%s,%s,%s,%s,%s,%s,%s,%s,...

really this goes on forever, there are 49 instances of %s and 49 different variables it's combining. There must be a better way!

bitprophet
Jul 22, 2004
Taco Defender

politicorific posted:

Next question regarding views/models.
__str__ in model constructs the output of the database search into a single string. I need to manipulate this data separately - each piece goes to a different place. I suppose I could use .split() and create another list, but that just doesn't seem elegant enough.

code:
def __str__(self):
                return ("""%s,%s,%s,%s,%s,%s,%s,%s,...

really this goes on forever, there are 49 instances of %s and 49 different variables it's combining. There must be a better way!

code:
def __str__(self):
    return ",".join([str(x) for x in list_of_vars])
Not sure why you were returning what looks like a tuple for your __str__, but my snippet there will give you a string of the form you're trying to generate, and assumes your variables are in a list of some kind.

It's not 100% clear what exactly you're trying to accomplish, though, so maybe you should step back a bit and give us a better idea :)

politicorific
Sep 15, 2007
okay here I'll be explicit:

Here's the assumption that I want blown apart, that an application of a project can only receive a single output from models.py.

code:
from django.db import models

class Entry(models.Model):
        id = models.IntegerField(primary_key=True)
        uniqnumber = models.CharField(blank=True, maxlength=765)
        combined = models.CharField(blank=True, maxlength=765)
        english = models.CharField(blank=True, maxlength=765)
for a total of ~49 entries
then:
code:
          def __str__(self):
                return ("""%s,%s,%s,%s,%s,%s,%s,%s,
                        %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s
                        %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s
                        %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s""")\
                        % (self.id,self.uniqnumber,self.combined,self.root1,\
                           self.root2,self.root3,self.root4,self.root5,self.root6,\
                           self.participle,self.tablenumber,self.intrans,\
                           self.english,self.sroot1,self.sroot2,self.sroot3,\
                           self.sroot4,self.sroot5,self.sroot6,self.broot1,\
                           self.nroot2,self.tabletype,self.pm1s,self.pf1s,\
                           self.pm1p,self.pf1p,self.hn1s,self.hm2s,self.hf2s,\
                           self.hm3s,self.hf3s,self.hn1p,self.hm2p,self.hm3p,\
                           self.fn1s,self.fm2s,self.ff2s,self.fm3s,self.fn1p,\
                           self.fm2p,self.ff2p,self.fm3p,self.ims,self.ifs,\
                           self.imp,self.ifp,self.inf)
The issue is that I want all those different variables to be separate, not combined.

Can I use a similar admin setup like this for my applications? If so how do I address them in other modules?

code:
class Admin:
                list_display = ('id','english','tablenumber','uniqnumber',\
'combined','root1','root2','root3','root4','root5','root6','participle','intrans',)
                #list_filter = ('english','tablenumber') #2 entries
                ordering = ('id',)
                search_fields = ('english',)
here is the view I'm trying to build:
code:
def formulate(request):
    query = request.GET.get('q', '')
    if query:
        qset = (Q(english__icontains=query))
        results = Entry.objects.filter(qset).distinct()
        resultnumber=len(results)
    return render_to_response("c:/django/words/templates/search.html", {
        "results": results,
        "query": query,
        "resultnumber": resultnumber})
I want to be able to pass individual Models, such as "english", "combined", "uniqnumber", and others onto this view to use in my template

bitprophet
Jul 22, 2004
Taco Defender
I...I don't think you quite get this :(

__str__ is solely a convenience method for printing out a string representation of your model object, like when you're debugging or displaying a list. "output from models.py" doesn't mean jack poo poo: you're supposed to query the database using the ORM, not parse the string representation of your model, or whatever you're trying to do.

It looks like you're trying to basically build an arbitrary query front end or something (like phpMyAdmin)? It's not clear. Can you give some example use cases in plain English? I.e. "I want to find all Entry items in my database which have the word 'Foo' in their 'english' field" or etc.

What is the real world problem your application is trying to model and solve here?

liquidfury
Jul 2, 2004

I having an issue with the database not updating the coloums when the models are changed. I saw in the thread that it is a known issue. Is there a way to force it to update? I am running Django 0.96.1

No Safe Word
Feb 26, 2005

liquidfury posted:

I having an issue with the database not updating the coloums when the models are changed. I saw in the thread that it is a known issue. Is there a way to force it to update? I am running Django 0.96.1

It's not just a known issue, it's just the way it's going to be. You have to recreate the database/tables when you make a change to the model. There was a schema-evolution branch in progress, but I don't know what is happening with it.

Alternately, manually make the changes :v:

bitprophet
Jul 22, 2004
Taco Defender
Yea, it's a decision made by the Django devs (for the time being, anyway) that having a script automagically update the DB based on changes you make to your models, isn't a good idea. There's a lot of places where such a script could gently caress things up or cause you to lose data, and they didn't want people to be tempted to run that kind of tool on live data.

Or, put another way, you really ought to know at least enough about SQL to be capable of making minor changes to your DB schema, if you're going to be making sites; that's my opinion, anyway. It's really not hard to run a couple of ALTER TABLE statements during development :)

That said, yea, it's a commonly asked-for feature and there are a few projects out there trying to address it, but nothing that's hit prime-time yet. Your best bet is to try checking out the schema-evolution branch and play with that, but it's not for the faint-hearted.

Actually, I take that back - your best bet is to read a few SQL tutorials so you understand how to make the changes yourself, it really is. You'll be a much better developer for it.

bitprophet fucked around with this message at 15:47 on May 6, 2008

king_kilr
May 25, 2007
If you want schema migration I would check out django-evolution(on google code).

liquidfury
Jul 2, 2004

No Safe Word posted:

It's not just a known issue, it's just the way it's going to be. You have to recreate the database/tables when you make a change to the model. There was a schema-evolution branch in progress, but I don't know what is happening with it.

Alternately, manually make the changes :v:

I am not worried about loosing the data in the table. Is there a way I can force it to just recreate the models?

I know sql so going in and making changes isn't an issue, but I was much happier not having to. So if I added a foreign key relation to the class I just have to add a foreign key relation to the actual tables?

edit: fixed it. should have read django faq

liquidfury fucked around with this message at 22:31 on May 6, 2008

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?

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

hey mom its 420
May 12, 2007

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

No Safe Word
Feb 26, 2005

Bonus posted:

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

With "no" as an argument for extra fun.

Adbot
ADBOT LOVES YOU

Larry Horseplay
Oct 24, 2002

I've been trying to figure this out for a little bit, and I think I'm confused.

I'm trying to build a survey form. You know, the kind where it asks you questions and you fill in a circle for "Strongly Agree", "Agree," "Disagree", etc.

My model has each of those in an int field with a choices enum.

Now, the thing works fine. About an hour of coding, most of that typing all the questions into the verbose names, and it's done.

However, the widgets look like crap. The standard RadioSelect outputs as lists. No problem, right? I just wrote a custom renderer.

code:

class AgreeRadioRenderer(forms.widgets.RadioFieldRenderer):

    def render(self):
        return mark_safe(u'<tr>%s</tr>' % u'\n'.join([u'<td>%s</td>' % w for w in self]))

However, I can't get the text outside of each input tag to not render. So, each radio button has its choice next to it. "Strongly Agree," etc. I just want a radio button, no labels, no anything. How do I do this?

edit: I just blanked the strings in the enum structure. I don't know if this is the "right" way to do this, but it works.

Larry Horseplay fucked around with this message at 22:44 on May 7, 2008

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