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

Larry Horse posted:

edit: I just blanked the strings in the enum structure. I don't know if this is the "right" way to do this, but it works.

By which I assume you mean your "enum"s look like this:

code:
CHOICES_FOR_SOME_FIELD = (
    ('option1',''),
    ('option2',''),
    ...
    ('optionN','')
)
?

If so, that's one way to do it, since you don't actually intend for each individual radio button to have a label. It's also probably the quickest way, given that the other alternative is to manually spit out the HTML yourself (and checking e.g. {{ form.some_field.data }} to determine which radio buttons are selected, if you ever display the form in a previously-filled-out state, like if you redisplay on user error). I say this assuming you currently do something like {{ form.some_field }} for the display...which is what is automatically spitting out labels.

If you're on trunk instead of 0.96, I think there may be a way to print the formfield sans label, with newforms (the form/manipulator stuff in 0.96 is now 'oldforms'; newforms is a lot better and gives you more granular control) but I don't know for sure off the top of my head.

Adbot
ADBOT LOVES YOU

Larry Horseplay
Oct 24, 2002

Yep, that's exactly how it looks. And it works!

I think it's a testament to how good Django is that whenever I have to do anything somewhat "manually" I wonder if I'm doing it right.

bitprophet
Jul 22, 2004
Taco Defender
Yea, Django's awesome like that :D

One minor note, the approach you're taking is potentially a little "off" accessibility-wise and/or markup-wise, in that it is probably littering your code with lots of <label for="field_name"></label> tags, i.e. tags which are generally intended to have text in them but which are now empty.

Chances are this isn't a huge problem, or that it's not an issue in your case (tho it could potentially cause style problems in e.g. IE6 even if you don't care about people with screen-readers), but I wanted to make sure you knew the diff between this approach and one where the <label> tags aren't even displayed :)

Larry Horseplay
Oct 24, 2002

Strangely enough, I happen to work for a non-profit where accessibility is an issue.

Eventually I'll have to create a subclass and render it myself, I guess. But for now I'll get the thing working.

I'm using the reportlab python package to make PDFs right now as part of the package, actually. It's pretty cool :)

ATLbeer
Sep 26, 2004
Über nerd

Larry Horse posted:

Yep, that's exactly how it looks. And it works!

I think it's a testament to how good Django is that whenever I have to do anything somewhat "manually" I wonder if I'm doing it right.
I had the same reaction when I started using Django myself. I found myself implementing something that was already built into Django.

For example if you didn't know. You have a model already pre-built. Need a form for that model?

ModelForm = form_from_model(SomeModel)
ModelForm.as_ul()

Poof..

king_kilr
May 25, 2007

ATLbeer posted:

I had the same reaction when I started using Django myself. I found myself implementing something that was already built into Django.

For example if you didn't know. You have a model already pre-built. Need a form for that model?

ModelForm = form_from_model(SomeModel)
ModelForm.as_ul()

Poof..

This is no longer the correct way to do it actually, if you are using SVN you should use ModelForms.

hey mom its 420
May 12, 2007

deimos posted:

code:
python manage.py sqlreset
python manage.py loaddata data

Just another response to this: I remember trying sqlreset before but couldn't remember why I'm not using that command. Tried it again today. The thing with sqlreset is that you have to specify all the app names that you want to reset. That's a bit of a hassle when your project is decoupled into a bunch of apps. So I guess I'm still sticking with my yes "no" script :)

Zenobia
Nov 11, 2007

i can't see the captcha image
where is it
I'm trying to filter objects by a foreign key.

In my models.py I have:
code:
user = models.ForeignKey(User, unique=True)
as a field for this particular class.

What I'd like to do is get all entries added by this user, but
code:
Entry.objects.filter(user='zenobia')
gives me nothing, although I'm sure the entered user string is correct.
Filtering by slug works without trouble, so I'm guessing it has something to do with the field being a ForeignKey?

hey mom its 420
May 12, 2007

