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
Hanpan
Dec 5, 2004

Going to show my ignorance here but whatever. I noticed when Django is querying the auth database, it selects EVERYTHING including the users password:

code:
SELECT `auth_user`.`id`, `auth_user`.`username`, `auth_user`.`first_name`, `auth_user`.`last_name`, 
`auth_user`.`email`, `auth_user`.`password`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.
`is_superuser`, `auth_user`.`last_login`, `auth_user`.`date_joined` FROM `auth_user`
Is this a potential security risk or should I not worry about it? I'm assuming if someone has forced access to the SQL results they have access to the database anyway so it doesn't really matter.

Adbot
ADBOT LOVES YOU

Profane Obituary!
May 19, 2009

This Motherfucker is Dead

Hanpan posted:

Going to show my ignorance here but whatever. I noticed when Django is querying the auth database, it selects EVERYTHING including the users password:

code:
SELECT `auth_user`.`id`, `auth_user`.`username`, `auth_user`.`first_name`, `auth_user`.`last_name`, 
`auth_user`.`email`, `auth_user`.`password`, `auth_user`.`is_staff`, `auth_user`.`is_active`, `auth_user`.
`is_superuser`, `auth_user`.`last_login`, `auth_user`.`date_joined` FROM `auth_user`
Is this a potential security risk or should I not worry about it? I'm assuming if someone has forced access to the SQL results they have access to the database anyway so it doesn't really matter.

The password is hashed and the database string is in a format like this hashtype$salt$hash.

So an example would be sha1$a1976$a36cc8cbf81742a8fb52e221aaeab48ed7f58ab4.

Hashes are not reversible (ignoring rainbow tables, which in this case would be useless unless you had a rainbow table that was precomputed for each salt, which is different for each user).

Hanpan
Dec 5, 2004

Ahh yes, I forgot about all that crazy salting.

Another question which came up today; I have a Media Manager app which I am attaching media to 'content' using the following table:

code:
class MediaAttachment(models.Model):
	media = models.ForeignKey(Media, related_name='attachment')
	content_type = models.ForeignKey(ContentType)
	object_id = models.PositiveIntegerField(db_index=True)
	object = generic.GenericForeignKey('content_type', 'object_id')
It works great, I can attach a Media object to my Entry objects just fine. The problem I have noticed is that when I delete an Entry object with attached Media, it doesn't delete the record in the MediaAttachment table. I'm ending up with a lot of redundant data in my MediaAttachment table :smith:

I want to keep the Entry model as abstract as possible, so overwriting the delete method to remove any media attachments seems a if a lame solution. Does anyone have any bright ideas as to how I could remove those redundant records when an Entry object is deleted?

Profane Obituary!
May 19, 2009

This Motherfucker is Dead

Hanpan posted:

Ahh yes, I forgot about all that crazy salting.

Another question which came up today; I have a Media Manager app which I am attaching media to 'content' using the following table:

code:
class MediaAttachment(models.Model):
	media = models.ForeignKey(Media, related_name='attachment')
	content_type = models.ForeignKey(ContentType)
	object_id = models.PositiveIntegerField(db_index=True)
	object = generic.GenericForeignKey('content_type', 'object_id')
It works great, I can attach a Media object to my Entry objects just fine. The problem I have noticed is that when I delete an Entry object with attached Media, it doesn't delete the record in the MediaAttachment table. I'm ending up with a lot of redundant data in my MediaAttachment table :smith:

I want to keep the Entry model as abstract as possible, so overwriting the delete method to remove any media attachments seems a if a lame solution. Does anyone have any bright ideas as to how I could remove those redundant records when an Entry object is deleted?

If you had the ForeignKey on Entry instead of MediaAttachment it would do that by default.

If you want to continue the way you are doing it, you could use a signal instead.

Hanpan
Dec 5, 2004

Profane Obituary! posted:

If you had the ForeignKey on Entry instead of MediaAttachment it would do that by default.

