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
bitprophet
Jul 22, 2004
Taco Defender

nbv4 posted:

Actually you're right. I was confused. The problem I was having was if the user isn't logged in, get_profile returns nothing. In that case, I'm pretty sure the only solution is to use a context processor, in order to make a profile object regardless if the user is logged in or not.

Yes, that's a perfect use of a context processor :) because that's something you'd have to repeat in all your templates or views and which can't be easily done in the templates.

Adbot
ADBOT LOVES YOU

The Red Baron
Jan 10, 2005

I'm still kind of a nublet at python/django, but I wrote up a little post on how to easily add reCAPTCHA support to django 1.0, since pretty much all of the examples I found online were for the old version of the comments framework. Hopefully someone will find it useful.

If I'm doing/explaining something wrong or inefficient, please let me know :)

hitze
Aug 28, 2007
Give me a dollar. No, the twenty. This is gonna blow your mind...

I know this is a dumb question and there's probably a simple answer to it. How can I update a field when a view if accessed? Like the view is hit and it adds +1 to a value. I figured out how to do this easily with PHP/CodeIgniter, but Django has me stumped again.

nbv4
Aug 21, 2002

by Duchess Gummybuns
All the data models in my site are very heavily user centric. All data has a "owner", and only the owner ever looks at and edits that data. For instance a user will create a character or something, but that one user is the only person who will ever see that character. How can I define this concept in the data model?

When the user adds a new character, he will choose from a dropdown box various items for that character to have (such as a hat or a cane). I only want the item the user "owns" to be in that dropdown box. This is how just about 100% of my data models are going to end up working. I basically want

code:
characters.object.all()
to by default only return the items that the user owns. Is there an elegant DRY-friendly way of doing this?

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"

nbv4 posted:

I basically want

code:
characters.object.all()
to by default only return the items that the user owns. Is there an elegant DRY-friendly way of doing this?

Use a custom manager method. You'd create something like a PerUserManager, add a .for_user() method, and call it like this:

code:
characters.objects.for_user (request.user)

bitprophet
Jul 22, 2004
Taco Defender

hitze posted:

I know this is a dumb question and there's probably a simple answer to it. How can I update a field when a view if accessed? Like the view is hit and it adds +1 to a value. I figured out how to do this easily with PHP/CodeIgniter, but Django has me stumped again.

What do you mean by "a field"? A field in the database? I'm assuming you have some sort of, say, page-hit-count table with 2 columns (view name, integer count), in which case you'd do something like this:

code:
def myview(request):
    counter = Counter.objects.get_or_create(view='myview')
    counter.count += 1
    counter.save()
    return the_page()
Now, if this is something you want to apply to a lot of different pages, you'd probably want to move this logic out of the view and into a middleware, which would be cleaner.

nbv4
Aug 21, 2002

by Duchess Gummybuns
I'm trying to port over a webapp I wrote in PHP to Django. In my PHP site, I stored the user's password as a sha246 hash from the userid, the user's password, and then a random string of letters, all concatenated together. So if your userid number was 25 and your password was "poopypants", it would store the sha256 hash of "25popypantsfdshjfdshjsdf".

Is there anyway to have django authenticate users this way? I'd really rather not have my entire site create a new password when I switch over...

proddo
Mar 13, 2006

A++ would club again

nbv4 posted:

I'm trying to port over a webapp I wrote in PHP to Django. In my PHP site, I stored the user's password as a sha246 hash from the userid, the user's password, and then a random string of letters, all concatenated together. So if your userid number was 25 and your password was "poopypants", it would store the sha256 hash of "25popypantsfdshjfdshjsdf".

Is there anyway to have django authenticate users this way? I'd really rather not have my entire site create a new password when I switch over...

Write your own authentication backend. In it, define an authenticate() method that does whatever custom authentication (reading from your database, hashing the given password, comparing them...) and returns a Django User (if login successful) and None if the login didn't work, and also a get_user() method.

http://www.djangoproject.com/documentation/authentication/#other-authentication-sources

evilmonkeh
Apr 18, 2004
meh
I'm using django to keep a simple order database (in addition to many other things).

I've got a model called 'hoody' which contains fields 'paid_for' and 'collected', and can be either Y or N. These show up in the admin list, but I'd like a way of editing these easily directly from the main list. Is this possible?

bitprophet
Jul 22, 2004
Taco Defender

evilmonkeh posted:

I'm using django to keep a simple order database (in addition to many other things).

I've got a model called 'hoody' which contains fields 'paid_for' and 'collected', and can be either Y or N. These show up in the admin list, but I'd like a way of editing these easily directly from the main list. Is this possible?

