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
LOLLERZ
Dec 9, 2003
ASK ME ABOUT SPAMMING THE REPORT FORUM TO PROTECT ~MY WIFE'S~ OKCUPID PERSONALS ANALYSIS SA-MART THREAD. DO IT. ALL THE TIME. CONSTANTLY. IF SHE DOESN'T HAVE THE THREAD, SHE'LL WANT TO TALK TO ME!
I am trying to detect duplicate uploaded images. I have a method that generates a signature for each image that is uploaded and I want to verify it against all the other signatures I have collected.

When is the best time to do this? I don't really think the model's .save() method is the right time, since that code would get called for every successive save, but images only get uploaded once.

I'm also not really sure on how to deal with validation from the user's perspective. If anyone has any insight on that, I would love to hear it.

Adbot
ADBOT LOVES YOU

king_kilr
May 25, 2007
Use django.forms. It has everything you'll need. Start with the docs: http://docs.djangoproject.com/en/dev/#forms

king_kilr
May 25, 2007
Security Announcement: http://code.djangoproject.com/changeset/11351 see successive commits for patches against 1.0.2 and .96.x. Releases will be forthcoming.

Edit: Corresponding blog post: http://www.djangoproject.com/weblog/2009/jul/28/security/ 1.1 release do within hours.

king_kilr fucked around with this message at 05:55 on Jul 29, 2009

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
http://docs.djangoproject.com/en/dev/releases/1.1/
:woop:

ATLbeer
Sep 26, 2004
Über nerd

mmm... Proxy models look quite useful

SlightlyMadman
Jan 14, 2005

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

code:
import datetime
from django.db import models
from django.contrib.auth.models import User

class Publication(models.Model):
    label = models.CharField(max_length=255)
    pages = models.ManyToManyField(Page, through='Link')

class Site(models.Model):
    label = models.CharField(max_length=255)

class Page(models.Model):
    site = models.ForeignKey(Site)
    url = models.CharField(max_length=255)
    get_vars = models.CharField(max_length=255)
    label = models.CharField(max_length=255)
    pub_date = models.DateTimeField('date published')

class Link(models.Model):
    publication = models.ForeignKey(Publication)
    page = models.ForeignKey(Page)
    user = models.ForeignKey(User)
Is the Link object done correctly? It's really a three-way many-to-many between Publication, Page, and User, but there doesn't seem to really be an appropriate way to model this.

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.

SlightlyMadman
Jan 14, 2005

Actually, the link itself is unique to the user. A user generates a Link, which is a specific page, targeted at a specific publication. Think of a link more as an instance of a page, but for a specific user and publication.

Let's say my page is "foo.html" and my publication is "MySite.com". There is already a many-to-many relationship between them, but further each user in my system gets their very own link for the combination of foo.html and MySite.com.

devilmouse
Mar 26, 2004

It's just like real life.
Alright - bear with me, this is driving me up the wall. I'm working on my first django project of substance and I'm trying to set up my code in a way that doesn't annoy me too badly.

I'm struggling with the way django seems to require the naming/location of the models. They seem to either have to reside at the top level of your app in models.py or in a subdirectory models/. Django seems bizarrely focused on having the string "models" involved and I can't figure out a way around it.

I'm trying to locate the model for a given class inside said class and not have to have a second class exist solely to wrap up the model. I blame the last 2 years I've spent in java + hibernate for this...

I'm not sure that makes sense, but what I'm trying for looks like this:

code:
What works:

project/
        game/
                system1/
                        class_a.py
                        class_b.py
                        models.py
                system2/
                        class_c.py
                        class_d.py
                        models.py
        views/

What also works:

project/
        game/
                system1/
                        class_a.py
                        class_b.py
                        models/
                                model_a.py
                                model_b.py
                system2/
                        class_c.py
                        class_d.py
                        models/
                                model_c.py
                                model_d.py
        views/

What I want and can't seem to get to work:

project/
        game/
                system1/
                        class_a_with_model_a.py
                        class_b_with_model_b.py
                system2/
                        class_c_with_model_c.py
                        class_d_with_model_d.py
        views/