If you want to continue the way you are doing it, you could use a signal instead.

A Foreign Key won't work because you can attach more than one piece of Media..

I like the idea of using signals. Do you happen to know if there is a way to listen for a delete signal on ALL models? That way I can keep things nice and dynamic on my Media model... whenever some 'content' is deleted, check it for attachments.

Edit: I figured this out, for anyone who wants to know, you don't have to define the sender of a post delete signal. Probably a really slow method but it works well enough:

code:
post_delete.connect(MediaAttachment.objects.delete_attachment)
My method looks like this:
code:
	def delete_attachment(self, instance, *args, **kwargs):
		ctype = ContentType.objects.get_for_model(instance)
		return self.filter(content_type=ctype, object_id=instance.pk).delete()
A cron job would do this nicely, but this is at least a decent fallback :)
\/\/\/\/\/\/\/\/\/\/\/\/\/\/


Hanpan fucked around with this message at 17:29 on Feb 3, 2011

Profane Obituary!
May 19, 2009

This Motherfucker is Dead
The other option is to leave it how it was, but make a cronjob that selects all the Media attachments without an Entry, and then delete them.

king_kilr
May 25, 2007

Hanpan posted:

Ahh yes, I forgot about all that crazy salting.

Another question which came up today; I have a Media Manager app which I am attaching media to 'content' using the following table:

code:
class MediaAttachment(models.Model):
	media = models.ForeignKey(Media, related_name='attachment')
	content_type = models.ForeignKey(ContentType)
	object_id = models.PositiveIntegerField(db_index=True)
	object = generic.GenericForeignKey('content_type', 'object_id')
It works great, I can attach a Media object to my Entry objects just fine. The problem I have noticed is that when I delete an Entry object with attached Media, it doesn't delete the record in the MediaAttachment table. I'm ending up with a lot of redundant data in my MediaAttachment table :smith:

I want to keep the Entry model as abstract as possible, so overwriting the delete method to remove any media attachments seems a if a lame solution. Does anyone have any bright ideas as to how I could remove those redundant records when an Entry object is deleted?

If you put a GenericRelation on the Entry object then it will get deleted automatically: http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#reverse-generic-relations

Hanpan
Dec 5, 2004

Sorry to poo poo up this thread with my dumb rear end questions, I hope someone can help me out.

I am using the contenttype framework to create a "media attachment" app which allows me to 'attach' media (images) to objects (pretty much the same as the one I posted above). It's fairly straight forward and works quite well. I want to expand on it slightly and define each attachment further... if you imagine a blog post which has 4 images attached to it, but one of those images is a 'header image', I want to be able to differentiate that attachment.

I have done this by adding another column to my attachment table:

code:
class MediaAttachment(models.Model):
	media = models.ForeignKey(Media, related_name='attachment')
	content_type = models.ForeignKey(ContentType)
	object_id = models.PositiveIntegerField(db_index=True)
	object = generic.GenericForeignKey('content_type', 'object_id')
	taxonomy = models.CharField(max_length=100, blank=True, null=True)
Taxonomy which is blank by default can store a term which defines an attachment, so I could do something like this:

code:
MediaAttachment.objects.filter(content_type=ctype, object_id=obj.pk, taxonomy='header-image')
Functionally this works, but I feel like I am going against some kind of rule here. I'm effectively adding a further content type to a specific content type.

Is there a better way in which I could do this or should I stop worrying and deal with it?

raymond
Mar 20, 2004
I haven't used them myself, and I'm not really sure how good this would be, but how about using proxy models that hardcode the taxonomy value?

We only just upgraded from 1.0.4 so I'm not familiar with all of these newer features.

Or maybe have an "attachment_type" field with predefined choices, making it a drop-down option in forms.

raymond fucked around with this message at 00:52 on Feb 8, 2011

duck monster
Dec 15, 2004

Does anyone know the correct syntax for putting data into a GeoDjango pointField

