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
The March Hare
Oct 15, 2006

Je rêve d'un
Wayne's World 3
Buglord

MonkeyMaker posted:

To answer both you and mmm11105 (and sorry for the double post), I do have a set plan for the future episodes. The next 7 or 8 will all focus on building one large app. It'll be set up as an app for tracking things you've loaned to friends/family. We'll obviously stretch the use case a little, but it'll include things like Celery, sending emails, manipulating images, and setting up an API to use with a Javascript frontend (we *might* scratch this, but I doubt it).

If that doesn't fill up that many episodes, I'll come up with some other small project after that.

Then there'll be a few more episodes covering other areas of Django development, like standing up servers on AWS and building search with Haystack.

As for a release schedule, I'm working on episode 4 already, so expect a video in a week or so.

For what its worth, a video detailing setting up an API to use with any kind of front-end would be awesome as I have been having a hard time locating a current and comprehensive/understandable resource for a stupid side project that I have almost finished except for that part. I would additionally like to thank you because the videos are top notch for an idiot code newbie such as myself.

Adbot
ADBOT LOVES YOU

Sinestro
Oct 31, 2010

The perfect day needs the perfect set of wheels.
I'm trying to get back into Django, and I'm finding it hard to not hate forms. What is the modern make-Forms-better library?

My Rhythmic Crotch
Jan 13, 2011

Django crispy forms comes highly recommended. It looks good but I have yet to try really working with it.

My Rhythmic Crotch fucked around with this message at 09:27 on Apr 9, 2013

MonkeyMaker
May 22, 2006

What's your poison, sir?

Sinestro posted:

I'm trying to get back into Django, and I'm finding it hard to not hate forms. What is the modern make-Forms-better library?

django-crispy-forms for form control. django-floppyforms for HTML5 widgets.

The March Hare
Oct 15, 2006

Je rêve d'un
Wayne's World 3
Buglord
More of a curiosity than anything here but I figure it is worth asking about. I've got a page iterating through some database objects in a standard django template for loop using "reversed." Locally, using sqlite3, this makes the items show up with the most recently created item at the top but on my "live" version over on Heroku, running postgres, it does the opposite.

Is this due to the databases being different or something else?

Pardot
Jul 25, 2001




The March Hare posted:

More of a curiosity than anything here but I figure it is worth asking about. I've got a page iterating through some database objects in a standard django template for loop using "reversed." Locally, using sqlite3, this makes the items show up with the most recently created item at the top but on my "live" version over on Heroku, running postgres, it does the opposite.

Is this due to the databases being different or something else?

There is no guaranteed order for a result set from postgres unless you specify ORDERY BY. Take a look at https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by

Also you really should run the same database in development as in production.

The March Hare
Oct 15, 2006

Je rêve d'un
Wayne's World 3
Buglord

Pardot posted:

There is no guaranteed order for a result set from postgres unless you specify ORDERY BY. Take a look at https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by

Also you really should run the same database in development as in production.

Cool, good to know. Additionally, I'm sure that link has some useful info in it and I can certainly see how normalizing things would be beneficial in most if not all situations, but that page needs to be rewritten by someone less evangelical -- poo poo reads like the label of a Dr. Bronner product.

etcetera08
Sep 11, 2008

When's more DjangoCon US info gonna get posted? I'm still suffering from jealousy at my coworkers' trip to Pycon.

MonkeyMaker
May 22, 2006

What's your poison, sir?

etcetera08 posted:

When's more DjangoCon US info gonna get posted? I'm still suffering from jealousy at my coworkers' trip to Pycon.

Usually after DjangoCon EU starts/wraps. What we know so far:

* Likely to be first week of September since that's been the date for a few years now
* It'll be in Chicago in 2013
* If there's public voting for talks, I expect all the goons to back mine ;)

EDIT:

They've put up a placeholder site: http://2013.djangocon.us/ and set the dates as Sept. 2nd through 7th.

MonkeyMaker fucked around with this message at 17:58 on May 1, 2013

bigmandan
Sep 11, 2001

lol internet
College Slice
I'm working on a basic asset tracking system and I need to keep track of different item types. Simple enough except that some item types are also "containers" and can only contain certain item types. I need to enforce this restriction and have reverse lookups indicate what an item type can be placed in. Would I be correct in using a model with a man-to-many field referencing itself?

For example a computer can "contain" a DVD, but a DVD can also be placed in a DVD player or DVD case.

