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
politicorific
Sep 15, 2007
Thank you Wulfeh - you understood perfectly what I was going for in every instance.
The next step is deploying it to my hosting provider

Adbot
ADBOT LOVES YOU

bbq
Jan 21, 2006

get funky.
For getting plurality right, django offers the pluralize template tag

MrMoo
Sep 14, 2000

Is there a reason that development on Django-rest-interface appears dead?

I'm looking at using Django for a new project that pulls data in from two databases and creates new data in a third. However multi-database support is still in development, lma0, and it's not clear whether MySQL's fruity cross-database feature works.

Another project I have running uses PHP and it was easy working with the developer to get Pear::Data_Object to support MySQL multi-database syntax, committed into trunk a long while ago.

The alternative is to setup some form of web services, e.g. REST on the two external databases and using that hidden behind Django Models. However this seems to be a very under-developed technology for Django, what gives?

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Honestly REST has no place in Django, it is by far the worst feature ever added to Rails... what is the point of it, it's huge, it's obtrusive to coding anything, it offers negligible benefit to users.

In fact it's worse for users if it is implemented incorrectly as it was initially with Rails, with the funky semicolons in the URL.

Is there any reason at all that we would need REST in Django? I understand you don't have to use REST in Rails but when you don't, you cannot use a lot of the new or upcoming features. It's like development in RESTless rails just stopped dead after the idea popped up and it's unnecessary. :mad:

politicorific
Sep 15, 2007
okay, I admit defeat again.

I'm going to try an abstract explanation of my database search problem.

my database is full of entries like this: a1b2c3d4e5

code:
def search(request):
    query = request.GET.get('q', '')
    qset = (
        Q(english__icontains=query)
        )
my query=abcde

Is it possible to instruct django's database api to be greedy and return (a1b2c3d4e5) from my query(abcde)?

Now let me complicate things - my search query is unicode, my data is unicode. I have 12 unicode characters I want the search to ignore. Is it possible to .split() "query" and use wildcards to make the match? Or should I consider .strip()-ing all 12 characters and maintain another database?

king_kilr
May 25, 2007
This query will probably be pretty slow but what you can do is:

code:
import operator
def search(request):
    query = request.GET.get('q', '')
    q = reduce(operator.or_, [Q(english__icontains=i) for i in query])
    Model.objects.filter(q)
What this does is it creates a Q object for each letter, and then ors them together.

hey mom its 420
May 12, 2007

Wouldn't you want to and_ them together in that case?

politicorific
Sep 15, 2007
I'm getting "reduce() of empty sequence with no initial value"

also, preferably it'll be doing this across 27 fields from 5000 rows...

what about this from djangobook appendix C:
http://www.djangobook.com/en/1.0/appendixC/

quote:

search

A Boolean full-text search that takes advantage of full-text indexing. This is like contains but is significantly faster due to full-text indexing.

Note this is available only in MySQL and requires direct manipulation of the database to add the full-text index.
Is this relevant? Although I read MySQL only indexes fields with 3 or more characters, my unicode strings should be longer than that(6 at least)

hey mom its 420
May 12, 2007

Yeah, that's cause reduce will fail if it gets an empty sequence with no initial value. In your case that happens when query == ''. I think you could pass a third argument, Q() to that reduce to avoid getting that error on an empty string, but I'm not really sure. However, I think anding the Q objects together won't work like expected because that just checks that the field contains all those letters. It doesn't check their order or how many of them there are.

I think you might be able to achieve what you want by using the iregex field lookup and specify the regex so that it ignores the characters you want.

jarito
Aug 26, 2003

Biscuit Hider
I got a interesting one for you all. We have been tasked with creating a new site that has some interesting properties. I could use some help since I'm still starting with Django.

The idea is to create a 'reference' site that implements all the features we need. This part I can do. I create a project with an application called super. This all works fine.

Here's the interesting part. I need to create an unlimited number of subsites. The subsites use the same models / db. The subsites will differ mostly in images and css, but sometimes they will need to modify the templates as well.

So the idea is that the subsites will use the super site's implementation, templates and views UNLESS the subsite defines it's own, then those should be used. I'd like to do this without copying anything over and over again so if changes need to be made, they only need to be made in one place.

My idea was to have the views in the reference site load templates based on a setting. The subsites would override this setting to their individual template dirs, but would check for the existence of a template and if one isn't found, use the reference template.

Am I right that I can have the subsites inherit the views from the supersite and then just override any methods that it wants to implement?