Heres my model:
code:
class ContactCard(models.Model):
    ...bunch of stuff...
    mpoly = models.MultiPolygonField(null=True,blank=True,verbose_name='Servicing region')
    coordinates = models.PointField(null=True,blank=True,verbose_name='location')
    objects = models.GeoManager()
The problem is , I have no loving idea, and its just not documented how to put a long and lat into a pointfield.

If I put a Point(lng,lat) in, I get:

TypeError: cannot set ContactCard GeometryProxy with value of type: <class 'geopy.point.Point'>

If I try a 'POINT(23.23345345,1.234234234)' type string, it comes back wondering what I'm smoking.

The GeoDjango documentation is atrocious :(


e: Just worked it out. Namespace clash between Geopy + GeoDjango. Ugh....

king_kilr
May 25, 2007
If you think there's a problem with the docs, please please please file bugs on them, including just needing more details.

Captain Capacitor
Jan 21, 2008

The code you say?

king_kilr posted:

If you think there's a problem with the docs, please please please file bugs on them, including just needing more details.

Never worked for Twisted :crossarms:

I love the framework, I really do. But when your documentation says one thing, your Epydoc says another and the code does something else entirely, it's a problem.

king_kilr
May 25, 2007

Captain Capacitor posted:

Never worked for Twisted :crossarms:

I love the framework, I really do. But when your documentation says one thing, your Epydoc says another and the code does something else entirely, it's a problem.

Yes it is. We take our documentation seriously.

duck monster
Dec 15, 2004

king_kilr posted:

If you think there's a problem with the docs, please please please file bugs on them, including just needing more details.

What am I going to say?

Bug: Your documentation is poo poo. Stop being poo poo.

...then deal with a bunch of manchild spergelords who are angry because the bug was already filed a year ago and marked "Wontfix"??

Yeah I'm 100% over open source bug trackers, sorry dude. Nothing, absolutely nothing, brings out the aspergic nature of the geek like bug-trackers can do.

e:

Seriously though, Django's docs are generally great. But the geodjango docs have some giant holes around field definitions, and what those field types mean and how to access them. Maybe those details ARE in there, but damned if I can find them, cos they aint in the logical place. Its important to remember that whilst most of us approach django from either a web developer or coders knowledge of things, we are approaching GIS from absolute newbie-cluelessness. Lots of hand holding is needed by docs here and NO prior knowledge of GIS ought be assumed.

duck monster fucked around with this message at 03:12 on Feb 15, 2011

epswing
Nov 4, 2003

Soiled Meat

duck monster posted:

What am I going to say?

Bug: Your documentation is poo poo. Stop being poo poo.

...then deal with a bunch of manchild spergelords who are angry because the bug was already filed a year ago and marked "Wontfix"??

Ok spergelord, why don't you just say "documentation is unclear because of reason X, Y, Z, can you please provide more detail!"

From reading a single post I'm willing to bet that the responses you've gotten have to do with your manchild bug reports which consist of nothing but "your documentation is poo poo."

epswing fucked around with this message at 06:04 on Feb 15, 2011

Yay
Aug 4, 2007

duck monster posted:

Seriously though, Django's docs are generally great. But the geodjango docs have some giant holes around field definitions, and what those field types mean and how to access them. Maybe those details ARE in there, but damned if I can find them, cos they aint in the logical place.
If you look at the Trac, 2400~ of 15500~ tickets are documentation related. That's about a sixth of all of them? Admittedly, lots of those will be duplicates, but Django's documentation is definitely improved by people submitting tickets, because stuff gets missed. And I'd imagine that if the GeoDjango docs are lacking in some respect, its because the rest of the framework has a lot more eyes looking at it, because it's all common requirements.

In short, please do submit a ticket. It's not hard, and I've rarely (never?) seen any childishness in the tickets. I imagine that's reserved for the mailing lists :)

king_kilr posted:

Yes it is. We take our documentation seriously.
They really do.

Hanpan
Dec 5, 2004

Hopefully some kind soul can check this code over for me. I want to create a thumbnail of an uploaded image. Annoyingly, since the file doesn't exist on the server until after the save method is called, I can't see any around doing this using the post_save signal. I am aware you can generate images by storing the image in memory before it's saved, but I don't really want to rape my servers resources every time I upload an image.

Here is the code I am using:
code:
class Media(models.Model):
	"""
	Media model - Represents images, music, video etc
	"""
	id = models.AutoField(primary_key=True)
	file = models.FileField(upload_to='uploads/%m-%Y/')
	thumbnail = models.ImageField(upload_to='uploads/%m-%Y/', blank=True, null=True)
	title = models.CharField(max_length=100, blank=True, null=True)
	alt = models.CharField(max_length=100, blank=True, null=True)
	caption = models.CharField(max_length=100, blank=True, null=True)
	desciption = models.TextField(blank=True)
	content_type = models.CharField(max_length=100, blank=False, null=False)
	created = models.DateTimeField(auto_now_add=True, editable=False)
	
	objects = MediaManager()
		
	def __unicode__(self):
		return u'%s' % self.id
		
	class Meta(object):
		verbose_name_plural = "Media"
		ordering = ['-created']
			
	def upload_media(self, data, params=None):
		self.file = data['file']
		self.content_type = data['file'].content_type
		self.save()

	def clean(self, *args, **kwargs):
		super(Media, self).clean(*args, **kwargs)
		if not valid_filetype(self.file.path):			
			raise ValidationError(_('Unrecognized file extension, allowed types: %s' \
						% u''.join([k+' ' for k in MEDIA_ALLOWED_TYPES])))

## THUMBNAIL MANAGEMENT ##	
@receiver(post_save, sender=Media, dispatch_uid="media_create_thumb")
def create_media_thumbnail(sender, **kwargs):
	if kwargs['created']:
		m = kwargs['instance']
		m.thumbnail = generate_thumbnail(m.file)
		m.save()


I'm going to extend this class further to allow for different kinds of media, incase you are wondering why I am using a FileField for the file attribute. Obviously I won't create thumbnails for anything other than images.

It works ok, but the reliance on the post_save signal worries me a bit as I only ever want to create a thumbnail the first time the instance is saved, and never again.. I am hoping the 'created' kwarg will prevent that?

I'm also hitting the database twice, once when the model is saved and again once the thumbnail has been generated. Considering I may also want to post process the uploaded image (resizing etc), that is going to take it up to 3 queries. I'm hopeful there is a way to do all that post processing before anything is actually saved to the database?

Any insights would be appreciated, I like to keep my code as pythonic as possible :)