I have the the following code but I feel like i'm missing something.

code:
class ItemType(models.Model):
    name = models.CharField(max_length=256, unique=True)
    description = models.TextField()
    is_container = models.BooleanField()    
    can_contain = models.ManyToManyField('self', related_name="contains")
EDIT:

I've been messing around a bit and i've come up with something that almost does everything I need:

code:
class ItemType(models.Model):
    name = models.CharField(max_length=256, unique=True)
    is_container = models.BooleanField(default=False)
    relationship = models.ManyToManyField(
        'self'
        , through='ItemContainerRelationship'
        , related_name='placeable_in'
        , symmetrical=False
    )

    def __unicode__(self):
        return self.name

class ItemContainerRelationship(models.Model):
    container = models.ForeignKey(ItemType, related_name="container")
    containee = models.ForeignKey(ItemType, related_name="containee")
    max_qty = models.PositiveIntegerField()
If I do
code:
disc = ItemType.objects.get(name="DVD Disc")
x = disc.placeable_in.all()
x will have a list of ItemType that disc can be placed in. This is half of what I want.

I need to do the reverse as well:
code:
player = ItemType.objects.get(name="DVD Player")
y = ???
Where 'y' would be a list of ItemType that 'player' is a container for. I'm not sure how I go about this.


EDIT #2:

Using the same models as above, I think I may have found the answer, but I have a nagging feeling that there is a "gotcha" somewhere:

code:
>>> player = ItemType.objects.get(name="DVD Player")
>>> player.placeable_in.all()  # where a DVD player can be placed
[<ItemType: Media Center>]
>>> player.relationship.all()  # what can be placed in a DVD player
[<ItemType: DVD>]
>>> 

bigmandan fucked around with this message at 21:50 on May 7, 2013

avidal
May 19, 2006
bawl-some

MonkeyMaker posted:

Usually after DjangoCon EU starts/wraps. What we know so far:

* Likely to be first week of September since that's been the date for a few years now
* It'll be in Chicago in 2013
* If there's public voting for talks, I expect all the goons to back mine ;)

EDIT:

They've put up a placeholder site: http://2013.djangocon.us/ and set the dates as Sept. 2nd through 7th.

Can you share what your talk will be about? Maybe I'll actually attend this time!

MonkeyMaker
May 22, 2006

What's your poison, sir?

bigmandan posted:

code:
    relationship = models.ManyToManyField(
        'self'
        , through='ItemContainerRelationship'
        , related_name='placeable_in'
        , symmetrical=False
    )

Not answering your question, but don't do leading commas like that. This isn't Javascript with lovely parsers that can't handle a trailing comma. Learn, love, and live PEP8 please.

To answer your question, your final approach doesn't look horrible. You might look into something like django-mptt, though, to make categorization easier.

@avidal: Not 100% certain yet but I have two I plan to propose. One about using django-rest-framework with AngularJS (including a live code demo! (which, like an intelligent person, I will write beforehand)). Second about lessons learned doing Getting Started with Django, both on 'how to run a kickstarter and get community support for your idea' and 'how to teach noobs things'. I have another idea or two kicking around too.

bigmandan
Sep 11, 2001

lol internet
College Slice
Thanks MonkeyMaker. I fixed my dumb commas too. I am already using django-mptt for categorization, but I trimmed my example to illustrate my particular concern and I should have stated that.

