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
Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC
I know this is a big vague, but hopefully someone may have an idea

code:
def contact_delete(request, file, contact_id): 
	
	contact_record = Contact
	contact_record = get_object_or_404(Contact, id=contact_id)
	contact_record.delete()
	
	return HttpResponseRedirect('/IR/' + file + '/contacts/')		
this raises an error stating "__init__ takes 2 args, but only 1 is given". I am not sure why/how 2 args are needed for deletion since all the examples show object.delete() as the way to delete

http://dpaste.com/45018/ - Full error message
http://dpaste.com/45019/ - My views, line 100 is the delete part

Adbot
ADBOT LOVES YOU

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

Wulfeh posted:

I know this is a big vague, but hopefully someone may have an idea

code:
def contact_delete(request, file, contact_id): 
	
	contact_record = Contact
	contact_record = get_object_or_404(Contact, id=contact_id)
	contact_record.delete()
	
	return HttpResponseRedirect('/IR/' + file + '/contacts/')		

Oh woops, contact_record = Contact was left there by accident when I was trying to debug. That can be ignored really.

No Safe Word posted:

Also, from your views:
code:
		blammo = "SLAMMMOOOOO" #temp - cant do an empty if, but we'll need an if soon
It's funny, but you do know about pass, right? :)

I remember passing over that when I started learning Python a few weeks ago, but yea, now it will stick with me since you mentioned it.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC
Totally forgot about this, but since I did get this fixed I thought I should mention what was causing it.

Wulfeh posted:

I know this is a big vague, but hopefully someone may have an idea

code:
def contact_delete(request, file, contact_id): 
	
	contact_record = Contact
	contact_record = get_object_or_404(Contact, id=contact_id)
	contact_record.delete()
	
	return HttpResponseRedirect('/IR/' + file + '/contacts/')		
this raises an error stating "__init__ takes 2 args, but only 1 is given". I am not sure why/how 2 args are needed for deletion since all the examples show object.delete() as the way to delete

http://dpaste.com/45018/ - Full error message
http://dpaste.com/45019/ - My views, line 100 is the delete part

I had my objects set to a custom search manager in my models, and when I was trying to delete the model it was trying to use the search managers args, which I wasn't passing. Anyway long story short I now have:

code:
objects = models.Manager
fulltext = SearchManager(('first_name','last_name','file'))

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

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

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

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

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++.

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"),
		)

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

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 %}

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC
http://www.djangoproject.com/documentation/db-api/#save-foo-file-filename-raw-contents

Have you tried that out? save_FOO_file()

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

Sock on a Fish posted:

Say I want to weigh the items returned in a search based on what other users have selected for the same search. Should I create a new model and new record for every search? Should I add a dict to the model on the items being searched? Is there an easy way to serialize a dict and put it in the database?

It seems like storing a record of every search made would eventually take up huge amounts of space, but at the same time it seems almost inappropriate to store this data in the model for the items being searched.

Can you explain this a little more? You mean like tags? Everytime a keyword is searched, add that keyword to the table if its not found, otherwise add the count for that keyword + 1. Something like that?

ashgromnies posted:

Yeah but it doesn't give me a model to store in the database if I use that. I could write raw SQL to do it but I want to do it "the Django way".

I don't need the model right now but in the future I will because I'm going to do spidering/aggregating so it'd be nice to have the framework set up to support storing a record of each image in the database along with some metadata I calculate.

The image isn't saved to the database it will be saved to your servers filesystem according to your upload_to and media_url

Wulfeh fucked around with this message at 22:38 on Jun 3, 2008

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC
So is anyone going to Djangocon? I grabbed a pair of tickets this morning for my boss and I.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC
Alright, got another problem that I am not quite sure how to approach.

We are trying to split up a section of the site in to a multi-step process so it is easier for user's to complete the information, obviously this looks like a job for FormWizard.

The problem I am having trouble with is that, not only do we take information for a model via form fields, but there is one part that requires the user to enter a search query and pick a person based on that query.

What I don't know how to do is maintain the form-wizards state when the user goes for a search, and picks a user. If I leave the current url, they lose all the data entered, so you can't re-enter the wizard from where they left off.

As an added bonus, they should be able to search and pick people several times.

One idea I had was to add a form to the wizard where they entered their search queries and it would return back another form with a MultipleChoiceField with all the queries and they can choose who they wanted, but that could be a little difficult for the end user to see who they are choosing.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

bitprophet posted:

AJAX

Another clincher is that we try to stay as far away as possible from AJAX / JS calls to the DB. Reason is because we are diligent in being handicap friendly. This means screen readers have to be able to go through this and be A-Ok at reading what's going on.

I think we may end up just using the form wizard for the model, saving it, then redirecting with the id in the url to the next step, and just have that step be repeatable.

We had discussed this idea in length, but put it down at first because we felt it wouldn't be coherent enough programatically, but seems to be one of the few options.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC
Fourthing the "hard to find poo poo you need in the new docs," and it isn't just because I memorized the the layout of the old one. It isn't clear where the links are going to lead sometimes and you have to dig from one page to the next to find what you need, unless you know the search term you want.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

nbv4 posted:

get_profile returns an object, so to use it in a template, you must do something like "{{ request.user.get_profile.posts_per_page }}", which unfortunately doesn't work.

That example you just put works perfectly fine, why do you say it doesn't?

What bitprophet said is correct, if posts_per_page took some args, then you would have to do it the other way.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

Janin posted:

code:
# myproject/myapp/models.py

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


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

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC
I watched the Djangocon vid again, and he mentioned that when you start using joins across several tables with Meta Ordering, it will do ordering on every table where Meta ordering was specified. So for large datasets, it will be ordering itself several times over, which you probably don't want it doing.

Wulfeh fucked around with this message at 16:19 on Nov 7, 2008

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

Ansible posted:

I have a ModelForm based on the Consumption model, which works for users to add foods to their log. (I'm assigning User in views.py after they POST the form with User excluded, is there a better way to do this?)

Doing it like that is fine, there are a variety of ways to accomplish this. Another option would be to do this is by passing the user into the form, and overriding save to add the user in. Like so,

code:
class BlankForm(forms.ModelForm):
        def __init__(self,user,*args,**kwargs):
                self._user = user
                super(forms.ModelForm,self).__init__(*args,**kwargs)
                
        def save(self,*args,**kwargs):
                record = super(BlankForm,self).save(commit=False)
                record.user = self._user
                record.save(*args,**kwargs)
		
		return record                                                                                                           

Ansible posted:

I run into a problem with the Nutrient table. I have a whole gaggle of Nutrients, but only want to show a handful. The only way that I've found I can access the table is with a loop through consumption_item.measure.food.nutrient_set.all - but I can't filter that to only include Nutr_Def_id = 1 (for example). I want to do something like {{ consumption_item.measure.food.nutrient_set.(filter(id_Nutr_Def=1)) }}.

Should I be passing another context to pull this information, or should I have my model set up differently?

I wouldn't do this in the template, filter the nutrients you want from the view, and pass it from the view to the template.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

Mashi posted:

Measures.objects.select_related('food') will produce a join on your food table which loads the related food instances in bulk, rather than running individual queries for them when they are accessed via the measure instances.

This needs to be stressed, if you fail to implement this you are going to be making a ridiculous amount of unneeded queries to the database.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

king_kilr posted:

No, what needs to be stressed is that that doesn't change the results returned, it is merely an optimization, start righting your site without any optimizations, and add as needed, if you just start sticking select_related throughout your code wiht no thought you are going to generate lots of massive joins that are far worse than extra queries.

I agree, but it is an easy optimization to make if you know you going to be using those relations and you are loading several instances of that model.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC
I had no problems developing on a windows machine with Django back in 0.96, and we used a Debian box for our production server.

I used Notepad++ for editing and tortoise svn as an interface for using svn on windows.

As for the python interpreter, I don't know if it runs any faster or slower, but I don't remember running into anything that stopped me from developing. Just make sure to setup all your path variables correctly in Windows and there shouldn't be any trouble.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

SlightlyMadman posted:

I've got a question about many-to-many relationships. In the following model:

How do you want the user associated to these models? Do you want the publication as a whole being attached to the user, or are individual pages of a publication written by different users?

The first means putting User on Publication.

The second means putting user on the Page model.

After that, you have two options, you can either put Page as a M2M field on the Publication model, or you can put Publication as a Foreign Key on the Page Model.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

Jabab posted:

code:
def index(request, page=1):
    home_articles_raw = Article.objects.raw("""SELECT ar.*, na.article_ptr_id as is_news, rev.article_ptr_id as is_review
        FROM `cms_article` ar
        LEFT JOIN `cms_newsarticle` na ON ar.id = na.article_ptr_id
        LEFT JOIN `cms_review` rev ON ar.id = rev.article_ptr_id""")
    all_home_articles = []
    for article in home_articles_raw:
        if article.is_news:
            article.link = '/news/' + str(article.id)
        if article.is_review:
            article.link = '/review/' + str(article.id)
        all_home_articles.append(article)
Is there a better way of doing this?

If you want to avoid raw sql, I believe you can name the child's ptr as such:

code:
class Article(models.Model):
    author = models.CharField(max_length=100)
    title = models.CharField(max_length=150)
    body = tinymce_models.HTMLField()

class NewsArticle(Article):
    base = models.OneToOneField(Article,parent_link=True,related_name="News")
    categories = models.ManyToManyField("NewsArticleCategory")
        
class Review(Article):
    base = models.OneToOneField(Article,parent_link=True,related_name="Review")    
    product = models.CharField(max_length=150)
    categories = models.ManyToManyField("ReviewCategory")
then in the view, just for example, you can distinguish like so

code:
for ar in Article.objects.all():
    try:
        article.link = ar.News.id
    except AttributeError:
        article.link = ar.Review.id
However, I wouldn't do this in the view, I would pass the results to the template and loop through them in there and use the {% url %} template tag to display the link. Look at naming your urls.

http://docs.djangoproject.com/en/dev/topics/http/urls/#naming-url-patterns

Basically it would look something like this in your template
code:
{% for ar in articles %}
    {% if ar.News %}
    <a href="{% url news_article ar.News.id %}">{{ ar.title }}</a>
    {% else %}
    <a href="{% url review_article ar.Review.id %}">{{ ar.title }}</a>
    {% endif %}
{% endfor %}
that's just how I would do things anyway.

Adbot
ADBOT LOVES YOU

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

quote:

Is there a one liner for:
code:
    context['latest_news'] = latest_news
    context['news_cats'] = news_cats
perhaps something like:
code:
context += {'latest_news': latest_news, 'news_cats': news_cats}

adding to a python dict object is just as easy as you thought

code:
context.update( {'latest_news': latest_new, 'news_cats': news_cats} )

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