Profane Obituary!
May 19, 2009

This Motherfucker is Dead
I'd just use sorl, this is a solved problem. Unless you are wanting to do something special that sorl can't do?

http://thumbnail.sorl.net/

Hanpan
Dec 5, 2004

Profane Obituary! posted:

I'd just use sorl, this is a solved problem. Unless you are wanting to do something special that sorl can't do?

http://thumbnail.sorl.net/

Yea, a lot of people seem to suggest using sorl. I have nothing against it, but in this instance, I really want to do it myself because not only will I learn how but I also don't need half of the functionality sorl offers :v:

I have a lot more control this way too, as I have also created some custom fields and admin widgets which integrate nicely with my media module.

Profane Obituary!
May 19, 2009

This Motherfucker is Dead
In that case, why not look at sorl to see how it does it? I would assume with the number of people using sorl, it's method probably isn't terrible.

Though i don't really see a problem using the post_save hook. The other option is to make m.thumbnail a method instead of a real field, and generate it the first time the image is requested.

leterip
Aug 25, 2004
Is there a reason you did
code:
u''.join([k+' ' for k in MEDIA_ALLOWED_TYPES])
instead of
code:
u' '.join(MEDIA_ALLOWED_TYPES)

Hanpan
Dec 5, 2004

Because it is a tuple.
code:
MEDIA_ALLOWED_TYPES = ('jpg', 'jpeg', 'gif')
I went with your suggestion of creating a thumbnail property, here is how it looks if anyone reads this and wonders:

code:
	@property
	def thumbnail(self):
		if hasattr(self, '_thumb'):
			return self._thumb
		else:
			setattr(self, '_thumb', get_thumbnail(self.file))
			return self._thumb
\/\/\/\/\/ This is why I love python :v:

Hanpan fucked around with this message at 11:09 on Feb 17, 2011

leterip
Aug 25, 2004

Hanpan posted:

Because it is a tuple.
code:
>>> ' '.join(('its', 'still', 'an', 'iterable'))
'its still an iterable'
Just in case you don't believe that,
code:
>>> MEDIA_ALLOWED_TYPES = ('jpg', 'jpeg', 'gif')
>>> ' '.join(MEDIA_ALLOWED_TYPES)
'jpg jpeg gif'

sink
Sep 10, 2005

gerby gerb gerb in my mouf
Is there something like htmltidy that works well for markup with template tags? I've got a ton of lovely templates that I would like to prettify, but htmltidy joins all lines of my Django template directives.

latexenthusiast
Apr 22, 2008
First off, I haven't read the whole thread, so I'm sorry if these issues have already been addressed elsewhere in one form or another. Then again, I'm such a Django newbie (and Python newbie in general, really), that most people wouldn't be asking these questions in the first place.

Also, I'm aware that there are Django-powered blogging applications out there and in some ways I'm trying to reinvent the wheel. Sure, my will be made of wood and rawhide in the time of alloys and carbon fiber, but sometimes one just needs to learn by doing.

  • Let's say I were making a blog application, and there were a bunch of ways I wanted to be able to display the data (by date, by author, by tag, etc.). One way I could imagine doing this is with view function called post that takes a bunch of arguments that lead to a specific QuerySet and then pass this all to one template file (post.html), so there's consistency in the way blog posts are displayed. The other way I could think of doing it is to have separate view fucntions (by_date, by_author, by_tag, etc.) that all do their own QuerySet and maybe have their own template, but for the display of the actual post itself, I just include single-post.html or something like that, so again the posts are displayed the same way.

    The former seems slightly more DRY to me, but at the expense of having one relatively complicated view function as opposed to bunch of little ones, so I think in that sense the latter approach is superior.

  • I'd really like to have pretty URLs. For example, for an individual blog post, say I had an BlogPost object whose title is "«Je parle le français (un peu)»" written on May 29th, 2011. I'd like the url to be http://www.mysite.com/posts/2011/05/29/je-parle-le-francais-un-peu/.

    My solution at the moment feels a little fragile. Let's first assume that I have a function urlify that will transform the string "«Je parle le français (un peu)»" into "je-parle-le-francais-un-peu" (i.e. everything goes to lowercase, spaces are replaced with dashes, punctuation is dropped, accented characters go to ASCII-looking equivalents if available, otherwise are dropped)--basically, it makes strings URL-friendly. Here's a simplified version of how I have things set up (ignore any typos, the real code is actually working right now):
    code:
    ### models.py ###
    (usual imports)
    from mysite.scripts.urlify import urlify
    
    class BlogPost(models.Model):
        title = models.CharField(max_length=50)
        timestamp = models.DateTimeField()
        body = models.TextField()
        url = models.CharField(max_length=100, editable=False)
        
        def get_absolute_url(self):
            return r'/posts/%s/%s' % (self.timestamp.strftime(r'%Y/%m/%d'), urlify(self.title))
        
        def save(self, *args, **kwargs):
            # need to leave off front slash due to incompatibilities between urls.py and get_absolute_url() method
            self.url = self.get_absolute_url()[1:]
            is_by_staff = self.author.is_staff
            super(BlogPost, self).save(*args, **kwargs)
    
    ### urls.py ###
    urlpatterns += (r'^(?P<abs_url>posts/\d{4}/\d{2}/\d{2}/[a-z0-9].*)/$', post)
    
    ### views.py ###
    def post(request, abs_url):
        entries = BlogPosts.objects.filter(url = abs_url)
        t = loader.get_template('post.html')
        c = Context({ 'entries': entries })
        return HttpResponse(t.render(c))
    
    So this solution has a couple of things going for it: 1) it's working right now, 2) the URLs are pretty, and 3) the URL field is automatically generated on save, so if I have non-programmy friends/staff members who want to make posts, they don't have to worry about making a nice url.

    It kind of sucks, though, because I may want to change get_absolute_url at some point, and that would mean all the BlogPost objects need to be re-saved, so that sucks. (Is there a way I can do a mass re-save?) It's probably bad in some other ways, too.

    I'm pretty sure I can't generate a QuerySet from the urlify'd URL that would always find the BlogPost I'm after due to the information loss from the urlify function.

    Looking around the web, I see that The Onion's website does something that in Django would look like:
    code:
    urlpatterns += (r'^articles/[a-z].*,(?P<article_id>\d+)/$', article_display)
    
    where the [a-z].* is the article title in a format similar to how I want to urlify my BlogPost.titles, but I feel like just displaying BlogPost.id is a little inelegant, and it seems like lots of places don't do that. Do they just have a manually-created BlogPost.url field so then you'd have
    code:
    class BlogPost(models.Model):
        ...
        def get_absolute_url(self):
            return 'posts/%s/%s' % (self.timestamp.strftime('%Y/%m/%d'), self.url)
    
    or something like that instead of my version?

  • Here's one that's probably a bit easier: what's the best way to get the title tag text to be all uniform and nice i.e. if I want to quickly change between a pipe separator and an em dash, how would I do go about doing that? I'm thinking this is something that should be confined to views.py somehow, but things are starting to creep into my templates, and that seems very un-DRY.

  • Finally, this one isn't for a blog, but something I want to do in the future. Let's say you could either work in a text box or upload a file. Would it then be reasonable to have
    code:
    class Superclass(models.Model):
        common_attribute1 = models.Field()
        common_attribute2 = models.Field()
    
    class Subclass_With_TextField(Superclass):
        body = models.TextField()
    
    class Subclass_With_FileField(Superclass):
        body = models.FileField()
    
    or is there a better way to do this?

