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
fuf
Sep 12, 2004

haha
If I pass an array of category names to a view how would I get all the posts in those categories? I don't really know how to deal with arrays.

Adbot
ADBOT LOVES YOU

MonkeyMaker
May 22, 2006

What's your poison, sir?

fuf posted:

If I pass an array of category names to a view how would I get all the posts in those categories? I don't really know how to deal with arrays.

code:
cats = kwargs.get("cats") # a list of category pks. i.e. [2, 4, 6]
posts = Posts.objects.filter(cats__pk__in=cats)

fuf
Sep 12, 2004

haha

MonkeyMaker posted:

code:
cats = kwargs.get("cats") # a list of category pks. i.e. [2, 4, 6]
posts = Posts.objects.filter(cats__pk__in=cats)

Thanks man. I'll admit I still don't understand kwargs but I think the "pk__in" bit was crucial.

I think it turns out that I was passing to the view wasn't actually an array so I ended up using "split" and now it works.

I have a crude, ham-fisted way of loading posts from categories without reloading the page using jquery, but I don't really know what I'm doing so it might be totally retarded.

When someone clicks a category I make an array of all the 'active' categories (whose posts will be displayed):

code:
var categories = new Array(); 
    	$('.active.category').each(function() {
        	categories.push($(this).attr("id"));
    	});
then pass this to a view and load the result:

code:
$( '#listPosts' ).load('{% url timeline.views.getPosts %}?categories=' + categories);
So the url looks like /getPosts?categories=1,2,3 (but no one ever sees this).

Then the view looks like this:

code:
def getPosts(request):
    categories = request.GET.get('categories')
    categories = categories.split(',')
    posts = Post.objects.filter(category__id__in=categories)
    return render_to_response("timeline/listPosts.html", dict(posts=posts))
Is this a really bad way to do things?

raymond
Mar 20, 2004
I don't think it's a bad approach, but I have some suggestions.

I would be more explicit about the comma separated categories in your JavaScript, and use jQuery's map function rather than building the array manually.

code:
var categoryIds = $('.active.category').map(function(){return this.id}).get();
$('#listPosts').load('{% url timeline.views.getPosts %}?categories=' + categoryIds.join(','));
Try accessing "/your-view/" (no categories parameter) or "/your-view/?categories=hello,there" (wrong value type, assuming your IDs are meant to be integers) and it will break big time. You should validate all user input and return an informative error response when there's a problem.

Your use of dict(posts=posts) is unusual, although it works perfectly fine. Do you know that you can do this?
code:
return render_to_response("timeline/listPosts.html", {'posts': posts})

uncleTomOfFinland
May 25, 2008

Does anyone have recommendations for generating pre-filled PDF forms out of templates? Apparently it's fairly easy to do if using HTML/CSS templates and then rendering them to PDF but I'd prefer something that does not require knowing HTML/CSS for creating and modifying the form template.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
On that note, does anyone have a recommendation for a python library that turns a HTML/CSS page into a PDF? I need to set up a weekly digest that gathers some stuff together for the users of my web application and attaches them as PDFs, was hoping there was an option that is as simple as template with css -> pdf so I don't have to spend much time learning how to make it go.

fuf
Sep 12, 2004

haha

raymond posted:

I don't think it's a bad approach, but I have some suggestions.

I would be more explicit about the comma separated categories in your JavaScript, and use jQuery's map function rather than building the array manually.

code:
var categoryIds = $('.active.category').map(function(){return this.id}).get();
$('#listPosts').load('{% url timeline.views.getPosts %}?categories=' + categoryIds.join(','));

Oh cool, that's a good way to do it. My only worry (with your solution and mine) is having integers as the IDs of so many divs. Apparently this is bad CSS practice. I wonder if it could cause problems?

quote:

Your use of dict(posts=posts) is unusual, although it works perfectly fine.

I don't know where I got that from. I think it must have been used in a tutorial and I just stuck with it. Your way is easier.

Thanks for the tips. :)

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html

Just make sure you aren't opening with digits and you'll be fine, you must start a HTML ID with a letter of the alphabet, upper or lowercase.

MonkeyMaker
May 22, 2006

What's your poison, sir?

Maluco Marinero posted:

On that note, does anyone have a recommendation for a python library that turns a HTML/CSS page into a PDF? I need to set up a weekly digest that gathers some stuff together for the users of my web application and attaches them as PDFs, was hoping there was an option that is as simple as template with css -> pdf so I don't have to spend much time learning how to make it go.

We used wkhtmltopdf pretty successfully. It uses a headless WebKit to render an HTML page (with whatever associated images and CSS) and then converts it to a PDF.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

raymond posted:

Your use of dict(posts=posts) is unusual, although it works perfectly fine. Do you know that you can do this?
code:
return render_to_response("timeline/listPosts.html", {'posts': posts})

I kind of like the dict constructor for string keys. I think it's a bit neater:

code:
return HttpResponse(json.dumps(dict(a=1, b=2, c=3)))

return HttpResponse(json.dumps({'a': 1, 'b': 2, 'c': 3}))

fuf
Sep 12, 2004

haha
I hope no one minds another tricky question.

I have a model called Books and a model called Eras. Each book has a year and each era has a start date and an end date (So for instance the Enlightenment era starts in 1650 and ends in 1800).

I want to distribute the books into the eras to which they belong then pass it all to a template. Ideally I want the template to work like this:

code:
{% for era in eras %}
These books belong to {{era.name}}:
    {% for book in era %}
    {{book.name}}
    {% endfor %}
{% endfor %}
Does that make sense? Is it possible? I don't know if template objects can contain other objects like that.

All I have so far is a way of getting all the books for a certain era:

code:
eras = Eras.objects.all()
for era in eras:
    startDate = era.startDate
    endDate = era.endDate
    books = Book.objects.filter(year__range=(startDate, endDate))
But now I don't know what to do with "books".

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Why not also have a ForeignKey from a book to its respective Era?

fuf
Sep 12, 2004

haha
Well because I was hoping the eras could be dynamic, so I could adjust the dates if I need to, or add more specific eras and so on.

Also I guess I thought that since each book already has a year, it shouldn't need an era as well.

Perhaps I am making things too complicated though. I'll use a foreign key if it's the only way.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
It's certainly not the only way, but it might be a bit easier right now. In raw SQL, you could do something like:

code:
SELECT books.id, eras.id FROM books, eras WHERE books.year BETWEEN eras.start_year and eras.end_year;
I don't know if that's immediately translatable to Django. I doubt it.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

MonkeyMaker posted:

We used wkhtmltopdf pretty successfully. It uses a headless WebKit to render an HTML page (with whatever associated images and CSS) and then converts it to a PDF.
Sounds the ticket, cheers mate.

raymond
Mar 20, 2004

fuf posted:

My only worry (with your solution and mine) is having integers as the IDs of so many divs.
Good point. How about using data attributes? <div class="category" data-id="1"> or something.


Suspicious Dish posted:

I kind of like the dict constructor for string keys. I think it's a bit neater:
I guess I just haven't seen it used very often in this way, but I can see what you mean.

raymond
Mar 20, 2004

fuf posted:

I have a model called Books and a model called Eras. Each book has a year and each era has a start date and an end date (So for instance the Enlightenment era starts in 1650 and ends in 1800).

I want to distribute the books into the eras to which they belong then pass it all to a template.
I think I get what you're trying to do. I would use instance methods on your models, eg:
code:
class Book(Model):
    def get_eras(self):
        """Returns all eras for this book."""
        return Era.objects.filter(startDate__lte=self.year, endDate__gte=self.year)


class Era(Model):
    def get_books(self):
        """"Returns all books for this era."""
        return Book.objects.filter(year__range=(self.startDate, self.endDate))


{% for era in eras %}
These books belong to {{ era.name }}:
    {% for book in era.get_books %}
    {{ book.name }}
    {% endfor %}
{% endfor %}

ufarn
May 30, 2009

deimos posted:

It doesn't seem like a DB error, seems like the naive implementation of the development http server having timing issue. If your requests take long enough it'll throw that error.
I've tried it on several connections now, and I get the same thing. I guess something on their deployment servers are hanging?

duck monster
Dec 15, 2004

Meet IF-ZILLA.



I'll revisit this when I'm not braindamaged from a rotten hangover. Its possibly
the most insane piece of code I've been asked to write.

e: Its a JSON endpoint for an iphone app that can login via user/pass or facebook, creating the account ex nihilo if it doesnt already exist.

e2: And if you dont know what sort of diagram that is, I'm going to bash you with my zimmer frame.

Mulozon Empuri
Jan 23, 2006

duck monster posted:

e2: And if you dont know what sort of diagram that is, I'm going to bash you with my zimmer frame.

Trying to figure out diagram by searching for zimmer frame didn't work out too well. Now I know what a zimmer frame is though, so I'm 50% of the way to enlightenment. :haw:

duck monster
Dec 15, 2004

Mulozon Empuri posted:

Trying to figure out diagram by searching for zimmer frame didn't work out too well. Now I know what a zimmer frame is though, so I'm 50% of the way to enlightenment. :haw:

Its a Nassi Schneiderman diagram, aka "structogram", and their loving useful if your having trouble holding a particularly messy structured algorithm in your head at once. Its basically a flowchart where its impossible to do a goto.