In the admin? No, not without altering the admin's templates, which is semi-easy for some cases, but I think that's mostly the forms and not the listing pages. Not sure.

Depending on what you're doing with the site, and if you need to do not-entirely-common things like what you describe, you'll probably want to ignore the admin and just write things from scratch (which is a lot easier than it sounds, with generic views).

Larry Horseplay
Oct 24, 2002

I'm writing a survey application. For items that have multiple checkbox entries (i.e. pick as many choices as you want), I was thinking of using a CommaSeparatedIntegerField in my model, and a MultipleChoiceCheckbox in the form. Is the the "right" way to do this?

bitprophet
Jul 22, 2004
Taco Defender

Larry Horse posted:

I'm writing a survey application. For items that have multiple checkbox entries (i.e. pick as many choices as you want), I was thinking of using a CommaSeparatedIntegerField in my model, and a MultipleChoiceCheckbox in the form. Is the the "right" way to do this?

Guess it depends on what exactly you need to do with those values on the query side of things, but it could be an OK choice, nothing obviously wrong with it that I can see.


Also, hooray! the book is officially out. Got my hard copies last night. Here's a crappy iPhone photo:

mwarkentin
Oct 26, 2004
Any samples from the book available? How does it compare to Practical Django Projects?

Larry Horseplay
Oct 24, 2002

bitprophet posted:

Guess it depends on what exactly you need to do with those values on the query side of things, but it could be an OK choice, nothing obviously wrong with it that I can see.


Also, hooray! the book is officially out. Got my hard copies last night. Here's a crappy iPhone photo:


Congrats!

Most likely I'll just be exporting stuff to XLS sheets for people in my organization to play with for now, so I don't think the comma separated integers will be an issue. Thanks!

king_kilr
May 25, 2007

bitprophet posted:

Guess it depends on what exactly you need to do with those values on the query side of things, but it could be an OK choice, nothing obviously wrong with it that I can see.


Also, hooray! the book is officially out. Got my hard copies last night. Here's a crappy iPhone photo:


Congrats! How is pbx doing? I remember hearing he was in a bad car accident over the summer.

hey mom its 420
May 12, 2007

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

bitprophet
Jul 22, 2004
Taco Defender
Thanks guys :blush:

Paul is doing a lot better, king_kilr, as far as I can tell he's fully physically recovered and I think he's mostly up to speed in terms of his work and personal life. He wasn't able to really get back into the book until after we'd sent off the last edits, but he's curating the website.

Which isn't much of a website right now, but we're putting up an aborted appendix (it's a list of links; we felt it would work better as part of the website), and will try to package up our sample applications for download, soonish.

king_kilr
May 25, 2007
Just looked through the index for your book, and I have to say the examples sound really cool, I can't wait to check it out.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

bitprophet posted:

Guess it depends on what exactly you need to do with those values on the query side of things, but it could be an OK choice, nothing obviously wrong with it that I can see.


Also, hooray! the book is officially out. Got my hard copies last night. Here's a crappy iPhone photo:

Hooray! Tell me it's updated for 1.0 :)

Also, slightly off topic - I've started fleshing out an outline for a book I'm pondering, except I've never written something that expansive - I'd be interested in hearing how you approached it and how it went for you.

m0nk3yz fucked around with this message at 14:09 on Oct 31, 2008

bitprophet
Jul 22, 2004
Taco Defender

m0nk3yz posted:

Hooray! Tell me it's updated for 1.0 :)

Take a closer look at the photo ;) specifically the upper right quadrant. Think circles.

quote:

Also, slightly off topic - I've started fleshing out an outline for a book I'm pondering, except I've never written something that expansive - I'd be interested in hearing how you approached it and how it went for you.

It's a significant effort, especially if you're going to do it solo (while I ended up doing more than half the work for our book, it was still very much a team effort, and I believe that made a big difference). We're talking no social life and no free time (well, no non-guilty free time) for a year or two or even three, depending on the process and the timeliness of the material. At least if you're balancing the book with a full-time job.

I was also fortunate in that I didn't have to sell the book to a publisher -- Wes has written books before (Core Python Programming) and so he had a strong relationship with Pearson already. So we didn't just have a foot in the door, we were already sleeping on the couch, so to speak. And even so, we still spent a bit of money on having a legally inclined individual look over the contract with us. If you don't have a contact at an interested publisher, I hear that getting one can be a big chore in and of itself. I could probably hook you up with Wes, I'm sure he has stories about CPP.