Kumquat
Oct 8, 2010
So I'm trying to run through GSWD but I'm having some issues at the very beginning. Some guy on the forums over there had the same problem two days ago (http://gettingstartedwithdjango.com/questions/1/errors-running-vagrant-up/) and hasn't gotten any responses, so I figured I'd try here.

When I do my "vagrant up" I get some errors:
Recipe Compile Error in /tmp/vagrant-chef-1/chef-solo-1/cookbooks/yum/resources/key.rb
wrong number of arguments (2 for 1)

If it helps, the link above to the GSWD forums has the full output of the command and the stacktrace which is the same thing I'm getting. Let me know if any additional info would be helpful.

MonkeyMaker
May 22, 2006

What's your poison, sir?

Kumquat posted:

So I'm trying to run through GSWD but I'm having some issues at the very beginning. Some guy on the forums over there had the same problem two days ago (http://gettingstartedwithdjango.com/questions/1/errors-running-vagrant-up/) and hasn't gotten any responses, so I figured I'd try here.

When I do my "vagrant up" I get some errors:
Recipe Compile Error in /tmp/vagrant-chef-1/chef-solo-1/cookbooks/yum/resources/key.rb
wrong number of arguments (2 for 1)

If it helps, the link above to the GSWD forums has the full output of the command and the stacktrace which is the same thing I'm getting. Let me know if any additional info would be helpful.

Sorry, been sick for a couple of days. As I answered him (just now), is this the first time or subsequent times? Actually, just check out the answer I gave him. You can hit me up on IRC too in #cobol

Lister_of_smeg
May 25, 2005
I've been away from Django for a while and since coming back I'm trying to get my head around class based views (It was only function based when I last played with Django). Does anyone have recommendations for good tutorials, info, etc. on testing class based views? Are they tested in the same way as function based views? I feel like there should be a different testing approach, but that may be because I'm getting hung up on the 'class' part of class based views.

Thanks in advance.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I'm thinking about deployment of a django project. Heroku is very tempting because if how easy it is (why didn't I try this out before?), however I'm looking to get some feedback from people who've got more sites and more high-traffic sites deployed and what they think about Heroku performance and the Rap Genius debacle. Big deal or not?

Lister_of_smeg posted:

I've been away from Django for a while and since coming back I'm trying to get my head around class based views (It was only function based when I last played with Django). Does anyone have recommendations for good tutorials, info, etc. on testing class based views? Are they tested in the same way as function based views? I feel like there should be a different testing approach, but that may be because I'm getting hung up on the 'class' part of class based views.

Thanks in advance.

Just test them. I think you're getting hung up on them being different from what you're used to. You just test their parts and test their functionality.

How exactly do you foresee the tests being different?

Thermopyle fucked around with this message at 17:57 on May 13, 2013

MonkeyMaker
May 22, 2006

What's your poison, sir?

Lister_of_smeg posted:

I've been away from Django for a while and since coming back I'm trying to get my head around class based views (It was only function based when I last played with Django). Does anyone have recommendations for good tutorials, info, etc. on testing class based views? Are they tested in the same way as function based views? I feel like there should be a different testing approach, but that may be because I'm getting hung up on the 'class' part of class based views.

Thanks in advance.

CBVs aren't all that different from FBVs except in a couple of places. How you call them from your URL routes, and how you inject functionality.

Say you have a CBV named PostListView. In your urls.py, instead of `'path.to.post_list_view'`, you'd have `PostListView.as_view()` for the function part of the route (after the regex, before the name).

And then, to change functionality, you'd override a method in the view instead of just adding code to a giant function. http://ccbv.co.uk is probably the best guide to what methods already exist for you to override and change.

But, really, CBVs work just like all other classes in Django and Python. Create a new class, extend it off of an existing one, override the methods and attributes that you need to, and you're done.

Testing is just like FBVs. Call the view, ideally through `self.client`, and check the response's status code, template, etc. If you want to test individual methods, instantiate the class with a request object and go to town.

ufarn
May 30, 2009
Heroku is alright, if you don't plan on going big - will you realistically need to do horizontal scaling on the project?

That, and not to use Relic's bullshit metrics, is the main take-away here. That and Heroku's lovely handling of the entire situation.

You don't have to be married to Heroku; django-deployer should keep you independent, as long as you don't rely on postinstall/post-deploy scripts, which aren't supported on Heroku, IIRC.

Comrade Gritty
Sep 19, 2011

This Machine Kills Fascists

Thermopyle posted:

I'm thinking about deployment of a django project. Heroku is very tempting because if how easy it is (why didn't I try this out before?), however I'm looking to get some feedback from people who've got more sites and more high-traffic sites deployed and what they think about Heroku performance and the Rap Genius debacle. Big deal or not?


Just test them. I think you're getting hung up on them being different from what you're used to. You just test their parts and test their functionality.

How exactly do you foresee the tests being different?

The Rap Genius debacle existed mostly because Rails is a single threaded app. Each dyno can only handle 1 request at a time and any other requests sent to that dyno will be queued by the OS. If you deploy Django with a good server like Gunicorn or uwsgi you'll get atleast a few requests concurrency per dyno, or if you use an event driven archecture (gunciron with gevent/eventlet for instance) you'll get thousands of requests work of concurrency per dyno. This effectively nulls the problem Rap Genius had.

Mulozon Empuri
Jan 23, 2006