The third option is completely eluding me. Am I SOL here? I've tried the meta app_label thing to no avail, but I have this sneaking suspicion that I'm just missing some __init__.py finesse. Surely someone out there wanted to do this before me for one reason or another!

nbv4
Aug 21, 2002

by Duchess Gummybuns
This is how django wants you to do it:
code:
project/
        system1/
            class_a.py
            class_b.py
            models.py
            views.py
            __init__.py
        system2/
            class_c.py
            class_d.py
            models.py
            views.py
            __init__.py
         urls.py
         settings.py
Within a project folder, django expects a bunch of modules called "apps" which contain all the views/models/admin definitions for a certain "piece" of your application.

devilmouse
Mar 26, 2004

It's just like real life.

nbv4 posted:

This is how django wants you to do it:

I realize that's how django wants it done, but not how I want to do it. :colbert:

My deeply ingrained OO-tendencies and code organizations are in a fight with django!

SlightlyMadman
Jan 14, 2005

devilmouse posted:

I realize that's how django wants it done, but not how I want to do it. :colbert:

My deeply ingrained OO-tendencies and code organizations are in a fight with django!

Is the problem just that you want to put each class of your model in its own file, instead of putting them all in models.py? If you don't like the django/python way, then there's plenty of java application frameworks out there you're welcome to use instead.

If you're going to use django though, you'd better do it the django way or it's going to hurt. I bet you capitalize your method names too, don't you?

To make a horribly inappropriate analogy, think of it like taking it in the rear end. Sure you may be used to vaginal sex and want to follow the same procedures, but if you insist on not using lube it's going to hurt.

devilmouse
Mar 26, 2004

It's just like real life.

SlightlyMadman posted:

To make a horribly inappropriate analogy, think of it like taking it in the rear end. Sure you may be used to vaginal sex and want to follow the same procedures, but if you insist on not using lube it's going to hurt.

An excellent analogy!

It's mostly me fighting with a new language/framework and if it's the accepted way, I'll comply with it. My last real web coding was done with perl in CGI, so things are a bit different now!

It's for work so I don't have the option of using anything else. I guess I'll just suck it up and learn the django way. Thanks for being blunt about it! It makes sense, I just didn't want to like it.

For the record, no, in python/perl, I use all lower-case for function names, separated with underscores! I'm not some sort of heathen, gosh.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
http://www.youtube.com/watch?v=A-S0tqpPga4 you should watch this, devilmouse. Good explanation of the django philosophy and how it should effect your design.

bitprophet
Jul 22, 2004
Taco Defender

SlightlyMadman posted:

If you're going to use django though, you'd better do it the django way or it's going to hurt. I bet you capitalize your method names too, don't you?

Er, what? That's BS. As long as he imports his model classes into models.py, Django won't give a poo poo what files they're originally defined in. It's all just Python.

king_kilr
May 25, 2007

bitprophet posted:

Er, what? That's BS. As long as he imports his model classes into models.py, Django won't give a poo poo what files they're originally defined in. It's all just Python.

He'll need to define app_label in the inner Meta class as well, but yeah.

SlightlyMadman
Jan 14, 2005

bitprophet posted:

Er, what? That's BS. As long as he imports his model classes into models.py, Django won't give a poo poo what files they're originally defined in. It's all just Python.

Well I was obviously being somewhat sarcastic, but I am a firm believer in using the common formatting standards for the language at hand. Of course the compiler isn't going to care how you format poo poo, just as it wouldn't care if you name all your variables x, xx, xxx, etc. Your code's going to suck and be unmaintainable though. Chances are, a programmer looking at python code is going to be most comfortable with python's common standards. If you use java standards, you're far more likely to confuse them. You'll also find yourself doing unnecessary translation when reusing code snippets, and you'll likewise be confused when editing other peoples' code.

jupo
Jun 12, 2007

Time flies like an arrow, fruit flies like a banana.
As mentioned above it seems like the issue here is entirely the java-esque desire to use one file per class. This makes sense when the language dictates that you write copious amounts of boilerplate code but in python when you can get as much done with a tenth of the amount of code it just doesn't make sense.