In terms of writing the book itself, my main regret is not spending a constant amount of time on it; it was more like slacking off earlier on and then really getting into it towards the end. I wish I'd evened it out more. This comes back to the idea of time -- even if you could jot down your ideas in N hours, like all other creative works you really need to re-examine it multiple times, and then there's a nontrivial time allotment for the back-and-forth with publisher staff during the copyediting and layout phases.

Uh...that's a bit of a ramble, sorry! :) let me know if you have specific questions, that might help. We might also want to take this off-thread, it's kind of off-topic :)

nbv4
Aug 21, 2002

by Duchess Gummybuns

Janin posted:

Use a custom manager method. You'd create something like a PerUserManager, add a .for_user() method, and call it like this:

code:
characters.objects.for_user (request.user)

What about a whole new manager? Like "characters.mine.all()", which list all of my characters? That seems like the most logical way of doing it. The only problem is I can't quite figure out how to tell the manager who "I" am...

bitprophet posted:


Also, hooray! the book is officially out. Got my hard copies last night. Here's a crappy iPhone photo:

hmm, I'm in the market for a django book. Does your book spend a lot of time explaining beginner concepts, or does it focus more on how to get things done in django?

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

bitprophet
Jul 22, 2004
Taco Defender

nbv4 posted:

hmm, I'm in the market for a django book. Does your book spend a lot of time explaining beginner concepts, or does it focus more on how to get things done in django?

We definitely go over the basics; there's even a smallish chapter towards the beginning that just makes sure the reader is up to speed on general Web development concepts, without mentioning anything specifically technical.

I wrote that particular chapter because I found a lot of newbies, even if they knew "Web development" coming from PHP or ASP (or any Web language which is generally implemented via simple scripts), had never actually been shown the Big Picture, and so had some initial conceptual problems when using a framework that basically models HTTP.

The first half of the book basically goes Python primer (a decently sized one :)) => whirlwind tour chapter => that small concepts chapter I mentioned => 3 pretty big chapters going over all the main components of Django. So by the time you hit the "how to get things done" sections (example apps + advanced materials) you've got a good foundation to build on.

bmoyles
Feb 15, 2002

United Neckbeard Foundation of America
Fun Shoe
No pdf/e-book version, eh? :\

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

bitprophet posted:

Take a closer look at the photo ;) specifically the upper right quadrant. Think circles.

I am a failure.

tankadillo
Aug 15, 2006

I've started setting up a site with Django a few days ago and I'm stuck with a completely newbie problem. I'm trying to set up a blogish type thing and in the table for the entries I want it to store the author. Here's what I figured it would be like:
code:
from django.contrib.auth.models import User

class Entry(models.Model):
  author = models.ForeignKey(User)
I'm not sure where to go from here though. How do I make it automatically add the user who's posting it? I feel like this should be simple but I can't find anything to help me.

bitprophet
Jul 22, 2004
Taco Defender

bmoyles posted:

No pdf/e-book version, eh? :\

Not through Amazon AFAIK, but it's available on InformIT's Safari service here. Honestly I'm not sure if you can get it as a single PDF or what -- I've only used Safari via subscription -- but poke around and see what you can get :)

duck monster
Dec 15, 2004

Congrats.

I had started on a book on Boa-Constructor a while back, but it started becoming clear that the system had no future because the guy who maintains/coded it works at a ponderously glacial speed and is alergic to collaborating with people who want to help him.

Then I started on a book on Python Webware, but gave that up too because it was getting clear it was being majorly eclipsed by Django

I suck at future prediction. I'm sure this english lit degree will become handy ONE day.

bmoyles
Feb 15, 2002

United Neckbeard Foundation of America
Fun Shoe

bitprophet posted:

Not through Amazon AFAIK, but it's available on InformIT's Safari service here. Honestly I'm not sure if you can get it as a single PDF or what -- I've only used Safari via subscription -- but poke around and see what you can get :)

Oh sweet, I'm a safari subscriber through O'Reilly. Perfect. I'm trying to keep up my record of not having bought a physical computer book in 3 years :)

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.

raezr posted:

I've started setting up a site with Django a few days ago and I'm stuck with a completely newbie problem. I'm trying to set up a blogish type thing and in the table for the entries I want it to store the author. Here's what I figured it would be like:
code:
from django.contrib.auth.models import User

class Entry(models.Model):
  author = models.ForeignKey(User)
I'm not sure where to go from here though. How do I make it automatically add the user who's posting it? I feel like this should be simple but I can't find anything to help me.

It is simple. In your view where the entry's form is submitted, save the object but don't commit it. Then add in the user. Then save it for real.

