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
Mulozon Empuri
Jan 23, 2006

SlightlyMadman posted:

This looks like it could do the trick. Pardon if this is a stupid question, but where do I put that? Can I just drop it in my app's admin.py file, or do I need to put it somewhere special? Additionally, is there a place I can override the User model to increase its max length?

I'd do what king_kilr says really. But yeah, throw it in admin.py in some app.

Check out this post perhaps.

Adbot
ADBOT LOVES YOU

SlightlyMadman
Jan 14, 2005

Mulozon Empuri posted:

I'd do what king_kilr says really.

That doesn't actually solve my problem at all. Like I said, I've already overridden the registration and authorization and have no problems there. The issue is that it can't be edited in the admin pages. In retrospect, I could have avoided this by just tossing a random string in the username, but the site is already live so it's too late for that.

Mulozon Empuri posted:

But yeah, throw it in admin.py in some app.

Check out this post perhaps.

Yes, this is exactly what I was looking for; thanks!

king_kilr
May 25, 2007
Wait, you can't edit their user in the admin, or you can't login?

chips
Dec 25, 2004
Mein Führer! I can walk!
My problem was not being able to edit in admin, not logging in. I just tried adding the form overloads, but that seemed to mess up and not work.

edit: Seems to be fixed now, now I can enter blank passwords in the user forms and email addresses in the username field - more importantly allowing me to actually edit users!

chips fucked around with this message at 12:46 on Jan 20, 2010

bmoyles
Feb 15, 2002

United Neckbeard Foundation of America
Fun Shoe
Are there any elegant pre-built solutions or snippets around that take care of content and data migration between environments?
Say I have a dev, integration, fqa, perf, and prod environment, and occasionally, I'll want to shuffle content between environments (refresh lower tiers with prod content, etc). Anything around to make that less painful?

Happycataclysm
Jan 11, 2005

The Fun Machine Took A Shit and Died
Just weighing in to say I'm a huge fan of Django. Last year I was fortunate enough to pick a technology to use for a site at work.

I learnt python and django as I went and constructed http://tardis.edu.au/ in about 6 weeks (including all back-end ingestion stuff and a non-python desktop tool). It's almost been a year since I started on it, and changing it up due to feedback and maintenance has been a breeze.

I also worked on a RoR project for most of last year. Found it too convoluted for its own good. Python has amazing readability.

nbv4
Aug 21, 2002

by Duchess Gummybuns
edit: nevermind

nbv4 fucked around with this message at 04:50 on Jan 21, 2010

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
Oooo, this is awesome, native-ish django in non-relational databases:
http://bitbucket.org/wkornewald/django-nonrel/wiki/Home

It's still got some work to go but my mediocre test app worked, pretty nice.

SlightlyMadman
Jan 14, 2005