Have a read of this article that goes into this in much more detail. I'm not sure if this is the original one that came to mind but it was the first google result so I assume it is.

devilmouse
Mar 26, 2004

It's just like real life.
Thanks for the links, guys. Old habits die hard and so forth, but at least I don't feel so alone anymore. I kept trying to explain to the main python guy at work what I wanted to do and he just kept asking "why would you want to do that?!?", failing to understand where I was coming from.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
I just noticed something that is missing from the OP. A list of good web hosts!

I just started using http://www.webfaction.com/ and after dicking around with other hosts these guys are a dream to work with. Being able to SSH into the my shared hosting and configure my own apache server is amazing!

Before that I tried using A small orange, and it didn't work out too well.

duck monster
Dec 15, 2004

devilmouse posted:

I realize that's how django wants it done, but not how I want to do it. :colbert:

My deeply ingrained OO-tendencies and code organizations are in a fight with django!

I hear you man. I adore django, but occasionally I want to start punchups with it for letting you put functions outside of classes. I grew up on smalltalk (hence my Obj C love) so Im a bit of an OO zealot.

duck monster
Dec 15, 2004

MEAT TREAT posted:

I just noticed something that is missing from the OP. A list of good web hosts!

I just started using http://www.webfaction.com/ and after dicking around with other hosts these guys are a dream to work with. Being able to SSH into the my shared hosting and configure my own apache server is amazing!

Before that I tried using A small orange, and it didn't work out too well.

Hey thats a pretty neat thing. I'm still a slicehost guy, but for smaller projects thats a pretty good deal.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

duck monster posted:

I hear you man. I adore django, but occasionally I want to start punchups with it for letting you put functions outside of classes. I grew up on smalltalk (hence my Obj C love) so Im a bit of an OO zealot.

First class functions are the loving balls - and it's a python thing - not Django :smug:

duck monster
Dec 15, 2004

If I wanted first class functions I woulda stuck with scheme.

*thats* how you do functions right.

spencer for hire
Jan 27, 2006

we just want to dance here, someone stole the stage
they call us irresponsible, write us off the page
Newbie question about forms.

I followed the tutorial on djangoproject.com and have a Poll model and a Choice model. I'd like to create a form where a user can create a poll and a few choices in one go like I can in the admin view. What is a good way to accomplish this?

I looked through the documentation and just started confusing myself with save_m2m() and inlineformsets and I don't know what else.

king_kilr
May 25, 2007

spencer for hire posted:

Newbie question about forms.

I followed the tutorial on djangoproject.com and have a Poll model and a Choice model. I'd like to create a form where a user can create a poll and a few choices in one go like I can in the admin view. What is a good way to accomplish this?

I looked through the documentation and just started confusing myself with save_m2m() and inlineformsets and I don't know what else.

You're going to be wanting to look at ModelForms, and inlineformest_factory.

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...
What's people favourite choice / method for creating multi-stage forms in Django? I'd like a solution where on the one page a user can click forwards (and backwards) through a multipart form.

deimos
Nov 30, 2006

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

outlier posted:

What's people favourite choice / method for creating multi-stage forms in Django? I'd like a solution where on the one page a user can click forwards (and backwards) through a multipart form.

Do you mean like a Form Wizard?

nonathlon
Jul 9, 2004
And yet, somehow, now it's my fault ...

deimos posted:

Do you mean like a Form Wizard?

I was looking for something that kept the form on a single page, but that's a start. (Apologies if this feature is incredibly well known, but I'm relatively new to Django.)

reksio
Feb 5, 2007
I have a question about an application I'm trying to setup right now on my server. It's a great questionnaire application I found called seantis-questionnaire, and is the best such application I've found that is written in Django. You can check out the github repository at http://github.com/rmt/seantis-questionnaire/tree/master. You can also check out an example of this application at http://questionnaire.corporatism.org/.

I have everything setup on my server, and I can get the questionnaire to pop-up and edit it without any problems. The problem I am experiencing is not being able to access some of the built in management features of this application, such as CSV export and the sending of e-mail invitations.