Example:
code:
# assuming you've checked the form is valid, or whatever
# and the HTTP request is passed in as request
new_entry = your_form.save(commit=False)
new_entry.author = request.user
new_entry.save()
The Django docs on forms with models has a bit more info if you're interested.

tankadillo
Aug 15, 2006

pokeyman posted:

It is simple. In your view where the entry's form is submitted, save the object but don't commit it. Then add in the user. Then save it for real.

Example:
code:
# assuming you've checked the form is valid, or whatever
# and the HTTP request is passed in as request
new_entry = your_form.save(commit=False)
new_entry.author = request.user
new_entry.save()
The Django docs on forms with models has a bit more info if you're interested.
I want to do this via the built in Django admin interface instead of writing my own form. I was hoping there would just be an easy way with editing models.py or something.

EDIT: durr I found an example showing exactly what I want to do on their documentation http://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-methods I was just looking in all the wrong places

tankadillo fucked around with this message at 05:45 on Nov 3, 2008

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.

raezr posted:

EDIT: durr I found an example showing exactly what I want to do on their documentation http://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-methods I was just looking in all the wrong places

Cool, that's good to know.

The documentation seems totally haphazard to me. Sometimes I find exactly what I need immediately; other times not a single Google search or random following of links can get me close. I'm not sure whether this is a fault of the documentation or of me though :( It's just weird how I can find whatever I need in the Python documentation in a heartbeat, but not so much with Django.

nbv4
Aug 21, 2002

by Duchess Gummybuns

Bonus posted:

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

Is there any way to hard code the "request.user" part into the model manager? I can't figure out how to import the request object into models.py. Does request only exist in views.py or something?

bitprophet
Jul 22, 2004
Taco Defender

nbv4 posted:

Is there any way to hard code the "request.user" part into the model manager? I can't figure out how to import the request object into models.py. Does request only exist in views.py or something?

Look in the Django docs (or just Google) to see what this whole "MVC" thing is :) the entire point is that you keep the model, views and templates as separate as possible, which makes your apps much easier to maintain and modify.

Yes, it makes things slightly more difficult when you have a need to cross layers, but it's well worth it. For example, if you required an HTTP request object in one of your model classes, you'd be pretty screwed if you needed to use that model in a non Web context, such as via a script.

In your case, no, there's no way to "hard code" the request user into the model manager -- you'd have to explicitly set up a manager subclass with an extra init parameter, as Bonus suggested, which would let you pass the request in when it's needed. This basically "pokes a hole" into the model layer that you can pass the request through when necessary, but doesn't actually tie the two layers together.

I seem to have missed it up-thread -- what's the actual problem being solved here? A custom manager is sometimes useful but when you're talking about needing info related to specific objects, it's almost always better to add regular QuerySet-returning methods to the model class. This is trickier with auth.User because it's not "your" model, but should still be possible (especially if you set up your own model that has a relationship to User; there are lots of blog posts out there about 'extending the User model' if you want to check them out).

nbv4
Aug 21, 2002

by Duchess Gummybuns

bitprophet posted:

Look in the Django docs (or just Google) to see what this whole "MVC" thing is :) the entire point is that you keep the model, views and templates as separate as possible, which makes your apps much easier to maintain and modify.

Yes, it makes things slightly more difficult when you have a need to cross layers, but it's well worth it. For example, if you required an HTTP request object in one of your model classes, you'd be pretty screwed if you needed to use that model in a non Web context, such as via a script.

In your case, no, there's no way to "hard code" the request user into the model manager -- you'd have to explicitly set up a manager subclass with an extra init parameter, as Bonus suggested, which would let you pass the request in when it's needed. This basically "pokes a hole" into the model layer that you can pass the request through when necessary, but doesn't actually tie the two layers together.

I seem to have missed it up-thread -- what's the actual problem being solved here? A custom manager is sometimes useful but when you're talking about needing info related to specific objects, it's almost always better to add regular QuerySet-returning methods to the model class. This is trickier with auth.User because it's not "your" model, but should still be possible (especially if you set up your own model that has a relationship to User; there are lots of blog posts out there about 'extending the User model' if you want to check them out).
My application is a pilot logbook webapp where pilots log flights they do. The site is 100% user encapsulated. User #34's flights will only be displayed by user #34, and user #78's flights will only ever be displayed by user #78, etc. The only time flights will be handled is as a set of flights belonging to the logged in user.

Think of it as like a webmail app. Your emails only exist to you. There will never be a time when some user will need to display emails of another user. It seems to me it would be best to define this "fact", if you will, is in the model layer. But I don't know I'm kinda new to this whole MVC thing...