I've got a generic template that's printing out the values of a dictionary, like so:
code:
<table>
{% for row in rows %}
<tr>
{% for col,val in row.items %}
<td>{{ val }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
Works great, but I can't figure out how to print headers. I've tried "for col,val in row.0.itmes" and things like "for col in row.0.keys" or "for col in row|first" but none of them seem to work. Any ideas? I'm sure it's something obvious, since the data is easily available.

SlightlyMadman fucked around with this message at 01:01 on Jan 28, 2010

bitprophet
Jul 22, 2004
Taco Defender

SlightlyMadman posted:

Works great, but I can't figure out how to print headers. I've tried "for col,val in row.0.itmes" and things like "for col in row.0.keys" or "for col in row|first" but none of them seem to work. Any ideas? I'm sure it's something obvious, since the data is easily available.

First, what exactly does your rows data stricture look like? A list of dicts? And what Django version are you using?

Prior to, I think, Django 1.2 (which is only in alpha or beta as of yet) doing {% for x,y,z in iterable %} was not possible, and your other attempts don't make syntactical sense given a list of dicts.

For reference, the pre-1.2 method of iterating over a dictionary looks like this:
code:
{% for tuple in mydict.items %}
Key: {{ tuple.0 }}<br />
Value: {{ tuple.1 }}<br />
{% endfor %}
So if your rows is a list of dicts ([{'a': 'b', 'c': 'd'}, {'foo': 5}]) you would replace your for loop with the above.

SlightlyMadman
Jan 14, 2005

Yeah, it's a list of dicts and I thought I was running the stable release, but I must be running 1.2, since the "for col,val in row.items" does work. To be clear, the code I posted works fine, I just want to know how to iterate just the keys of the first element, or something like that, so I can print the keys as column headers at the top of the table.

king_kilr
May 25, 2007

bitprophet posted:

First, what exactly does your rows data stricture look like? A list of dicts? And what Django version are you using?

Prior to, I think, Django 1.2 (which is only in alpha or beta as of yet) doing {% for x,y,z in iterable %} was not possible, and your other attempts don't make syntactical sense given a list of dicts.

For reference, the pre-1.2 method of iterating over a dictionary looks like this:
code:
{% for tuple in mydict.items %}
Key: {{ tuple.0 }}<br />
Value: {{ tuple.1 }}<br />
{% endfor %}
So if your rows is a list of dicts ([{'a': 'b', 'c': 'd'}, {'foo': 5}]) you would replace your for loop with the above.

Unpacking in templates has worked since before 1.0.

bitprophet
Jul 22, 2004
Taco Defender

king_kilr posted:

Unpacking in templates has worked since before 1.0.

I must be thinking of the updated if tag, then.

And I did the bulk of my Django work well before 1.0, so don't be talking like 1.0 was all that long ago, sonny :bahgawd:

king_kilr
May 25, 2007

bitprophet posted:

I must be thinking of the updated if tag, then.

And I did the bulk of my Django work well before 1.0, so don't be talking like 1.0 was all that long ago, sonny :bahgawd:

Trunk is the only stable branch!

nbv4
Aug 21, 2002

by Duchess Gummybuns
code:
    # for convenience 
    PopupFlightForm = myforms.PopupFlightForm
    
    # replace the default plane field with my new custom plane field
    PopupFlightForm.plane = myforms.text_plane_field

    print PopupFlightForm.plane.widget

    #now create the form
    form = PopupFlightForm(user=request.display_user, prefix="new")
    
    print form.fields['plane'].widget
the output is this:

code:
<django.forms.widgets.TextInput object at 0x26b8f90>
<django.forms.widgets.Select object at 0x26cd0d0>
forms.text_plane_field looks like this:

code:
text_plane_field = \
    TextPlaneField(
       required=True,
       queryset=Plane.objects.get_empty_query_set()
    )
TextPlaneField is a custom field I created which I know works because if I drop it in the class definition of the modelform (instead of trying to put it in in the view), it works fine.

The PopupFLightForm is a modelform with no overriding on the plane field. I want to override that field with my custom text_plane_field in the view. For some reason the act of calling __init__ is reverting my form back to using the default modelform field... Anyone know how to not have it do that? How are you supoposed to override form fields at runtime?

nbv4 fucked around with this message at 06:35 on Jan 28, 2010

Captain Capacitor
Jan 21, 2008

The code you say?

bitprophet posted:

I must be thinking of the updated if tag, then.

And I did the bulk of my Django work well before 1.0, so don't be talking like 1.0 was all that long ago, sonny :bahgawd:

Easy, gramps. Don't blow your stack now.

king_kilr
May 25, 2007
You cannot overide a field, or a widget by assigning to it in the manner you are. Fields on classes can be found in the Form.base_fields dictionary, fields in instances can be found in the Form().fields dictionary.

SlightlyMadman
Jan 14, 2005

So nobody has any advice for me? I just want to iterate through the keys of the first dict in a list of dicts. In python, I would do something like:

code:
foreach col in rows[0].keys:
    print col
It seems like I should be able to do this in a template:
code:
[% for col in rows.0.keys %}
{{ col }}
{% endfor %}
But that doesn't work.

edit: Nevermind, I just figured it out with the "forloop.first" property:
code:
<table>
»·······{% for row in rows %}
»·······<tr>
»·······»·······{% if forloop.first %}
»·······</tr><tr>
»·······»·······{% for col in row.keys %}
»·······»·······<td>{{ col }}</td>
»·······»·······{% endfor %}
»·······</tr><tr>
»·······»·······{% endif %}
»·······»·······{% for col,val in row.items %}
»·······»·······<td>{{ val }}</td>
»·······»·······{% endfor %}
»·······</tr>
»·······{% endfor %}
</table>

SlightlyMadman fucked around with this message at 18:01 on Jan 28, 2010

MonkeyMaker
May 22, 2006

What's your poison, sir?
Something I ran into this week that seems like a bug (maybe king_kilr can comment on it) and I didn't see it heavily commented on anywhere on the internet:

If you're using a custom auth backend, like I am to allow users to log in with either email address or username, and you move that backend from one location to other, again, like I did (common.backends to company_name.backends), you'll get all sorts of errors about not being able to find the old backend.

If you're like me, you'll delete all the .pyc files, triple-check everything and then poo poo your pants. None of these are the answer, though. Delete the contents of your django_session table. Django apparently stores the auth method and module location in the session_key or session_data SHAs.

Hope that helps.

nbv4
Aug 21, 2002

by Duchess Gummybuns

MonkeyMaker posted:

Something I ran into this week that seems like a bug (maybe king_kilr can comment on it) and I didn't see it heavily commented on anywhere on the internet:

If you're using a custom auth backend, like I am to allow users to log in with either email address or username, and you move that backend from one location to other, again, like I did (common.backends to company_name.backends), you'll get all sorts of errors about not being able to find the old backend.

If you're like me, you'll delete all the .pyc files, triple-check everything and then poo poo your pants. None of these are the answer, though. Delete the contents of your django_session table. Django apparently stores the auth method and module location in the session_key or session_data SHAs.

Hope that helps.

Hmm, I run into this problem sometimes too. One on my sites uses an OpenID backend, which works fine on the live site, but flat out doesn't work when I dump and copy all the data to my development server. Whenever I try to log in, I get an "integer out of range" error.

I just now truncated the session table but it still doesn't work...

MonkeyMaker
May 22, 2006

What's your poison, sir?

nbv4 posted:

Hmm, I run into this problem sometimes too. One on my sites uses an OpenID backend, which works fine on the live site, but flat out doesn't work when I dump and copy all the data to my development server. Whenever I try to log in, I get an "integer out of range" error.

I just now truncated the session table but it still doesn't work...

That's a completely different error. Mine was a typical 'failed to import' kind of error.

But feel free to post your errors and auth backend and we can look at it.

king_kilr
May 25, 2007
That's correct, Django stores the authbackend used in the session, along with the user id. I can't remember what problem this solves, but the comments probably give some indication.

Jonnty
Aug 2, 2007

The enemy has become a flaming star!

SlightlyMadman posted:


code:
[% for col in rows.0.keys %}
{{ col }}
{% endfor %}

Are you sure that doesn't work? It's much cleaner and looks like it should, apart from that square bracket at the start. Sure that wasn't the problem? Make sure the rows variable actually exists for the template, too.

SlightlyMadman
Jan 14, 2005

Jonnty posted:

Are you sure that doesn't work? It's much cleaner and looks like it should, apart from that square bracket at the start. Sure that wasn't the problem? Make sure the rows variable actually exists for the template, too.

Ah, the square bracket may well have been it. I'm going to stick with using the .first property though, because it feels cleaner in that I don't have to explicitly check that rows isn't empty first.

ATLbeer
Sep 26, 2004
Über nerd
Just an FYI of something that I bumped into. Not specifically Django related but, you can run into it.


When a unicode character is passed into an ORM statement

example ("& #9829;" = ♥ but, vBul alters it below)
code:
some_user_input_from_form = "&#9829;"
YourModel.objects.filter(field = some_user_input_from_form)
An MySQLdb.OperationalError is thrown. That's not a problem until you try to catch it. MySQLdb.OperationalError is WAY too broad. It covers Collation errors (which the above is) and things like DB connect errors, DB memory errors, etc. So you can catch these collation errors but, you'll also silence a lot of other errors that you may want to handle.

Of course this only happens if your DB tables are not UTF-8 but, it looks like the default for MySQL might be latin1 so, unless you changed it before, you probably are running latin1.

The way we are catching it currently is by casting the user input into a string and catching the UnicodeEncodeError and handling that error instead of the OperationalError.

Just another FYI, never trust any user input, ever.

bitprophet
Jul 22, 2004
Taco Defender

ATLbeer posted:

An MySQLdb.OperationalError is thrown. That's not a problem until you try to catch it. MySQLdb.OperationalError is WAY too broad.

This poo poo (exceptions which are far, far too generic) pisses me off so much. I run into it in a few other pieces of software which my code is a client of, and boy howdy does it make my life difficult :argh:

You didn't mention this but sometimes, if you're lucky, you can introspect the exception's string value or other elements (depends on who wrote the exception and what they do with it) and derive additional meaning from that. Though I still find it nasty to have to hard-code that sort of comparison.

MonkeyMaker
May 22, 2006

What's your poison, sir?

bitprophet posted:

This poo poo (exceptions which are far, far too generic) pisses me off so much. I run into it in a few other pieces of software which my code is a client of, and boy howdy does it make my life difficult :argh:

Much like psycopg2's "Programming Error" when you have some bad SQL.

ATLbeer
Sep 26, 2004
Über nerd

bitprophet posted:

if you're lucky, you can introspect the exception's string value or other elements (depends on who wrote the exception and what they do with it) and derive additional meaning from that. Though I still find it nasty to have to hard-code that sort of comparison.

I tried that as a patch but, drat was it ugly. I also didn't like to be dependent upon the fact that the exception might not change but, there's never a guarantee that the text of the error in the exception might change in MySQLdb (which I was never a big fan of, I'm falling into the dislike category now)

It's less hacky than inspecting the exception information but, I think the solution of forcing the exception before possible reaching the OperationalError stage is a slightly better solution.

Has anyone used anything like ( https://launchpad.net/myconnpy )? A pure Python MySQL connector would be much nicer than the current MySQLdb connector.

king_kilr
May 25, 2007
I haven't used it, but there's also `oursql`. There's actually a backend for django that uses it, but no comments on it's quality (David Cramer wrote it). our sql uses Cython extensively as far as I know.

nbv4
Aug 21, 2002

by Duchess Gummybuns
I wrote a custom middleware class that basically looks to see if the url has a username variable in it, and if it does, it turns that username into a user object, and then adds it to the display_user variable on the request object. In my views and in my templates I can do request.display_user and it works fine. But if I try to access that variable in a context processor, it doesn't work. I'm guessing context processors are evaluated before middleware, correct? Is there a way around this?

king_kilr
May 25, 2007
That's not necessarily correct, it depends which middleware method you've implemented, but process request or process view both occur before your template context processor.

nbv4
Aug 21, 2002

by Duchess Gummybuns

king_kilr posted:

That's not necessarily correct, it depends which middleware method you've implemented, but process request or process view both occur before your template context processor.

Are you sure? My middleware sets the request variable in a process_view method. Yet my context processor is raising an AttributeError...

king_kilr
May 25, 2007
Beyond reproach. http://code.djangoproject.com/browser/django/trunk/django/core/handlers/base.py#L91 is how django processes a request:

You'll see that it resolve the view, applies the view middleware (the process_view methods), and *then* it calls your view. Context processors are only called when you go to render your template and call RequestContext.

nbv4
Aug 21, 2002

by Duchess Gummybuns
you know what, I'm loving stupid. In my context processor I had

getattr("request", "display_user")

instead of

getattr(request, "display_user")

:ughh:

king_kilr
May 25, 2007
Oh my :v: Friendly reminder:

request.display_user

You're using a constant string, no need to call getattr.

taqueso
Mar 8, 2004


:911:
:wookie: :thermidor: :wookie:
:dehumanize:

:pirate::hf::tinfoil:

I'm trying to create a context processor that will fill in a variable with the menu data for a superfish menu. I made a really simple processor:
code:
def navlist(request):
	return {'nav': 'test'}
This is in the file context_processor.py, in the context_processors directory along with an __init__.py.

I added this line to TEMPLATE_LOADERS:
code:
	'context_processors.context_processor.navlist',
Now I get the AttributeError "'function' object has no attribute 'is_usable'"

I'm really new to django, but from the examples I've seen it seems like making a context processor should be easy. What am I doing wrong?

I am thinking I might try using a custom template tag that I put in my base template. Is one method preferred over the other?

bitprophet
Jul 22, 2004
Taco Defender

taqueso posted:

I added this line to TEMPLATE_LOADERS

Surely you meant TEMPLATE_CONTEXT_PROCESSORS? :)

taqueso
Mar 8, 2004


:911:
:wookie: :thermidor: :wookie:
:dehumanize:

:pirate::hf::tinfoil:

bitprophet posted:

Surely you meant TEMPLATE_CONTEXT_PROCESSORS? :)

I surely did. Thank you for the help, I knew it had to be something stupid on my part.

MonkeyMaker
May 22, 2006

What's your poison, sir?
Does anyone have a good guide to writing a new backend to Django Registration? Or, really, just answering my one problem. I need to require a first and last name for any new users. I've tried two or three tutorials that I've found online and they haven't worked. Bennet, as awesome as he is, hasn't provided any examples of this kind of interaction.

Adbot
ADBOT LOVES YOU

king_kilr
May 25, 2007
Reading through the code it looks like your backend needs to implement get_form_class and return a Form subclass that includes first and last name fields. And then a register method that takes those values and attaches them to the User instance.

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