The urls.py file looks like this
code:
    url(r'^$',
            questionnaire, name='questionnaire_noargs'),
    url(r'^(?P<runcode>[^/]+)/(?P<qs>\d+)/$',
            questionnaire, name='questionset'),
    url(r'^(?P<runcode>[^/]+)/',
            questionnaire, name='questionnaire'),
    url(r'^csv/\d+/',
            export_csv, name='export_csv')
and there is another file as well called test-urls.py with the following code
code:
    url(r'^q/(?P<runcode>[^/]+)/(?P<qs>\d+)/$',
        'questionnaire.views.questionnaire', name='questionset'),
    url(r'^q/([^/]+)/',
        'questionnaire.views.questionnaire', name='questionset'),
    url(r'^q/manage/csv/(\d+)/',
        'questionnaire.views.export_csv'),
    url(r'^q/manage/sendemail/(\d+)/$',
        'questionnaire.views.send_email'),
    url(r'^q/manage/manage/sendemails/$',
        'questionnaire.views.send_emails'),
I am able to access my survey as /q/secondtrypsych/ but I cannot for the life of me figure out how to access the CSV and e-mail tools. I've tried every combination of /q/manage/csv/secondtrypsych but all I get is a redirect to my index page.

If anybody here has any ideas, I would appreciate it immensely. If you need more information and would be willing to help me figure this out, then you can e-mail me at discopoland (at) gmail.com since I don't have PMs and let me know what you'd request in return. This is for a school project and I've got a kid on the way so I'm not flush with cash but will see what I can do.

entr0py
Jan 31, 2004


A real-life robot.
I have a question about developing a Django application that interacts with a REST API. I posted a question on Stack Overflow (http://stackoverflow.com/questions/1225701/well-behaving-restful-client-interactions) first, but I didn't do a very good job of explaining my problem (though I did get a couple good replies).

Here's the premise:

I have a REST API that tries to adhere to HATEOAS and REST architectural rules. I want to design a Django application to consume that API (adhering to these rules as well), but I want all the application logic and user interactivity (the frontend) to be contained within the Django application itself. Since I can't seem to adequately describe the problem (likely a sign of poor design decisions to start, but let's ignore that for now), an example is easiest (JSON responses for simplicity).

code:
// get available resources through single URI entry-point
GET api.example.com HTTP/1.1
{
  'services': [
    {
      'name': 'Widget Factory'
      'href': 'http://api.example.com/widgets/'
    },
    {
      'name': 'Neckbeard Generator'
      'href': 'http://api.example.com/neckbeards/'
    }
  ]
}

// render response to user for navigating API
{% for service in services %}
    <a href="{% url testapp.views.getservice {{ service.name }} %}">{{ service.name }}</a>
{% endfor %}
This is the first problem: the server returns content describing the services and providing links to traverse them -- I cannot have users follow these links directly as I want the Django application to perform the API interactions. I can remain RESTful here by using performing another request as above and using the service name (passed to the view) to discover the URI for the resource and then continue to traverse the API. The problem gets worse though when I'm dealing with things like a resource collection (eg. a list of a widgets).

code:
// GET operation on the resource returns a list of widgets
GET api.example.com/widgets/ HTTP/1.1
{
  'widgets': [
    {
      'id': 1
      'name': 'A beautiful anime'
      'href': 'http://api.example.com/widgets/1'
    },
    {
      'id': 2
      'name': 'spam ham eggs'
      'href': 'http://api.example.com/widgets/2'
    }
    ...
  ]
}

// let the users view the widgets
{% for widgets in widgets %}
    <a href="{% url testapp.views.getitem {{service_name}}, {{widget.id}} %}">{{ widget.name }}</a>
{% endfor %}
This just bothers me because it seems like it should be extremely simple and missed a large-shiny detail somewhere along the path. Alternatively, this is trivial to implement when using URI construction or any various other means of API consumption that violates principles in Fielding's dissertation, but I would really like to try and do this correctly. I have a few really hack-ish ways of accomplishing this currently (glimpsed above with the view methods you can see being invoked and the parameters passed), but I think I've really headed in the wrong direction.

Thanks in advance for any help.

entr0py fucked around with this message at 04:00 on Aug 5, 2009