Steampunk Hitler posted:

The Rap Genius debacle existed mostly because Rails is a single threaded app. Each dyno can only handle 1 request at a time and any other requests sent to that dyno will be queued by the OS. If you deploy Django with a good server like Gunicorn or uwsgi you'll get atleast a few requests concurrency per dyno, or if you use an event driven archecture (gunciron with gevent/eventlet for instance) you'll get thousands of requests work of concurrency per dyno. This effectively nulls the problem Rap Genius had.

Eh, wasn't the whole thing mostly about the 'intelligent' routing that doesn't really exist?

Anyways. Anybody at Djangocon EU?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Mulozon Empuri posted:

Eh, wasn't the whole thing mostly about the 'intelligent' routing that doesn't really exist?

As far as I can understand it's a combination of that with the problem that Steampunk Hitler mentioned. Since Rails can handle only 1 request, and since Heroku's routing is dumb, Heroku would route a request to a dyno that was waiting on rails instead of routing to dyno's that were just idling.

I didn't even realize you could use eventlet workers with gunicorn, which means that while a dyno is waiting on I/O it can serve other requests.

Lister_of_smeg
May 25, 2005
Thanks Thermopyle and MonkeyMaker. As I suspected I was getting hung up on the class part. I kept thinking "Hey, this is a Python class. Let's unit it test it like a class." rather than thinking "Hey, this is a slightly different way of implementing a view. Test it like you do with other views".

Also, http://ccbv.co.uk is fantastic.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
Can I get a sanity check on this... it does what I want, but I'm paranoid that I'm doing something that may bite me in the rear end in the future. Basically I am building forms through mixins, but one of the mixins does multi-field validation, so I'm calling super.clean() first in my clean method on the form:

Python code:
from django import forms

class GuestFormMixin(forms.Form):
    guest_first_name = forms.CharField(required=False)
    guest_last_name = forms.CharField(required=False)
    guest_email = forms.EmailField(required=False)

    def clean(self):
        # code that validates that if you filled in *any* of the guest inputs
        # that you filled in *all* of them
        # it adds errors like so:  self._errors["guest_email"] = self.error_class(["oh noes!"])
        # if that happens
        super(GuestFormMixin, self).clean()

class OptInFormMixin(forms.Form):
    opt_in = forms.BooleanField(required=True)

'''
The actual form build from other forms.
'''
class SomeForm(GuestFormMixin, OptInFormMixin):
    first_name = forms.CharField()

    def clean(self):
         super(SomeForm, self).clean()
         if len(self._errors) == 0:
              #do some API stuff to get data I need before I finish submitting
         return self.cleaned_data
I have only seen examples of super being called at the end of methods, which makes me nervous about what I am doing. Should I be?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Some semantical stuff: I recommend that mixins should only inherit from object. By definition, a mixins only purpose is to provide a small number of features to multiple other classes. By inheriting from Form, you're getting a ton of other methods and attributes which will make behavior of classes using those mixins more difficult to reason about. (Great advice from Kenneth Love, actually) From the looks of it, I don't think those are actually mixins by the common definition.

Anyway, it doesn't really matter where you put your call to the super's clean method as long as you're aware of what the super is doing. If your code makes modifications to data that you then want the super's clean method to validate, than you put it at the end, if you want the super's clean method to validate before then you put it at the end. You can put it right in the middle if you want the super to validate before your own validation code continues.

From what I can tell, you're fine in that regard.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Thermopyle posted:

Some semantical stuff: I recommend that mixins should only inherit from object. By definition, a mixins only purpose is to provide a small number of features to multiple other classes. By inheriting from Form, you're getting a ton of other methods and attributes which will make behavior of classes using those mixins more difficult to reason about. (Great advice from Kenneth Love, actually) From the looks of it, I don't think those are actually mixins by the common definition.

Anyway, it doesn't really matter where you put your call to the super's clean method as long as you're aware of what the super is doing. If your code makes modifications to data that you then want the super's clean method to validate, than you put it at the end, if you want the super's clean method to validate before then you put it at the end. You can put it right in the middle if you want the super to validate before your own validation code continues.

From what I can tell, you're fine in that regard.

Thanks. And yes, they aren't "really" mixins, and are not actually called that in my code (the actual names are Base____Form) since they can be (and are) used standalone Forms as well. I changed the names in my example to make it more clear what I was doing.

