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
Hanpan
Dec 5, 2004

I'm having some trouble figuring out how to update the user table with Django 1.2. I've created my own custom form:

code:
from django.forms import ModelForm
from django.contrib.auth.models import User

class BasicAccountForm(ModelForm):
    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email')
And I'm updating it like so:

code:
elif 'accountFormSubmit' in request.POST:
            accountForm = BasicAccountForm(request.POST, instance=request.user)
            if accountForm.is_valid():
                accountForm.save()
                messages.success(request, 'Account updated succesfully.')
It works fine, but I'd like it so the user has to enter a valid email address... currently it doesn't seem to validate the email field at all. Is there anything I can add to my BasicAccountForm in order to force a valid email in this field?

Adbot
ADBOT LOVES YOU

nbv4
Aug 21, 2002

by Duchess Gummybuns
does anyone know how to create a signal for all inherited model classes?

code:
class GenericModel(models.Model):
    [some stuff]

class SpecificModel1(GenericModel):
    [more stuff]

class SpecificModel2(GenericModel):
    [even more stuff]

### signals

def set_up(sender, **kwargs):
    print "setup"

    model = kwargs['instance']
    model.set_up()
    
models.signals.post_save.connect(set_up, sender=GenericModel)
I want this signal to work on all inherited models of GenericModel. Possible without registering the signal for each inherited model?

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

nbv4 posted:

does anyone know how to create a signal for all inherited model classes?

code:
class GenericModel(models.Model):
    [some stuff]

class SpecificModel1(GenericModel):
    [more stuff]

class SpecificModel2(GenericModel):
    [even more stuff]

### signals

def set_up(sender, **kwargs):
    print "setup"

    model = kwargs['instance']
    model.set_up()
    
models.signals.post_save.connect(set_up, sender=GenericModel)
I want this signal to work on all inherited models of GenericModel. Possible without registering the signal for each inherited model?

What's wrong with this? You could even use range and getattr if the naming scheme just uses numbers like that.

code:
for model in [SpeficifModel1, SpecificModel2, ...]:
  models.signals.post_save.connect(set_up, sender=model)

nbv4
Aug 21, 2002

by Duchess Gummybuns

Jonnty posted:

What's wrong with this? You could even use range and getattr if the naming scheme just uses numbers like that.

code:
for model in [SpeficifModel1, SpecificModel2, ...]:
  models.signals.post_save.connect(set_up, sender=model)

eh I don't really like that because if I add a new SpecificModel later on and forget to add it to the list, it could potentially lead to hard to catch errors. What I ended up doing was modifying the save() method on the GenericModel. I'd still rather use signals, but eh.

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.
You might be able to achieve what you want using a metaclass to register the signal.

Ferg
May 6, 2007

Lipstick Apathy
Anybody know what might cause all email messages sent via Django to go to a users spam filter? This would include both messages sent via send_mail() and password reset emails. More of a generic, non-Django question I suppose, but hopefully somebody has come across it.

Hughlander
May 11, 2005

Ferg posted:

Anybody know what might cause all email messages sent via Django to go to a users spam filter? This would include both messages sent via send_mail() and password reset emails. More of a generic, non-Django question I suppose, but hopefully somebody has come across it.

Depending on the email take a look at the headers that the provider added. Some add score to tell you why it went like that. Could be the return path, could be that you don't have SPF set up, etc...

Ferg
May 6, 2007

Lipstick Apathy

Hughlander posted:

Depending on the email take a look at the headers that the provider added. Some add score to tell you why it went like that. Could be the return path, could be that you don't have SPF set up, etc...

This is the best I could gather (via Gmail). The domain name is swapped to be myapp.com:

code:
Received-SPF: neutral (google.com: 173.203.223.116 is neither permitted nor denied by best guess record for domain of [email]support@myapp.com[/email]) client-ip=173.203.223.116;
Authentication-Results: mx.google.com; spf=neutral (google.com: 173.203.223.116 is neither permitted nor denied by best guess record for domain of [email]support@myapp.com[/email]) smtp.mail=support@myapp.com
Maybe it's just my spam filter that's being a bit too strict?