How would I do this for the site_media stuff? Images / css should be loaded from the subsite specific folders unless they don't exist, then they should load from the supersite...is that possible?

king_kilr
May 25, 2007
As some of you may know, Django Dash(http://www.djangodash.com/) will be occuring next weekend, and registration ends today. Is there anyone who would be interested in working on something with me. I have no idea for a project(or at least no original ones :P). If you are interested either let me know here, or message me in the #django channel on freenode IRC(my name is the only one that starts with Alex_ in the channel).

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I am hoping I can find some help, currently I am trying to build a page which will create a new object, save it to the database and redirect me to the new object. The object being created spans over two tables, this is the first time I've done this so I want to be sure I'm doing it correctly before I continue doing it wrong for the rest of the project.

The object is named Conversation and it is basically a thread topic with first post. CommentContainer is the post, Comment is going to contain previous edits but I'm not concerned about it too much right now.

EDIT: I've updated my code into working status.

urls.py
code:
from django.conf.urls.defaults import *
from conversation import views

urlpatterns = patterns('',
    url(r'^$', views.conversation_list, name='conversations_conversation_list'),
    #url(r'^show/(?P<id>\d+)/$', list_detail.object_detail,
    #    queryset=Conversation.objects.all(), name='conversations_conversation'),
    url(r'^create/$', views.create_conversation, name='conversations_conversation_create'),
    #url(r'^edit/$', views.edit_profile, name='conversations_conversation_edit'),
)
views.py
code:
from django.views.generic.list_detail import object_list
from django.views.generic.create_update import create_object
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from conversation import models, forms

def conversation_list(request):
    return object_list(request, queryset=models.Conversation.objects.all(), paginate_by=10)

def create_conversation(request):
    if request.method == "POST":
        conversation_form = forms.ConversationForm(request.POST, instance=models.Conversation())
        comment_form = forms.CommentContainerForm(request.POST, instance=models.CommentContainer())
        if conversation_form.is_valid() and comment_form.is_valid():
            new_conversation = conversation_form.save()
            new_comment = comment_form.save(commit=False)
            new_comment.conversation = new_conversation
            new_comment.save()
            return HttpResponseRedirect('/coffee/')
    else:
        conversation_form = forms.ConversationForm(instance=models.Conversation())
        comment_form = forms.CommentContainerForm(instance=models.CommentContainer())
    return render_to_response('conversation/create_conversation.html',
            {'conversation_form': conversation_form, 'comment_form': comment_form})
models.py
code:
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Conversation(models.Model):
    # These three fields are a polymorphic association
    content_type = models.ForeignKey(ContentType, null=True)
    object_id = models.PositiveIntegerField(null=True)
    # Automatically sets the above two values given a valid Model object
    content_object = generic.GenericForeignKey()
    
    user = models.ForeignKey(User, editable=False, null=True)
    title = models.CharField(max_length=100)
    subtitle = models.CharField(max_length=100, blank=True)
    updated_on = models.DateTimeField(auto_now=True, editable=False)
    comments_count = models.PositiveIntegerField(default=0, editable=False)
    class Meta:
        ordering = ["updated_on"]

class CommentContainer(models.Model):
    conversation = models.ForeignKey(Conversation, editable=False)
    user = models.ForeignKey(User, editable=False, null=True)
    message = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    updated_on = models.DateTimeField(auto_now=True, editable=False)
    previous_edits = models.PositiveIntegerField(default=0, editable=False)
    class Meta:
        ordering = ["created_at"]

class Comment(models.Model):
    comment_container = models.ForeignKey(CommentContainer, editable=False)
    user = models.ForeignKey(User, editable=False, null=True)
    message = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    class Meta:
        ordering = ["created_at"]
forms.py
code:
from django import newforms as forms
from conversation import models

class ConversationForm(forms.ModelForm):
    class Meta:
        model = models.Conversation
        fields = ('title', 'subtitle')

class CommentContainerForm(forms.ModelForm):
    class Meta:
        model = models.CommentContainer
        fields = ('message')

class CommentForm(forms.ModelForm):
    class Meta:
        model = models.Comment
        fields = ('message')
Is this the best way to do this?

It seems I was being a little bit greedy and that Generic views don't really do what I wanted, in that the view needed to save two models at once. If I could get it any shorter at all that would be great, In Rails I can fit it into about 5 or 10 lines of code which is why it feels like I'm not doing this right.

If I refresh the page after I've posted Firefox asks me if I want to resend the data, I don't want it to give me the opportunity to do this.

Nolgthorn fucked around with this message at 11:52 on May 27, 2008

Typh
Apr 18, 2003

LAY EGG IS TRUE!!!
How in the hell do you people handle dynamic menus? I just want a simple submenu on my sections, but have no idea how to go about pulling the relevant subsections (which could be flatpages or not). Flatpages I can get because I gave them a section property, but regular urls/views I have no idea how to specify their parents/pull them out. Without data duplication anyways.

No Safe Word
Feb 26, 2005

James Bennett has apparently just finished up some of the final edits on his upcoming Django book, "Practical Django Projects". You may recognize him from some online sites as ubernostrum, but he's one of the higher profile Django devs and an all-around pretty bright guy. I'm sure his book will be very good, and for anyone looking to get started in the next few months it sounds like this may be a good book to have on the shelf.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

No Safe Word posted:

James Bennett has apparently just finished up some of the final edits on his upcoming Django book, "Practical Django Projects". You may recognize him from some online sites as ubernostrum, but he's one of the higher profile Django devs and an all-around pretty bright guy. I'm sure his book will be very good, and for anyone looking to get started in the next few months it sounds like this may be a good book to have on the shelf.

But this other book says I could most assuredly learn Django in 24 hours. :colbert: So what's James Bennett going to do about that?

bitprophet
Jul 22, 2004
Taco Defender
James' book is, in my understanding, exactly what the title implies - a look at developing some practical sample applications. I don't think he's going for the "learn Django just by reading my book", which is what the official book, the Sams (lol) book, or my book (http://www.amazon.com/dp/0132356139/) would be good for.

Looking forward to James' book, though, he's a very smart cookie and he and I pretty much tag-teamed the IRC channel back in the day in terms of fielding questions. He's also been the official Django release manager for, what, a year now? :) so he's practically part of the core team.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Neato, is a developers library more or less what you find on the Django web site? I'm curious.

bitprophet
Jul 22, 2004
Taco Defender

Nolgthorn posted:

Neato, is a developers library more or less what you find on the Django web site? I'm curious.

If you mean the "Developer's Library" on the cover image of my book, naw, it's just the "line" or series of Addison-Wesley books it's being published in (sorta like how O'Reilly has the In A Nutshell series).

The book I'm writing (with two other guys, so it's really "our" book, not "my" book :)) is sort of a generalist book...it's got wide coverage of the framework's features, both basics and contrib apps (so it functions as a general howto like the official Django docs/book); it's got four example application chapters (probably similar, but smaller, than James'); it's also got an intro chapter on Python for Python newbies, and overall tries to keep a focus on practical development practices, something none of the other books really have (except James' by virtue of the example-app focus).