Use a double underscore to follow foreign key relationships when filtering, selecting, etc.
code:
Entry.objects.filter(user__username='zenobia')
Basically the form is <FK field>__<property> and with that you can also follow them as far as you want, like
code:
Employee.objects.filter(company__country__label='US')
On an unrelated note, I'm implementing a back end for a site for a client right now and because I don't have Django support on my reseller account (hopefully I'll have it soon though), I've spent like three days implementing something in PHP that I could have done in one day with Django. Just goes to show, don't take awesome things like Django for granted.

Jacko
Aug 30, 2002

I just created my first Django project and I am having some trouble figuring out where certain work should happen (I'm new to Web development and Django). Hopefully someone can help.

For example:

I am writing a simple referee scheduler for youth soccer. I have a game model, a referee model, and a basic template where I list out each game and referee.

What I would like to do is have games listed in a column on the left, referees listed in a column on the right, and let the user click a game then click a ref and have the assignment made.

This is where my confusion comes in, because I'm not sure where I should do the work of assigning the referee to the game. Is this in a separate view? How do I get information into this other view, such as the selected game?

Then, finally, after this assignment is made, how do I reload the original page (with the updated assignment) so the user can continue to make selections?

Thanks.

bitprophet
Jul 22, 2004
Taco Defender
Not sure if you've been using generic views for your existing template(s), but for this you will need a normal, non-generic view. For input it'll probably just take the request, and you'll want to use a form with checkboxes or radio buttons to make this happen (you can use JavaScript so that clicking the name of the game/referee selects the appropriate form control, if you want to make it even easier for users).

Then your view will do what's a pretty normal form-processing flow control: check to see if request.POST is non-empty (and request.POST is a dict, so you can just do if request.POST: since an empty dict is equal to False). If it is non-empty (i.e. the user has submitted the form) you see what game/referee were selected and make the association in the database (how exactly this is done depends on how you've related the two models, but I'm assuming a many-to-many given your description).

After that if statement (but not in an else!) you will then want to render the template; users hitting the page for the first time will just get the normal display, while users who have submitted the form will get it back again, as you've said you want them to.

Here's an example...please don't copy-paste this, as I'm going from memory, but instead make sure you understand what it's doing and look up the correct methods and such to use :) Copy-paste is a terrible way to learn! Also, I am very lazy when whipping up HTML for the first time, so this isn't awesome front-end work either (but CSS-styled divs and spans are generally better than tables, regardless).

Template
code:
<form action="" method="POST">
<div class="page-wrapper">
    <div id="left-col">
        {% for game in games %}
        <input type="radio" name="game" value="{{ game.id }}" />
        <span class="game">{{ game.title }}</span><br />
        {% endfor %}
    </div>

    <div id="right-col">
        {% for referee in referees %}
        <input type="radio" name="referee" value="{{ referee.id }}" />
        <span class="referee">{{ referee.name }}</span><br />
        {% endfor %}
    </div>

    <input type="submit" value="Associate the selected game and ref!" />
</div>
</form>
Model (just to fit with the rest of the example)
code:
from django.db import models

class Referee(models.Model):
    name = models.CharField(maxlength=100)

class Game(models.Model):
    title = models.CharField(maxlength=100)
    referees = models.ManyToManyField(Referee)
View
code:
from django.shortcuts import render_to_response
from myproject.myapp.models import Referee, Game

def refs_and_games(request):
    if request.POST:
        # Omitting checks to make sure a game & ref were actually selected!
        game = Game.objects.get(pk=request.POST['game']) # since we used game.id
        ref = Referee.objects.get(pk=request.POST['referee'] # ditto
        game.referees.add(ref) # no need to call game.save() since it's a m2m op
    return render_to_response('refs_and_games.html')

tehk
Mar 10, 2006

[-4] Flaw: Heart Broken - Tehk is extremely lonely. The Gay Empire's ultimate weapon finds it hard to have time for love.
Can anyone recommend any talks or presentations about Django? I have already watched Web Development for Perfectionists with Deadlines(Google Tech Talk) given by Jacob Kaplan-Moss, and Snakes and Rubies. I seem to get a lot, including motivation, out of things like that.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

bitprophet posted:

One way of accomplishing the task

I wanted to show another way to accomplish this task, though I might be off a little on syntax. I thought modelchoicefields would be a better choice than radiobuttons, but that's just me :)

of course, I am only 2 months old in django and web stuff in general, so take that as you will.

Model
I used the same one as Bitprophet

Template
code:
<form action="." method="POST">
	<div>
	{{ form.games }}
	{{ form.games.errors }}	
	</div>
	<div>
	{{ form.refs }}
	{{ form.refs.errors }}
	</div>
	<div><input class="submit" type="submit" name="submit" value="Connect Refs to Games" /></div>
</form>
View
code:
from django.shortcuts import render_to_response,
from django import newforms as forms
from appname.models import Game, Referee

class ref_game_form(forms.Form):
	games = forms.ModelChoiceField(queryset=Game.objects.all())
	refs = forms.ModelMultipleChoiceField(queryset=Referee.objects.all())

def ref_and_games(request):
	if request.POST:
		form = ref_game_form(request.POST)
		if form.is_valid():
			game = Game.objects.get(pk=form.cleaned_data['games'].id) # I believe this is correct, but it might be wrong
			refs = Referee.objects.get(pk=form.cleaned_data['refs'].id)
			game.referees.add(refs) # I actually didn't know you could do this, thanks bitprophet!
			return render_to_response('refs_and_games.html')
	else:
		form = ref_game_form()
	return render_to_response('refs_and_games.html', { 'form':form, })

Wulfeh fucked around with this message at 04:28 on May 13, 2008

bitprophet
Jul 22, 2004
Taco Defender
Wulfeh's approach is quite valid and leverages the forms framework more than mine does. Main difference template-wise is that his uses the default representation of a field with choices (forget what that is these days but it used to be a dropdown list or a multi-select box depending on field type), whereas mine has a more explicit/manual HTML setup. The former is quicker while the latter gives you more control.

I guess I went with the latter myself because the way the problem was phrased made me think "ok, he's got a fairly specific page layout in mind, so that means custom form HTML", but that's not always necessary. Mine actually ended up involving less work than Wulfeh's, but is also less realistic as it omits all the error checking and such :) In the long run, the more you can leverage the forms stuff, the better off you'll be.

FrontLine
Sep 17, 2003
I gave Mr. Adequate hot, steamy man love and all he bought me was a custom title!
Can somebody post an example of how to use the validators mentioned at the bottom of http://www.djangoproject.com/documentation/forms/

The one provided isn't to clear, for a newb like me, on the proper usage.

Specifically I have three fields that are only required if the user selects 'Yes' on a BooleanField with the RadioSelect widget. If the user selects or No or selects nothing the fields aren't required.

I'm thinking RequiredIfOtherFieldGiven but prove me wrong :)

king_kilr
May 25, 2007

FrontLine posted:

Can somebody post an example of how to use the validators mentioned at the bottom of http://www.djangoproject.com/documentation/forms/

The one provided isn't to clear, for a newb like me, on the proper usage.

Specifically I have three fields that are only required if the user selects 'Yes' on a BooleanField with the RadioSelect widget. If the user selects or No or selects nothing the fields aren't required.

I'm thinking RequiredIfOtherFieldGiven but prove me wrong :)

Don't use that, you should be using newforms.

And also, for everyone using pretty much any version of django there is a security update to fix an XSS issue in the Admin, more info on the django blog.

Wedge of Lime
Sep 4, 2003

I lack indie hair superpowers.

Wulfeh posted:

checkboxes and newforms.

Interestingly I recently wanted to select the available check boxes based on data passed to my view. This isn't that well documented so I thought i'd share my example.

forms:
code:
class SampleForm(forms.Form):
    test_field = forms.ModelMultipleChoiceField(queryset=Model.objects.none())
Then in my view I only want to display a subset of the Model objects, I discovered this can be done as follows:

views:
code:
form = SampleForm()
form.fields['test_field'].queryset = Model.objects. # create any query set you wish  here
Fairly straight forward once you've seen it done.

king_kilr
May 25, 2007
I'd usually do that in the __init__ method, rather than in the view.

[code]
class SampleForm(forms.Form):
field = forms.ModelChoiceField(queryset=Model.objects.none())
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super(SampleForm, self).__init__(*args, **kwargs)
self.fields['field'].queryset = Model.objects.filter(owner=user)

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

FrontLine posted:

I want to use validation errors

king_kilr posted:

Use newforms
http://www.djangoproject.com/documentation/newforms/#custom-form-and-field-validation

Yea the old forms and manipulators are on the way out I believe. To do it in newforms, you would put something like this in your form class:

code:
def clean(self):
	if 'bool_field' in self.cleaned_data:
		if self.cleaned_data['bool_field']:
			if not 'field1' in self.cleaned_data:
				raise forms.ValidationError('field1 is required')
			if not 'field2' in self.cleaned_Data:
				raise forms.ValidationError('field2 is required')
			if not 'field3' in self.cleaned_data:
				raise forms.ValidationError('field3 is required')
	return self.cleaned_data
Just make sure that you loop through the errors in the template, since they aren't field specific errors, they are thrown into a list form.non_field_errors

king_kilr
May 25, 2007
I'd usually do that in the __init__ method, rather than in the view.

for example:
code:
class SampleForm(forms.Form):
    field = forms.ModelChoiceField(queryset=Model.objects.none())
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user')
        super(SampleForm, self).__init__(*args, **kwargs)
        self.fields['field'].queryset = Model.objects.filter(owner=user)

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC
Something I am having trouble with are perms, I want to do something like user.has_perm(perm_object), but IRC told me that has_perm won't validate a perm object. I am not sure how to go about checking some custom permissions, I am open to ideas. ( I am trying to restrict a fields choices with permissions ).

Invalid code
code:
tag_list = []
for tags in Tag.objects.all():
	if user.has_perm(tags.perm): # Will always be false
		tag_list.append(tags)
if tag_list:
	self.fields['tags'] = forms.MultipleChoiceField(choices=(tag_list, ), widget=forms.CheckboxSelectMultiple())
One workaround I was toying with was something like:

ModelMultipleChoiceField(queryset=Tags.objects.filter(perms__exact=user__user_permissions))

Wulfeh fucked around with this message at 21:26 on May 14, 2008

FrontLine
Sep 17, 2003
I gave Mr. Adequate hot, steamy man love and all he bought me was a custom title!

king_kilr posted:

Don't use that, you should be using newforms.

And also, for everyone using pretty much any version of django there is a security update to fix an XSS issue in the Admin, more info on the django blog.

I am using newforms :( I'm just a bit to new to this to realise what's deprecated and what's not.

Wulfeh posted:

http://www.djangoproject.com/documentation/newforms/#custom-form-and-field-validation

Yea the old forms and manipulators are on the way out I believe. To do it in newforms, you would put something like this in your form class:

code:
def clean(self):
	if 'bool_field' in self.cleaned_data:
		if self.cleaned_data['bool_field']:
			if not 'field1' in self.cleaned_data:
				raise forms.ValidationError('field1 is required')
			if not 'field2' in self.cleaned_Data:
				raise forms.ValidationError('field2 is required')
			if not 'field3' in self.cleaned_data:
				raise forms.ValidationError('field3 is required')
	return self.cleaned_data
Just make sure that you loop through the errors in the template, since they aren't field specific errors, they are thrown into a list form.non_field_errors

I'll give this a try and post a trip report. Thanks!

deimos
Nov 30, 2006

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

Wulfeh posted:

code:
def clean(self):
	if 'bool_field' in self.cleaned_data:
		if self.cleaned_data['bool_field']:

Gah, this is a pet peeve of mine, it's a bit wasteful and IMO makes it harder to read when you have a single method that does both: self.cleaned_data.get('bool_field', False) works fine to replace both of those.

Allie
Jan 17, 2004

deimos posted:

Gah, this is a pet peeve of mine, it's a bit wasteful and IMO makes it harder to read when you have a single method that does both: self.cleaned_data.get('bool_field', False) works fine to replace both of those.

Even better, just .get('foo'). It'll return None when the key doesn't exist, which evaluates to False in a boolean context.

I'd be more concerned about his tabs for indentation, which is definitely not part of any accepted Python coding standard or style guideline that I've ever heard of or seen before (the official Python style guide specifies 4 spaces for tabs).

The if not ... in ... is also kind of hard to read. I'd use if ... not in ... :)

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

deimos posted:

Gah, this is a pet peeve of mine, it's a bit wasteful and IMO makes it harder to read when you have a single method that does both: self.cleaned_data.get('bool_field', False) works fine to replace both of those.

That's pretty cool, i'll try to start using that.

Milde posted:

.get('foo')
Tabs and Semantics


Even better for the bool

Honestly, it must be from the way I copied it from my editor, because my tab settings are set to 4 spaces. I don't see why indentation should even be mentioned, it's obvious I am totally trying to "break the standard" and be "unique".

for the: if not ... in ... and the if ... not in ... is that just a preference of yours, or do most Python developers try to strive for the latter? (it's like asking "if there isn't this field in the cleaned data", or "if the field isn't in the cleaned data")

Allie
Jan 17, 2004

Wulfeh posted:

for the: if not ... in ... and the if ... not in ... is that just a preference of yours, or do most Python developers try to strive for the latter? (it's like asking "if there isn't this field in the cleaned data", or "if the field isn't in the cleaned data")

I'd use not in because it reads more like English. It's just easier for me to read, that's all. Using not in reads to me like both of your examples, whereas using not ... in ... makes me pause for a second to think about it.

It's obviously not a huge deal, but readability is a pretty important tenet of Python, so I guess I notice these things more than in other languages.

Jacko
Aug 30, 2002

bitprophet posted:

awesome stuff...

Wulfeh posted:

awesome stuff...
This was a huge help, I was *hoping* to post back with some results but as I do one thing I realize I'm missing something else, so I have been backtracking to make sure I understand the fundamentals. I'll definitely post back (with more questions :) )when I get this implemented.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC
It took me a few weeks of playing with the whole django framework and finally having that "Aha!" moment where you understand how all the different parts interact. I never knew about MVC frameworks, web development, databases, or anything of that sort before I started learning django and python, I had mostly only known how to do console stuff with C or C++. So it is kind of fun seeing how easy it is to create something and see results pretty much instantly. I also love how python is so easy to work with, compared to literally "fighting" with C++.

bitprophet
Jul 22, 2004
Taco Defender

Wulfeh posted:

I also love how python is so easy to work with, compared to literally "fighting" with C++.

IMHO that's Python's greatest strength: most of the time, your biggest problem is...the problem at hand...not the language or the libraries. When you get down to it, programming is just problem solving and domain modeling, and Python makes it very easy to focus almost entirely on what you're doing, not how you're doing it.

Jacko posted:

I have been backtracking to make sure I understand the fundamentals

Good! It'll take a bit of time, but I'm glad you're doing this - too many people care only about the end result and "getting it working" instead of understanding the tool and/or the right way to solve the problem at hand. If you can manage to juggle both the desire to learn the "Right Way" of doing stuff, and the desire to get things done on time, you'll be a much better developer than most of 'em :)

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I've made one or two custom template filters which I would like to use on every or almost every single page of the web site.

I have a utils application, in it I've created a templatetags folder and added my_filters.py in there. How can I have access to the methods in my_filters without loading it from every template?

That would be easier.

Currently, I always have to put {% load my_filters %} to the top of each one.

bitprophet
Jul 22, 2004
Taco Defender
http://www.djangosnippets.org/snippets/160/

Found by googling for django templatetags "every template" :)

I knew this existed but couldn't remember the specific method to use, and it's not documented for some reason (pretty unusual for Django, but could imply that it's not considered 'stable' yet).

bitprophet fucked around with this message at 15:22 on May 17, 2008

king_kilr
May 25, 2007
It's not documented because it's considered internals, my guess is it's that way because sometimes DRY and explicit bump heads.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

Cool, in order to get it to work I had to use something like this but it works.
code:
# In __init__.py
from django.template import add_to_builtins
add_to_builtins('utils.templatetags.my_filters')
This raises the question about how liberally imports should or should not be used. How much extra processing is required when you use urls.py and views.py to import a lot of stuff, instead of just directing everything in your urls.py file to you view, to only import there.

I would be concerned, that if importing does use up resources, then more resources are being used than necessary. Thoughts?

bitprophet
Jul 22, 2004
Taco Defender

Nolgthorn posted:

This raises the question about how liberally imports should or should not be used. How much extra processing is required when you use urls.py and views.py to import a lot of stuff, instead of just directing everything in your urls.py file to you view, to only import there.

I would be concerned, that if importing does use up resources, then more resources are being used than necessary. Thoughts?

I'm reasonably sure that it doesn't matter; everything except for templates is loaded once, and only once, per Apache child process (or whatever Web server process you're using which has loaded up a Python interpreter) so whether something is imported to your URLconf or your view, it's going to take up memory for that particular process either way. (Also pretty sure that Python interpreters are smart enough that only one copy of each module gets loaded, so importing your Foo model class everywhere won't be a problem...)

This is a good thing, though, because re-loading and re-interpreting all your Django/Python code on each request would be pretty god-awful performance-wise.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

Wulfeh posted:

Something I am having trouble with are perms, I want to do something like user.has_perm(perm_object), but IRC told me that has_perm won't validate a perm object. I am not sure how to go about checking some custom permissions, I am open to ideas. ( I am trying to restrict a fields choices with permissions ).

Answering my own question again, in case anyone finds it useful. This allowed me to add permissions from the admin panel to someone, and if they have those permissions, it restricts what options they can view in that choicefield. If they are a superuser, then they get all permissions.

code:
def __init__(self,user,*args,**kwargs):
	super(forms.ModelForm,self).__init__(*args,**kwargs)
	if not user.is_superuser:
		self.fields['tags'] = forms.ModelMultipleChoiceField(required=False, 
                                      queryset=Tag.objects.filter(perm__in=user.user_permissions.all()), widget=forms.CheckboxSelectMultiple())
	else:
		self.fields['tags'] = forms.ModelMultipleChoiceField(required=False, queryset=Tag.objects.all(), widget=forms.CheckboxSelectMultiple())
		
class Meta:
	model = Contact
	exclude = ('address',)

code:
from django.contrib.auth.models import *
from django.db import models

class Tag(models.Model):
	name = models.CharField(max_length=50)
	perm = models.ForeignKey(Permission)
	def __unicode__(self):
		return u'%s' % (self.name)
	class Meta:
		ordering = ('name',)

class Contact(models.Model):
	tags 	= models.ManyToManyField(Tag,blank=True,null=True)
	class Meta:
		permissions = (
			("Activities", "Can add Activities"),
			("Socks", "Can add Socks"),
			("Newsletter", "Can add Newsletter"),
		)

Larry Horseplay
Oct 24, 2002

Anyone have any Django-based calendaring code they wouldn't mind sharing? It seems like a common use, but I don't see much sample code via Google.

(If no one's got any, though, I'll post what I have once I finish it up.)

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

Larry Horse posted:

Anyone have any Django-based calendaring code they wouldn't mind sharing? It seems like a common use, but I don't see much sample code via Google.

(If no one's got any, though, I'll post what I have once I finish it up.)

http://www.djangosnippets.org/tags/calendar/

There a couple there, and if those aren't exactly what your looking for, I am sure they would be good references

Larry Horseplay
Oct 24, 2002

Wulfeh posted:

http://www.djangosnippets.org/tags/calendar/

There a couple there, and if those aren't exactly what your looking for, I am sure they would be good references

One of those is exactly what I needed. It even works with the models I've already created! I totally forgot about djangosnippets, too (doh!) Thanks!

politicorific
Sep 15, 2007
okay I've crawled out of my hole - the tutorial was a bit confusing with the str methods- time to see if I'm doing things correctly. A few posts to make sure I'm on track

First) performing a len on database results - either djangobook or the documentation says not to do this:

code:
results = ConjewgateEntry.objects.filter(qset).distinct()
    resultnumber=0
    if results:
            resultnumber=len(results)
    letter=letter.upper()
    return render_to_response("c:/django/words/templates/english_index.html", {
            "letter":letter,
            "results":results,
            "resultnumber":resultnumber,
    })
this is so that I can display "x results for ..."

Second random result generator:
code:
def randomly(request):
    import random
    digit = random.randint(1,5000)
    results = ConjewgateEntry.objects.filter(id=digit)#.distinct()
    resultnumber=0
    return render_to_response("c:/django/words/templates/select.html", {
            "digit":digit,
            "results":results,
            "resultnumber":resultnumber,
    })
Then I have my urls.py set up for "(r'^random/', randomly),"

Third: Static pages
code:
def english(request):
    return render_to_response("c:/django/words/templates/englishindex.html", {
    })
Is there a better way?

Finally I would like to make sure that my grammar is correct on this site I'm building. So I get something like "0 results" verses "1 result" - models.py has the meta tag.
code:
def tablenumber(request, digit):
    results = ConjewgateEntry.objects.filter(tablenumber=digit)#.distinct()
    resultnumber=0
    verbstatus= "verbs follow"
    if results:
            resultnumber=len(results)
            print resultnumber
            if resultnumber ==1:
                verbstatus = "verb follows"
    return render_to_response("c:/django/words/templates/tablenumber.html", {
            "digit":digit,
            "results":results,
            "resultnumber":resultnumber,
            "verbstatus":verbstatus
    }) 
Something tells me the "verbstatus" belongs in the template file, not in my views file.

one more thing:
code:
(r'^english/(?P<letter>\w)/', english_index),
this only works with numbers above 10, how do I make it work with numbers equal to or greater than 1?

So, does this all look okay?

Adbot
ADBOT LOVES YOU

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

politicorific posted:

performing a len on database results - either djangobook or the documentation says not to do this:
this is so that I can display "x results for ..."
code:
results = ConjewgateEntry.objects.filter(qset).distinct()
    resultnumber=0
    if results:
            resultnumber=len(results) # use results.count()
you can use .count() on any queryset list, they mention not using len() because that will "get" every single object to count it.

politicorific posted:

Third: Static pages
Is there a better way?
code:
def english(request):
    return render_to_response("c:/django/words/templates/englishindex.html", {
    })
Yes, in your urls.py you can direct_to_template html pages
code:
from django.views.generic.simple import direct_to_template
patterns('django.views.generic.simple',
    (r'^$', 'direct_to_template', 	{'template': 'englishindex.html'}),
)

politicorific posted:

Finally I would like to make sure that my grammar is correct on this site I'm building. So I get something like "0 results" verses "1 result" - models.py has the meta tag.

Something tells me the "verbstatus" belongs in the template file, not in my views file.
code:
def tablenumber(request, digit):
             if resultnumber ==1:
                verbstatus = "verb follows"
    return render_to_response("c:/django/words/templates/tablenumber.html", {
            "digit":digit,
            "results":results,
            "resultnumber":resultnumber,
            "verbstatus":verbstatus
    }) 
In the template, there are template tags that emulate if, for, and other neat things.

So for what you wanted you could do
code:
{% ifequal resultnumber 1 %}
    verb follows: {{ variable }} # I think this is what your asking right?
{% endifequal %}

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