Yay
Aug 4, 2007

latexenthusiast posted:

My solution at the moment feels a little fragile. Let's first assume that I have a function urlify that will transform the string "«Je parle le français (un peu)»" into "je-parle-le-francais-un-peu" (i.e. everything goes to lowercase, spaces are replaced with dashes, punctuation is dropped, accented characters go to ASCII-looking equivalents if available, otherwise are dropped)--basically, it makes strings URL-friendly.

This is a common enough case that it's handled for you, using models.SlugField and the slugify templatetag (the latter of which is just a python function you can import.

latexenthusiast posted:

It kind of sucks, though, because I may want to change get_absolute_url at some point, and that would mean all the BlogPost objects need to be re-saved, so that sucks. (Is there a way I can do a mass re-save?) It's probably bad in some other ways, too.
get_absolute_url can be improved by using models.permalink as a method decorator. This allows you to call a named URL (or the view name ...) and pass parameters in, which realistically means you only need to change your urls.py and get_absolute_url definitions to change URI structure (of course, changing all the slugs would require resaving, yes).

latexenthusiast posted:

The former seems slightly more DRY to me, but at the expense of having one relatively complicated view function as opposed to bunch of little ones, so I think in that sense the latter approach is superior.
There's no reason your view callable has to do all the legwork, if that's what you're worried about; ultimately it just has to return an HttpResponse, so utility functions can be used to marshall data.

Personally, I'd have different view functions for the distinct options in filtering/displaying data, if only because it makes it much easier to add in additional features to one view without having to worry about the rest of the logic. Class Based Views, when they land (1.3) will, I think, make this kind of grouping easier, however.

Yay fucked around with this message at 21:04 on Feb 19, 2011