king_kilr
May 25, 2007
Just started blogging(thanks to a bunch of Django people for yelling at me), here's my first post: http://lazypython.blogspot.com/2008/11/lazy-user-foreign-keysthis-is-double.html

Let me know what you guys think.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Hey guys I'm going to be asking a whole lot of dumb questions the next few weeks because I'm making an online Dungeons and Dragons game in django for a school project.

I think we are doing well so far. We are learning Python as we go along and we haven't hit any major road blocks yet. My question right now is how do I split up the models.py class? Right now it's 200 lines of code and growing. I think I can split it up using the __init.py__ class but I'm not entirely sure. How do I go about changing this?

bitprophet
Jul 22, 2004
Taco Defender

MEAT TREAT posted:

Hey guys I'm going to be asking a whole lot of dumb questions the next few weeks because I'm making an online Dungeons and Dragons game in django for a school project.

I think we are doing well so far. We are learning Python as we go along and we haven't hit any major road blocks yet. My question right now is how do I split up the models.py class? Right now it's 200 lines of code and growing. I think I can split it up using the __init.py__ class but I'm not entirely sure. How do I go about changing this?

Google around for this, there've been a lot of blog entries and such about it. I thought the official docs had a note about it by now, but can't find it.

Offhand you can use __init__.py as you sort of mentioned (it's not a class; it's basically an organizational tool you can use to control what a given Python module "exposes" when it's imported. In this case you'd make models.py (a module in a single file) into models/*.py (a module defined in 1+ file within a folder) and have your __init__.py import the constituent parts so it becomes a flat namespace.

In other words, if you normally had mymodule/a.py:
code:
class ModelOne(models.Model):
    pass
and mymodule/b.py:
code:
class ModelTwo(models.Model):
    pass

class ModelThree(models.Model):
    pass
Then doing import mymodule would just give you the two sub-modules a (containing ModelOne) and b (containing ModelTwo and ModelThree).

But what you want is basically to flatten the contents of these into one big flat namespace (since that's what is expected of Django model files for the most part; you need to be able to refer to mymodule.ModelOne, mymodule.ModelTwo, and etc) so you'd need an __init__.py that does something like
code:
from a import *
from b import *
With that in place, doing import mymodule would give you an object with all 3 of your model classes; or doing from mymodule import * would get all 3 model classes into the calling namespace.

I know that's probably a lot to absorb for a newbie, but if you read up just a little bit on Python importing and modules, it should make sense.

TOO SCSI FOR MY CAT
Oct 12, 2008

this is what happens when you take UI design away from engineers and give it to a bunch of hipster art student "designers"

MEAT TREAT posted:

Hey guys I'm going to be asking a whole lot of dumb questions the next few weeks because I'm making an online Dungeons and Dragons game in django for a school project.

I think we are doing well so far. We are learning Python as we go along and we haven't hit any major road blocks yet. My question right now is how do I split up the models.py class? Right now it's 200 lines of code and growing. I think I can split it up using the __init.py__ class but I'm not entirely sure. How do I go about changing this?

200 lines isn't very long; don't worry about splitting it up unless the length is interfering with your understanding of the code.

That said, the usual way of splitting up models.py is to convert it into a "package"; a directory containing a file named "__init__.py". If your models.py looks like this:

code:
# myproject/myapp/models.py

class ModelA (models.Model):
	name = models.CharField (max_length = 255)
	
	class Meta:
		ordering = ['name']
		
class ModelB (models.Model):
	name = models.CharField (max_length = 255)
	
	class Meta:
		ordering = ['name']
change it into this:

code:
# myproject/myapp/models/__init__.py

from .model_a import ModelA
from .model_b import ModelB

# myproject/myapp/models/model_a.py

class ModelA (models.Model):
	name = models.CharField (max_length = 255)
	
	class Meta:
		ordering = ["name"]
		app_label = "myapp" # <--- IMPORTANT
		

# myproject/myapp/models/model_b.py

class ModelB (models.Model):
	name = models.CharField (max_length = 255)
	
	class Meta:
		ordering = ["name"]
		app_label = "myapp" # <--- IMPORTANT

Adbot
ADBOT LOVES YOU

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

Janin posted:

code:
# myproject/myapp/models.py

class ModelA (models.Model):
	name = models.CharField (max_length = 255)
	
	class Meta:
		ordering = ['name']


I was under the impression that class Meta ordering was "bad", something to do with inheritance, I forget. It was something mentioned by David Cramer at djangocon. Does anyone remember the exact reason why?

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