/self-promotion

ATLbeer
Sep 26, 2004
Über nerd
Has anyone seen a clever way to store revisions or changes to data?
(That wasn't a great way to explain it. Basically a have a set of models but, I want to be able to go back and explore the past versions and easily identify the differences between the older version and the current version)

I have a couple of ideas kicking around in my head but, I don't want to reinvent the wheel if someone has already found a clever way to do it.

hey mom its 420
May 12, 2007

Yeah, ummm, do you mean like version control? Like mercurial, git, svn, etc.

king_kilr
May 25, 2007
Checkout django-wikiapp it keep revisions for all the articles, theres also django-rcsfield.

king_kilr
May 25, 2007
Checkout django-wikiapp it keep revisions for all the articles, theres also django-rcsfield.

king_kilr
May 25, 2007
Checkout django-wikiapp it keep revisions for all the articles, theres also django-rcsfield.

ATLbeer
Sep 26, 2004
Über nerd

Bonus posted:

Yeah, ummm, do you mean like version control? Like mercurial, git, svn, etc.

The triple post below you got it right...

BTW, how the gently caress do you triple post!

hey mom its 420
May 12, 2007

Ooh, you mean like revisions are stored in wiki pages, kind of like that? Ah, I don't know, but it seems like the cool triple post nailed it. lol

ATLbeer
Sep 26, 2004
Über nerd

Bonus posted:

Ooh, you mean like revisions are stored in wiki pages, kind of like that? Ah, I don't know, but it seems like the cool triple post nailed it. lol

Yeah djnago rcs looks pretty cool actually. It looks fairly beta though. I want to take a peak under the hood to see how hacky it is.

leinad
Jan 14, 2003

Not sure if this has been answered but I can't search, so here goes. This documentation talks about how to get the person and city of a given book, but what is the best way to get a list of books, their associated author, and any other city information in the model given a city id? I could probably figure out the SQL, but what's the Django way?

bitprophet
Jul 22, 2004
Taco Defender
Are you asking whether select_related() will pull things down across reverse foreign keys? As far as I know, not having checked the source, it wouldn't (but I'm not an expert in this area) - it would probably only follow 'forward' relationships. So in the setup given in that documentation, City.objects.all().select_related() wouldn't pull in all the Persons and Books.