Hanpan
Dec 5, 2004

Just to add, I find using the {% url %} template tag pretty useful as it means I don't have to use get_absolute_url and worry about keeping it updated.

Profane Obituary!
May 19, 2009

This Motherfucker is Dead

Yay posted:

Personally, I'd have different view functions for the distinct options in filtering/displaying data, if only because it makes it much easier to add in additional features to one view without having to worry about the rest of the logic. Class Based Views, when they land (1.3) will, I think, make this kind of grouping easier, however.

There's nothing stopping you from using class based views now either.

Mulozon Empuri
Jan 23, 2006

What do you guys do about multilingual urls?

I'd like to be able to translate my urls so that /en/woop/ can be translated into /da/whoop and hit the same view on the same site.

I've found an app that tries to handle this problem transurlvania, but according to an open issue the app isnt threadsafe.

multigl
Nov 22, 2005

"Who's cool and has two thumbs? This guy!"
I'm having an awful time getting django-piston working with apache/mod_wsgi on windows.

I have literally 24 hours before go live so I can't exactly switch REST frameworks or off of windows.

I had to edit piston.utils.Mimer.content_type to:

code:
def content_type(self):
	type_formencoded = "application/x-www-form-urlencoded"
	ctype = self.request.META.get('CONTENT_TYPE', type_formencoded)
	if ctype.strip().lower().find(type_formencoded) >= 0:
		return None
	return ctype
and do an stupid CSRF Wrapper to disable disable CSRF on my handler just to get it "working"

Now, anything I have that returns piston.utils.rc.ANYTHING it throughs a big dumb error.

For example:

return rc.CREATED

will give me an Apache 500 error, not a django error:
code:
 mod_wsgi (pid=3500): Exception occurred processing WSGI script 'D:/srv/vhosts/titan/mat/public/run.wsgi'.
 Traceback (most recent call last):
  File "C:\\Program Files (x86)\\Python2.7\\lib\\site-packages\\django\\http\\__init__.py", line 408, in next
     chunk = self._iterator.next()
   File "D:\\libs\\piston\\emitters.py", line 298, in stream_render
     yield self.render(request)
   File "D:\\libs\\piston\\emitters.py", line 352, in render
     self._to_xml(xml, self.construct())
   File "D:\\libs\\piston\\emitters.py", line 277, in construct
     return _any(self.data, self.fields)
   File "D:\\libs\\piston\\emitters.py", line 101, in _any
     raise thing
 TypeError: exceptions must be old-style classes or derived from BaseException, not HttpResponse
If I change the block of code in question to:
code:
def _any(thing, fields=()):
            elif isinstance(thing, HttpResponse):
                return thing
            ...
from:
code:
def _any(thing, fields=()):
            elif isinstance(thing, HttpResponse):
                raise HttpStatusCode(thing)
            ...
it "works" but I don't get accurate http status codes (which I need :()

edit: gently caress I hate piston so goddamned much. I'm going to replace it the second I can. Turns out it pistons streaming output clobbers the whole thing and I cannot raise HttpResponses because piston is trying to stream it, not return it.

multigl fucked around with this message at 06:50 on Feb 22, 2011

epswing
Nov 4, 2003

Soiled Meat
If I override a ModelForm's clean(self) method, I would typically call the parent's clean(self) method, right?

What's weird is that I'm not calling the parent's clean(self) method, and validation on fields I'm not handling in my clean(self) still seems to be happening...

king_kilr
May 25, 2007
That stuff isn't called by clean, it's called by full_clean (or maybe _full_clean).

nbv4
Aug 21, 2002