MonkeyMaker
May 22, 2006

What's your poison, sir?

Thermopyle posted:

(Great advice from Kenneth Love, actually)

D'awww.

And, yeah, Thermopyle has it right. `super()` is just to invoke a function from a superclass, so it can (and should) be called from wherever it's needed.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
It's my first five minutes looking at Django and this thread, but the OP is foobar (at least the images and some links), in case anyone cares.

ufarn
May 30, 2009

supermikhail posted:

It's my first five minutes looking at Django and this thread, but the OP is foobar (at least the images and some links), in case anyone cares.
It also doesn't have syntax-highlighting, which was introduced after the post.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."

ufarn posted:

It also doesn't have syntax-highlighting, which was introduced after the post.

I see.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

ufarn posted:

It also doesn't have syntax-highlighting, which was introduced after the post.

It is also 5 years old, which means it was written around version 1.0, so it's woefully out of date.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

New OP:

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Double postin' like a crazy man.

What's the right way to access Django settings from a non-Django script? Specifically, I have some periodic celery tasks in which I'd like to use Django's LOGGING config.

Right now, I'm reading DJANGO_SETTINGS_MODULE from the environment variable and importing LOGGING and using dictConfig to configure my logger, but it kind of feels like that since I'm using django-celery there should be something else. But then again, this is my first time using it so I may just be wrong.

ufarn
May 30, 2009
I personally store my settings as

MYSETTING = os.environ.get('MYSETTING', "DEFAULT_VALUE")

I don't think there's any sexy way to store and retrieve settings, if that's what you're asking.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Thermopyle posted:

Double postin' like a crazy man.

What's the right way to access Django settings from a non-Django script? Specifically, I have some periodic celery tasks in which I'd like to use Django's LOGGING config.

Right now, I'm reading DJANGO_SETTINGS_MODULE from the environment variable and importing LOGGING and using dictConfig to configure my logger, but it kind of feels like that since I'm using django-celery there should be something else. But then again, this is my first time using it so I may just be wrong.

Shouldn't you be able to run Celery Beat and Celery through Django when you have the django-celery installed? That way you should be able to make use of django.conf.settings, yeah?

edit: It's something like python manage.py celery worker for development. For production you need daemonize the process yourself (http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#starting-the-worker-process)

I don't have my full setup on hand right now, but in one of my applications I'm just importing whatever I like from tasks.py in a Django app without any dramas.

Maluco Marinero fucked around with this message at 02:31 on May 21, 2013

MonkeyMaker
May 22, 2006

What's your poison, sir?

Maluco Marinero posted:

Shouldn't you be able to run Celery Beat and Celery through Django when you have the django-celery installed? That way you should be able to make use of django.conf.settings, yeah?

edit: It's something like python manage.py celery worker for development. For production you need daemonize the process yourself (http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#starting-the-worker-process)

I don't have my full setup on hand right now, but in one of my applications I'm just importing whatever I like from tasks.py in a Django app without any dramas.

Yeah, this is pretty much it.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Yeah, I'm a dummy.

I was only having problems because while testing I was just running my script from the command line, which obviously doesn't work. And by obvious I mean obvious after you go to bed and wake up.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
I am the worst Googler in the world, apparently.

I have a class-based FormView, which has SomeForm as it's form_class.

How on earth do I set a cookie at any point in either for view or the form. Preferably the form, but I don't care at this point.

MonkeyMaker
May 22, 2006

What's your poison, sir?

Lumpy posted:

I am the worst Googler in the world, apparently.

I have a class-based FormView, which has SomeForm as it's form_class.

How on earth do I set a cookie at any point in either for view or the form. Preferably the form, but I don't care at this point.

What do you mean by "set a cookie"? Like pass in a kwarg to the form?

code:
def get_form_kwargs(self, **kwargs):
    form_kwargs = super(MyView, self).get_form_kwargs(**kwargs)
    form_kwargs.update({"foo": "bar"})
    return form_kwargs

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

MonkeyMaker posted:

What do you mean by "set a cookie"? Like pass in a kwarg to the form?

code:
def get_form_kwargs(self, **kwargs):
    form_kwargs = super(MyView, self).get_form_kwargs(**kwargs)
    form_kwargs.update({"foo": "bar"})
    return form_kwargs

No, i mean use the request.set_cookie("key", "value", 1000) method to set a cookie so I can read it in the future. Or is there some other way to do that?

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