Hughlander
May 11, 2005

Ferg posted:

This is the best I could gather (via Gmail). The domain name is swapped to be myapp.com:

code:
Received-SPF: neutral (google.com: 173.203.223.116 is neither permitted 
nor denied by best guess record for domain of [email]support@myapp.com[/email]) client-ip=173.203.223.116;
Authentication-Results: mx.google.com; spf=neutral (google.com: 173.203.223.116 
is neither permitted nor denied by best guess record for domain of [email]support@myapp.com[/email]) smtp.mail=support@myapp.com
Maybe it's just my spam filter that's being a bit too strict?

I'd just set up SPF, send another mail through G-Mail to confirm it worked and call it a day...
What you're looking to see is:
Received-SPF: pass (google.com: domain of support@myapp.com designates 173.203.223.116 as permitted sender) client-ip=173.203.223.116;
Authentication-Results: mx.google.com; spf=pass (google.com: domain of support@myapp.com designates 173.203.223.116 as permitted sender) smtp.mail=support@myapp.com

Doh004
Apr 22, 2007

Mmmmm Donuts...
I'm moving my my Django portfolio site to a Wordpress site merely because I don't need Django to do it, and Wordpress can achieve everything I'd want with the site out of the box. Not dissing Django, just not necessary for my needs. Anyways, my problem:

I used this tutorial (http://www.nerdydork.com/setting-up-django-on-a-whm-cpanel-vps-liquidweb.html) to setup my website. It had me doing that wonky creating a .conf for my website and running a Cpanel script that adds the conf file into the Apache installtion. I understand what it's doing, but that's not my issue. My issue is that I want to get rid of that item that sends all of my traffic from the root of my domain via the wsgi script, and instead revert back to its regular functionality.

Aside from recreating my account on my webserver (it's my own dedicated with full root access, so that's not an issue), how can I easily stop the whole relaying thingy mabober.

This may be suited for a different topic, but figured someone else may have this problem.

No Safe Word
Feb 26, 2005

Quick, register for Django Dash

http://djangodash.com/

Registration closes Saturday! Competition starts next Friday!

HIERARCHY OF WEEDZ
Aug 1, 2005

I'm having trouble finding the right thing to test. It's a business rule that a Foo is allowed to have many Bars. However, any real test of that would basically just be testing Django's One-to-many manager on the Foo object.

Is this a reasonable test? I can't think of a better way to make sure the framework corresponds to a business requirement.

code:
from models import Foo

from django.test import TestCase

class TestFoo(TestCase):
    def test_foo_can_have_many_bars(self):
        self.assertTrue(hasattr(Foo, 'bar_set'))

king_kilr
May 25, 2007
Honestly, that's not something I'd bother to test. Test that the views that add it (or where it comes from, unless it's the admin) work. Testing that you actually wrote
code:
fizzle = models.ForeignKey(Foo)
is a waste of time.

HIERARCHY OF WEEDZ
Aug 1, 2005

Yeah, that's what I figured. Thanks!

ATLbeer
Sep 26, 2004
Über nerd
For models, the only thing I test are additional methods or manager that are added. No reason to test the basics of the models themselves

Ferg
May 6, 2007

Lipstick Apathy
How can I pull an inline admin form value out from within a template? I'm customizing the TabularInline template for a UserPhoto's model so that administrators can see the photo on the admin site. However, that requires me to construct a URL dynamically which includes the User ID (foreign key) for a UserPhoto object. I've found an 'inline_admin_form.fk_field' object but can't find documentation on actually getting the value, only the name of the field (via label_tag).

Profane Obituary!
May 19, 2009

This Motherfucker is Dead
I resisted Pinax for the longest time because i didn't think I needed it. I just started playing around with it and i can easily say it is amazing. If you havn't tried it out yet you should.

ErIog
Jul 11, 2001

:nsacloud:
I have a strange question that's really making me go insane. I'm using Django for an internal web app I'm developing for my company. This app is going to be for managing metadata about high quality scanned magazine pages sitting on a NAS with 16TB of capacity. I have that NAS mounted as a share on my web server. I can access it fine. When I "su" to the apache user the apache user can access it fine.

I'm implementing my import process for that material, but I'm having a really annoying issue. When I do this:
code:
os.listdir("/mount/point/of/my/NAS/share")
from within one of my Django views I get no response back. This doesn't happen when I launch a development server through manage.py. This only happens when Django is being served through Apache. This also doesn't happen when I run the development server as the apache user. This doesn't happen with any directory other than the mount point for that share. If I do os.listdir("/") in that view, I get the proper response back.

This only happens when httpd is serving my Django app which means that I've built this drat thing. I know it works. I've tested it, but it doesn't work in a production setting.

I realize it's odd I'm doing this, but my system has to be able to allow end users to choose which files from the NAS are imported into the system. I'm not trying to serve that directory through apache. I'm just using os.listdir to populate a bunch of javascript selector boxes that allow the user to choose what to import. I'm not moving 16TB of images to the web server when the whole point of this system is to allow people to work with the data from that NAS without waiting 2 minutes to flip between pages.

I'm running Django 1.3 alpha on CentOS 5 through mod_python on Apache 2.2.3.

ErIog fucked around with this message at 23:03 on Aug 23, 2010

king_kilr
May 25, 2007
hrm does:

code:
from subprocess import call
data = call(["ls", "/mount/point/of/your/nas/share/"])
work?

ErIog
Jul 11, 2001

:nsacloud:

king_kilr posted:

hrm does:

code:
from subprocess import call
data = call(["ls", "/mount/point/of/your/nas/share/"])
work?

I'll try that, but I really would like to avoid doing that if at all possible. There's something that feels so unclean about parsing ls output.

Captain Capacitor
Jan 21, 2008

The code you say?

ErIog posted:

I'm running Django 1.3 alpha on CentOS 5 through mod_python on Apache 2.2.3.

You know, I hate to be that guy but, have you tried mod_wsgi? I had no end of problems with mod_python and I'd highly suggest you evaluate it as an option, if you can.

ErIog
Jul 11, 2001

:nsacloud:

Captain Capacitor posted:

You know, I hate to be that guy but, have you tried mod_wsgi? I had no end of problems with mod_python and I'd highly suggest you evaluate it as an option, if you can.

Yeah, I'll look into it. I've decided my dev environment probably isn't suitable for the production system anyway. Apache + mod_python generally feels sluggish compared to even the manage.py runserver command.

I played around with moving everything over to Fedora + nginx. So switching to mod_wsgi isn't a big deal compared to that.

I like the idea of CentOS, but it's the most annoying thing in the world to know there's a feature or fix for some issue that is nigh on impossible for you to utilize since you're lagged behind like a year for all packages.

Update!:

It's a good thing you were that guy. I did not go with your mod_wsgi recommendation, but I did get my stuff to work. On a lark I did "yum search nginx", and found a version of nginx in the EPEL CentOS 5 repo. I installed it, configured it, and it runs my script beautifully. It's so much faster and cleaner than apache + mod_python.

ErIog fucked around with this message at 17:26 on Aug 24, 2010

MonkeyMaker
May 22, 2006

What's your poison, sir?

ErIog posted:

Yeah, I'll look into it. I've decided my dev environment probably isn't suitable for the production system anyway. Apache + mod_python generally feels sluggish compared to even the manage.py runserver command.

I played around with moving everything over to Fedora + nginx. So switching to mod_wsgi isn't a big deal compared to that.

I like the idea of CentOS, but it's the most annoying thing in the world to know there's a feature or fix for some issue that is nigh on impossible for you to utilize since you're lagged behind like a year for all packages.

Update!:

It's a good thing you were that guy. I did not go with your mod_wsgi recommendation, but I did get my stuff to work. On a lark I did "yum search nginx", and found a version of nginx in the EPEL CentOS 5 repo. I installed it, configured it, and it runs my script beautifully. It's so much faster and cleaner than apache + mod_python.

To be another "that guy", you could also try just using gunicorn. It's a lot faster to set up than nginx (not that nginx is hard to set up) and it's just a Python package so you don't have to worry about CentOS being lagged or not.

king_kilr
May 25, 2007

MonkeyMaker posted:

To be another "that guy", you could also try just using gunicorn. It's a lot faster to set up than nginx (not that nginx is hard to set up) and it's just a Python package so you don't have to worry about CentOS being lagged or not.

You shouldn't be using gunicorn in place of nginx, you should use it in addition to nginx in replacement of mod_wsgi.

bitprophet
Jul 22, 2004
Taco Defender

king_kilr posted:

You shouldn't be using gunicorn in place of nginx, you should use it in addition to nginx in replacement of mod_wsgi.

People respond better if you tell them why something is instead of just dictating it ;)

GUnicorn is intended to be used behind a "real" Web server that is better able to handle actual browser-based clients, such as Apache or NginX. GUnicorn's design is such that it assumes the clients speaking to it will be fast -- see GUnicorn's design doc and also the PHILOSOPHY document for the original Unicorn project.

So while yes, it does speak HTTP, it's supposed to be paired up with some sort of general-purpose frontend server and not run standalone.

nbv4
Aug 21, 2002

by Duchess Gummybuns
more like GOONicorn

MonkeyMaker
May 22, 2006

What's your poison, sir?

king_kilr posted:

You shouldn't be using gunicorn in place of nginx, you should use it in addition to nginx in replacement of mod_wsgi.

Yeah, sorry for the confusion. I wasn't thinking.

Gunicon for Python, nginx for images/css/js/etc.

wins32767
Mar 16, 2007

Is there a handy overview to generic views? The docs have a detailed reference page which links to a "overview" the entirety of which is a link back to the reference page.

EDIT: Are Django "views" are really controllers from MVC? It seems like all the presentation aspects are handled by the template.

wins32767 fucked around with this message at 14:36 on Sep 10, 2010

Lamacq
Jun 15, 2001

Breezeblock RIP

wins32767 posted:

Is there a handy overview to generic views? The docs have a detailed reference page which links to a "overview" the entirety of which is a link back to the reference page.

EDIT: Are Django "views" are really controllers from MVC? It seems like all the presentation aspects are handled by the template.

That looks like a bug in the documentation; there is no separate "topic guide" page for generic views. The page you're looking at is it. That said, in my opinion generic views aren't really that useful. About the only thing I use them for is when I'm stubbing out my views when first building an app, since just about any app is going to have the usual list/detail views for its models and generic views get you about 80% of the way there with very little work (you still have to write the template of course).

The thing is though, once you start to actually put the finishing touches on your app and implementing all your features you end up having to wrap the generic views anyway so you might as well just rewrite the view yourself.

RE: the MVC thing, my understanding is that in Django-think the framework itself is the controller. See this FAQ.

wins32767
Mar 16, 2007

Lamacq posted:

That looks like a bug in the documentation; there is no separate "topic guide" page for generic views. The page you're looking at is it. That said, in my opinion generic views aren't really that useful. About the only thing I use them for is when I'm stubbing out my views when first building an app, since just about any app is going to have the usual list/detail views for its models and generic views get you about 80% of the way there with very little work (you still have to write the template of course).

The thing is though, once you start to actually put the finishing touches on your app and implementing all your features you end up having to wrap the generic views anyway so you might as well just rewrite the view yourself.

RE: the MVC thing, my understanding is that in Django-think the framework itself is the controller. See this FAQ.
Thanks. I kept trying to figure out how the views generically handled HTML generation and got really confused.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
That's the way I've seen it, the views are the controllers.

MonkeyMaker
May 22, 2006

What's your poison, sir?

wins32767 posted:

Is there a handy overview to generic views? The docs have a detailed reference page which links to a "overview" the entirety of which is a link back to the reference page.

EDIT: Are Django "views" are really controllers from MVC? It seems like all the presentation aspects are handled by the template.

Not to toot any horns I may own, but I did a screencast (as part of a series) over Generic Views the other day.

You can watch it here if you want.

nbv4
Aug 21, 2002

by Duchess Gummybuns
they're most likley going to redo the generic views for 1.3 to be class based, which will make them approximately 3459864578346% less useless.

Yay
Aug 4, 2007

nbv4 posted:

they're most likley going to redo the generic views for 1.3 to be class based, which will make them approximately 3459864578346% less useless.
Hopefully they'll make things like the generic view for update (and formpreview, and formwizard, I think?) somehow take instances, every time I have to write an update form that might do something 'a bit clever', I wish I could just wrap the boilerplate-saving view.

Mulozon Empuri
Jan 23, 2006

The vids from djangocon 2010 are up. Good quality videos this year and some pretty interesting talks.

Sock on a Fish
Jul 17, 2004

What if that thing I said?
I'm repeating myself in some form validation code for separate forms that use some of the exact same fields.

Is the accepted way to solve this problem to define the validation function outside of the forms, have the clean_field_x() function in the form class do nothing, then override __init__ and after calling the superclasse's __init__ assign self.clean_field_x to the shared validation function?

Is there a better way?

edit: duh, define clean_field_x in a superclass

Sock on a Fish fucked around with this message at 18:02 on Oct 4, 2010

bmoyles
Feb 15, 2002

United Neckbeard Foundation of America
Fun Shoe
This is kind of a dumb question, I suspect, but it's been driving me nuts (and I'm probably missing something obvious).
I have a model that essentially represents an audit trail of checkins by a system. The name of the system, IP of the system, and the date/time the system checked in are recorded.