Should be pretty easy to figure out if this is the case, though, by doing from django import db and then printing out db.queries (I think that's the right name) at different points, before/during/after running some queries.

Just did some Googling and found at least one Django-users post implying that it does not follow reverse relations at this point in time; the post was from mid April, though, so it's possible the queryset-refactor merge has changed things.

king_kilr
May 25, 2007
Correct, select_related() only goes forward at present, there was some discussion a while ago about having it work backwards as well, and malcolm said he would probably look at it, and that it was doable.

king_kilr
May 25, 2007
Correct, select_related() only goes forward at present, there was some discussion a while ago about having it work backwards as well, and malcolm said he would probably look at it, and that it was doable.

leinad
Jan 14, 2003

That's what I figured. So how would you get that information? Straight up SQL query?

king_kilr
May 25, 2007
You can still do backwards relations: http://www.djangoproject.com/documentation/db-api/#backward you just can't use select_related to prefect them

Sock on a Fish
Jul 17, 2004

What if that thing I said?
Is there any good reason why I shouldn't customize a set of Users by creating them as instances of a subclass of django.contrib.auth.models.User? I can't see why it wouldn't, but the official book doesn't even suggest it as an idea, and further suggests that to create Users with a profile you should create a new model for the profile with the user id as a foreign key.

hey mom its 420
May 12, 2007

Because then you don't get to use some the nifty features that contrib.auth offers, like messages and getting the user directly from request. The proper way to extend the User model is described here.

Sock on a Fish
Jul 17, 2004

What if that thing I said?

Bonus posted:

Because then you don't get to use some the nifty features that contrib.auth offers, like messages and getting the user directly from request. The proper way to extend the User model is described here.

Excellent, thanks!

Sock on a Fish
Jul 17, 2004

What if that thing I said?
I've Googled around, and can't find an answer -- is there any significant performance boost from using a SmallIntegerField in my models instead of an IntegerField? One of my models is going to have about 100 attributes, only a handful of which are going to be negative or possibly exceed 65,535. However, I'd rather not make my model less flexible unless I'm going to get something for it.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!

Sock on a Fish posted:

I've Googled around, and can't find an answer -- is there any significant performance boost from using a SmallIntegerField in my models instead of an IntegerField? One of my models is going to have about 100 attributes, only a handful of which are going to be negative or possibly exceed 65,535. However, I'd rather not make my model less flexible unless I'm going to get something for it.

Performance? none. The advantage comes when you have millions (or even billions) and it nets you a slight storage improvement.

duck monster
Dec 15, 2004

ATLbeer posted:

BTW, how the gently caress do you triple post!

Its that drat robot again :argh:

ATLbeer
Sep 26, 2004
Über nerd

duck monster posted:

Its that drat robot again :argh:

He seems to be stuck in a negative incrementing loop. First triple post, then double post, now single post.

I think he's broken now

Adbot
ADBOT LOVES YOU

ashgromnies
Jun 19, 2004
Does anyone know anything about the ImageField that they tossed into the trunk version of Django? I can't find much documentation on it. I need to make sure the image a user uploads isn't some 100mb monstrosity and I can't really find anything on Google that helps me out. Anyone have any ideas?


edit: well, here are the two models I came up with. I think someone can still attack me just by virtue of uploading a huge image, though.

code:
from django.db import models
from django import newforms as forms
import Image, ImageFile

class ImageSizeLimitedField(forms.ImageField):
    def clean(self, value, initial):
        if not value:
            raise forms.ValidationError('Please upload an image')
        size = len(value['content'])
        if size > 1024000:
            raise forms.ValidationError('Filesize too large. Expected <= 1 megabyte')
        try:
            p = ImageFile.Parser()
            p.feed((value['content']))
            im = p.close()
        except IOError:
            raise forms.ValidationError('Please upload a valid image')
        return value

class ImageUploadForm(forms.Form):
    image = ImageSizeLimitedField()

ashgromnies fucked around with this message at 19:47 on Jun 2, 2008

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