by Duchess Gummybuns
I need some advice of cultivating a testing suite. At work we have a fairly large django project, which has recently (over the past 2 months or so) gone from 0% coverage, to about 60% coverage. The problem is that the guys that are in charge of the QA process are, in my opinion, going about it entirely wrong. These guys come from java, where I guess mocking is a common strategy to creating tests. The problem is that I don't really think the mocking strategy is really best for the way django's testing framework is set up. For instance, we have a MockQuerySet object they we have to monkey patch in before using any models that moick out save() and a bunch of other stuff. We also have a subclassed TestCase class that does an unholy amount of stuff. Basicvally, each and every test is pretty much 50% mocking, then the other 50% is actual test code. The way inporting works in python (and the way django works makes it much worse) means that you have to pretty much mock out an object once each time it's imported if you want to completely mock it. So our test code gets really complex really fast.

There is this bit of code I wrote which works by generating a random number, and then doing something with that random number. My test just iterated over that bit of code until I got the result I was looking for (i'm simplifying big time). When the QA tester saw my test, he rejected it, saying that all tests have to be deterministic, and that there is a 0.00237% change that the test will fail even though the code is right, so he made me mock out the call to random.randint(), which was waaaay harder than it sounds, because I had to restore that mock before random.randint() was called later on. It was a big mess in my opinion, but the people in charge seem to think this is the only way to go about it.

I don't really have a lot experience with django testing, or testing in general for that matter. Is this a legitimate strategy for doing test? Literally, every single one of our tests has at least 10 or so lines of mock code at the begining. Is this typical? My gut reaction is that since the django tests documentation doesn't include any mocking tools, or even really mention mocking at all, that this mocking fetish we have is wrong. What do you all think?

Yay
Aug 4, 2007
Since Django has reasonably recently been migrating away from doctests to proper unittests, there's a fairly comprehensive test suite included in the package which probably demonstrates a recommendable method of doing so. In my experience looking at them, an awful lot of the tests are small, or just bundles of assert tests. Not the monolithic things you're describing.

IMO, tests should be as concise as possible, because if you can't write bug-free production code, why risk writing buggy tests? short and sweet means less opportunity to go wrong, usually.

ufarn
May 30, 2009
Are there any Django tutorials for creating a forum? I want to learn Django, but I need to apply it to something interesting and relevant.

I know it can't be that different than a general CMS, but it'd probably make for the most productive investment of my time.

Stabby McDamage
Dec 11, 2005

Doctor Rope

ufarn posted:

Are there any Django tutorials for creating a forum? I want to learn Django, but I need to apply it to something interesting and relevant.

I know it can't be that different than a general CMS, but it'd probably make for the most productive investment of my time.

I don't know of any tutorials, but if you can design the data model for it, you can likely code the rest, since the queries and views will come naturally (view forum list, view topic list, view thread).

ufarn
May 30, 2009

Stabby McDamage posted:

I don't know of any tutorials, but if you can design the data model for it, you can likely code the rest, since the queries and views will come naturally (view forum list, view topic list, view thread).
I'm fairly confident about pulling it off like any other dynamic system. It's just that it'd be more of a DYI gig rather than following a guide and being more effective with my time and concentration.

(And I'm also so new to the framework that I don't know any of the basic apps there are, but maybe that's not pivotal when working in Django.)

multigl
Nov 22, 2005

"Who's cool and has two thumbs? This guy!"

ufarn posted:

I'm fairly confident about pulling it off like any other dynamic system. It's just that it'd be more of a DYI gig rather than following a guide and being more effective with my time and concentration.

(And I'm also so new to the framework that I don't know any of the basic apps there are, but maybe that's not pivotal when working in Django.)

build a blog. everyone build a blog. ten million django blogs.

ufarn
May 30, 2009

multigl posted:

build a blog. everyone build a blog. ten million django blogs.
NO. I refuse to build a goddamn blog. I already use ExpressionEngine anyway.

Adbot
ADBOT LOVES YOU

Yay
Aug 4, 2007

ufarn posted:

NO. I refuse to build a goddamn blog.
But much of the basics are the same (date oriented, facted content), only posts don't go in categories, they go in threads, and then the threads go in categories. Throw in multiple users, and you've got the rudimentary beginnings of a simple forum. You can probably get that far with the ORM and generic views.

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