But I have no idea if they are still taught , now that things have gone OO. (Although I'm not sure why it wouldn't be suitable for OO being that OO really is just structured but fancy, anyway.

Captain Capacitor
Jan 21, 2008

The code you say?
They're not, but I wish they were. Most often it seems to be Data-flow diagrams or copious abuse of MSDs.

Doh004
Apr 22, 2007

Mmmmm Donuts...

duck monster posted:

Meet IF-ZILLA.



I'll revisit this when I'm not braindamaged from a rotten hangover. Its possibly
the most insane piece of code I've been asked to write.

e: Its a JSON endpoint for an iphone app that can login via user/pass or facebook, creating the account ex nihilo if it doesnt already exist.

e2: And if you dont know what sort of diagram that is, I'm going to bash you with my zimmer frame.

As a recent college graduate (1 year out) I can safely say we were never shown a diagram like that. Plenty of other useless flowcharts, but not that one.

epswing
Nov 4, 2003

Soiled Meat

duck monster posted:

and their loving useful if your having trouble holding a

"they're" and "you're"

I keep seeing you do this and I can't let it go on any longer.

Surface
May 5, 2007
<3 boomstick

Honestly, is this chart more useful than say... anything?


duck monster posted:

Its a JSON endpoint for an iphone app that can login via user/pass or facebook

If you haven't already you may be interested in taking a look at:

Djang-facebook

and

Django-social-auth


Even if you can't use them directly in your project they do things like:

duck monster posted:

creating the account ex nihilo if it doesnt already exist.

and you can see how they solve issues that arise from the idiosyncrasies in the Facebook API.

Mulozon Empuri
Jan 23, 2006

Surface posted:

Honestly, is this chart more useful than say... anything?

I've never seen it before, but I think it looks pretty drat useful for describing flows in functions.

theratking
Jan 18, 2012
Okay so I'm a Django beginner, and I'm having a lot of trouble with a ranking / filter algorithm I'm trying to write.

Essentially we're filtering songs/albums/artists first by a bunch of metrics (location, genre, price). These are simple boolean filters. Easy.

next we filter the Fan object of all these objects (new fan object for every user who fans the artist/album/song). We filter the fans based on time (fans added this week, etc.)

the problem is then ranking each category by #fans, but only fans in our filtered queryset. Right now I'm doing all the ranking in pure python, which is not ideal. I'd like to be able to have the function return 3 ranked query sets.

any guidance would be appreciated

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Provide the models that represent this and it'll be easier to help out. By the way Query sets can follow relationships like

code:

objects.filter(tags__name__in=['Tag 1', 'Tag 2']

theratking
Jan 18, 2012
essentially the profile/artist models are set up like this:
code:
class Profile(models.Model):
	fans = models.ManyToManyField('self',through='Fan', related_name='fanned')

class Fan(models.Model):
	fanee = models.ForeignKey(Profile)
	faner = models.ForeignKey(Profile)
The song/album ones are similar.

so I can sort profiles by # fans by using
code:
Profile.objects.all().annotate('fan_count'=Count('fans')).order_by('-fan_count')
or something like that. But I don't want ALL the fans. I just want some from another query set.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
I don't think annotate can take a second queryset, altthough I'd welcome being proved wrong. You can do it with python using sorted definitely, but I'm assuming you're already doing that.

Python code:
profiles = Profile.objects.all()
sorted_profiles = sorted(list(profiles), key=lambda prof: prof.fans.filter(name__startswith="B").count())
Of course, this runs a queryset for each profile. Not sure of a better way to do this.

Maluco Marinero fucked around with this message at 01:03 on Jun 29, 2012

theratking
Jan 18, 2012
Yeah that's something like what I have. I was worried that in production with a large database it'd suffer. I actually didn't use sorted so your suggestion helped.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
You probably need to look into some form of caching if you're worrried about your heavy stuff. You could even give your profiles an IntegerField which stores the count, which you'd update each save() call or something. Then you can order directly in the first queryset using that stored value. A bit rough but caching really depends on your use case doesn't it.

theratking
Jan 18, 2012
Okay thanks for the heads up.

duck monster
Dec 15, 2004

Surface posted:

Honestly, is this chart more useful than say... anything?


The Nassi-Schneiderman diagram was a technique popular in the 80s and early 90s but seems to have gone out of fashion because it doesnt handle some of the more hairier features in functional languages (I *think*) and OO, back when structured was still king, to design and diagram program flow in a way that forbade spaghetti code of the goto variety and could let you fairly easily map out complex control flows. Its a variant of the flow chart, but its basically *better* because if you are *designing* this way, your guaranteed your resulting chart will work in a structured language.

It was mostly used for teaching, and once upon a time books on algorithms would always have one of these diagrams attached to the pseudo or pascal code.

It's still handy tool when you have some loving disgusting looking nest of an algorithm you want to design or at least figure out what the gently caress its doing.

NtotheTC
Dec 31, 2007


I have a model with a bound method that returns the name of a related model_c or a blank string

code:
class ModelA(models.Model):
    
    id
    name
    model_c              #foreign key
    etc...

    def get_model_c_name (self) :
	if self.model_c:
	    return model_c.name # Assume this model has a name field
        else:
            return ''
I have ANOTHER model with another bound method that returns the value of ModelA's bound method, so:

code:
class ModelB(models.Model):
    
    id
    stuff
    model_a             #foreign key

    def get_model_c_name_from_model_a (self) :
	if self.model_a:
	    return self.model_a.get_model_c_name
Why does a template tag of {{ instance_of_b.get_model_c_name_from_model_a }} instead return "<bound method ModelB.get_model_c_name_from_model_a of <ModelB: >" etc? I can accept that it doesnt work, and find a way around it. I was just curious as to why this behaviour occurs, still very new to django and python.

Mulozon Empuri
Jan 23, 2006

NtotheTC posted:


code:
    def get_model_c_name_from_model_a(self) :
	if self.model_a:
	    return self.model_a.get_model_c_name <--- 

That's because you're returning the method, not calling it

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
You aren't actually calling the function there, you're mixing your syntaxes. Django's template system will always automatically call a function with no variables, but obviously in Python this will result in returning the function.

Add () to your function in modelB
Python code:
def get_model_c_name_from_model_a (self) :
	if self.model_a:
	    return self.model_a.get_model_c_name()
Of course this all seems a bit of a waste of effort in this example when {{ instance_of_b.model_a.model_c.name }} is almost the same length, and Django's templating system automatically ignores failed variables if they don't exist, so it'd return '' in a non find anyway.

NtotheTC
Dec 31, 2007


Maluco Marinero posted:

Of course this all seems a bit of a waste of effort in this example when {{ instance_of_b.model_a.model_c.name }} is almost the same length, and Django's templating system automatically ignores failed variables if they don't exist, so it'd return '' in a non find anyway.

Ah yeah, I've been using model properties a lot recently so my stupid brain didn't pick up on the fact that it was actually a method. Duh.

In response to your last point though, the reason I'm using this method is because the default response I was getting if a variable didn't exist was "None" rather than ''.

And if I use {{ instance_of_b.model_a.model_c.name }} and it turns out model_b's related field to model_a is null, or model_a to model_c's is null, then it would fail with a NoneType error would it not?

I may need to look into this a bit more.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Nope, just a silent fail. This is good as long as you know what is happening, because it make's it fairly straightforward to check for existence.

Django Documentation posted:

If the variable raises an exception when called, the exception will be propagated, unless the exception has an attribute silent_variable_failure whose value is True. If the exception does have a silent_variable_failure attribute whose value is True, the variable will render as an empty string.

Note that django.core.exceptions.ObjectDoesNotExist, which is the base class for all Django database API DoesNotExist exceptions, has silent_variable_failure = True. So if you're using Django templates with Django model objects, any DoesNotExist exception will fail silently.

As the foreign key is going to return an object or raise DoesNotExist, this will fail to nothing. If you want a default to something other than an empty string, you can use the template filter |default or |default_if_none (if suitable for what you're calling returns).

Reverse rels/many to many managers are also easy, as in order to call them you use {{ instance.model_a_set.all }}, which returns either an empty queryset which is false in if statements, or a queryset that you can run over like a list.

Maluco Marinero fucked around with this message at 14:17 on Jul 4, 2012

Adbot
ADBOT LOVES YOU

duck monster
Dec 15, 2004

Has anyone suggested a violent purge of ex java programmers from the django development team yet? I swear this framework is getting more complicated and more "enterprisey" as time goes on. Like just a giant review where 60% of stupid poo poo , with close attention payed to which fucker put it there, is stripped out so that django is simple minded , quick to learn and fast to think in without having to constantly be reverting to manuals, again. Gah....

Anyway, does anyone know where the django documentation , without all the confusing poo poo about custom file handlers for big and small files and blah blah blah defining forms blah blah etc is?

I'm trying to transfer a file in from an iphone app and I *dont* want to use a form and I'm hosed if I can find the documentation. It *USED* to be there, or maybe its 4am and my brains fritzed it. :(

Been very tempted over a few projects lately where django is just too much loving guff to jump ship to flask...

duck monster fucked around with this message at 21:34 on Jul 4, 2012

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