We frequently want to reference the most recent "heartbeat" or check-in per-system.

I can do this:
code:
SiteMonitoring.objects.values('site_name').annotate(last_heartbeat=Max('site_heartbeat'))
and get a ValuesQuerySet back that has the name of each distinct site (values w/ annotate implies a group by clause), along with the most recent timestamp.

What I am going nuts trying to do is include the ip_address field in that resultset.

If that query generates something (like)
code:
select site_name, max(site_heartbeat) as last_heartbeat from sitemonitoring group by site_name
Is there a way to add another field to that select, but not to the group by, without doing raw SQL?
That is,
code:
select site_name, ip_address, max(site_heartbeat) as last_heartbeat from sitemonitoring group by site_name
I've tried various forms of .extra, .values, etc, and my request for the field is ignored (using extra) or it's lumped in with the group by (when I add a field to values()). Any thoughts?

(for reference, the schema I'm dealing with is fixed, so as a constraint, I cannot add, change, or remove fields).

king_kilr
May 25, 2007
No, postgres (and the SQL standard AFAIK) requires that any non-aggregate listed in the select clause must also appear in the group by clause.

bmoyles
Feb 15, 2002

United Neckbeard Foundation of America
Fun Shoe
So my latter query succeeds due to a deficiency in MySQL then :\

http://dev.mysql.com/doc/refman/5.1/en/group-by-hidden-columns.html

Yay.

So what might be a better solution?

Also assume that I have a site model that relates to the sitemonitoring model by the site_name field, but is not defined as an explicit foreign key (existing legacy schema, Django grafted on top). Since the schema is managed outside DJango, can Iie to Django and make sitemonitoring.site_name a foreign key to site.site_name?

I would like to try to avoid joins (but can cope) as the DB is MySQL NDBCLUSTER, which will execute joins but can take a significant perf penalty for doing so. We end up doing a lot of ugly denormalization to work around that :\

Adbot
ADBOT LOVES YOU

Doh004
Apr 22, 2007

Mmmmm Donuts...
What am I doing wrong? I just want to select stuff after a certain date:

code:
last = request.POST['lastUpdate'];
l_datetime = time.strptime(last, "%H:%M %m/%d/%Y")
newMessages = Message.objects.filter('when' >= l_datetime)
I get a "TypeError: unpack non-sequence". I tried Googling selecting stuff after a certain date, and it all looked convoluted. This isn't that difficult to do :(

*edit*

Found the __lte functionality. Trying to get my time in that format... Hopefully it works :smith:

Doh004 fucked around with this message at 18:46 on Oct 13, 2010

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