LOLLERZ
Dec 9, 2003
ASK ME ABOUT SPAMMING THE REPORT FORUM TO PROTECT ~MY WIFE'S~ OKCUPID PERSONALS ANALYSIS SA-MART THREAD. DO IT. ALL THE TIME. CONSTANTLY. IF SHE DOESN'T HAVE THE THREAD, SHE'LL WANT TO TALK TO ME!
Can anyone offer an explanation of what an app should consist of? I can't really understand when something should be factored out into an "app" and when it's part of a main Django site. I would like a few concrete examples, if you know of any, or could make any up.

king_kilr
May 25, 2007

LOLLERZ posted:

Can anyone offer an explanation of what an app should consist of? I can't really understand when something should be factored out into an "app" and when it's part of a main Django site. I would like a few concrete examples, if you know of any, or could make any up.

http://www.youtube.com/watch?v=A-S0tqpPga4

mwarkentin
Oct 26, 2004

reksio posted:


I am able to access my survey as /q/secondtrypsych/ but I cannot for the life of me figure out how to access the CSV and e-mail tools. I've tried every combination of /q/manage/csv/secondtrypsych but all I get is a redirect to my index page.

It looks like you need to use a custom management command for sending emails (http://github.com/rmt/seantis-quest...naire_emails.py)

Details are here: http://docs.djangoproject.com/en/dev/howto/custom-management-commands/#howto-custom-management-commands

I think you should be able to just run ./manage.py questionnaire_emails

reksio
Feb 5, 2007
Thanks for the help mwarkentin. I tried running the e-mail command from the terminal, but got tripped up because "QUESTIONNAIRE_DEFAULT not in settings" but at the same time I have searched the code and cannot figure out what this setting is supposed to be set at.

Since my project I am working on for school is to do stats analysis on questionnaire results, the CSV export to me is a probably the most important aspect to get this up and running. The problem with this is that the application wants me to pass my questionnaire ID (qid) to the export_csv view, but I have no idea what this ID is. If somebody could take a look at this I would be super grateful, and my offer still stands if somebody would be willing to help me with these issues for some sum we can both agree on.

spencer for hire
Jan 27, 2006

we just want to dance here, someone stole the stage
they call us irresponsible, write us off the page

king_kilr posted:

You're going to be wanting to look at ModelForms, and inlineformest_factory.

Thanks. I guess I just needed to look at it more closely and actually do some trial and error.

Is there a way to required a minimum number of forms for an inlineformset?

is_valid() does not throw an error for blank fields unless the form is partially complete. I'd like to throw a "this field is required" error if at least 2 Poll choices aren't entered.

king_kilr
May 25, 2007

spencer for hire posted:

Thanks. I guess I just needed to look at it more closely and actually do some trial and error.

Is there a way to required a minimum number of forms for an inlineformset?

is_valid() does not throw an error for blank fields unless the form is partially complete. I'd like to throw a "this field is required" error if at least 2 Poll choices aren't entered.

You'd have to subclass BaseInlineFormset and overide is_valid() to do that logic, there isn't an option for it like max_num or extra.

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.
When should I use a OneToOneField, and when should I use ForeignKey(unique=True)?

For example, the Django Book's section on user profiles uses ForeignKey(User, unique=True) in the profile. I'd expect it to use a OneToOneField; is there any reason that's not done in the example?

king_kilr
May 25, 2007

pokeyman posted:

When should I use a OneToOneField, and when should I use ForeignKey(unique=True)?

For example, the Django Book's section on user profiles uses ForeignKey(User, unique=True) in the profile. I'd expect it to use a OneToOneField; is there any reason that's not done in the example?

In .96 (which the original DjangoBook was written for) OneToOneFields were fairly hosed up, for example the automatically became primary keys. Personally I would always ues OneToOneFields for that stuff because it changes the reverse accessor, and that's very useful to crazy people like me who have automatic caching on gets by pk :)

Adbot
ADBOT LOVES YOU

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.
Sounds reasonable. I figured there'd be something like that, and I'm glad to hear it's no longer an issue.

It just seemed silly getting a queryset back from a de facto one-to-one field.

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