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
Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

What's the best practice for integrating javascript-heavy webapps that build their forms with JS with Django's form handling?

My first inclination is to build ModelForms and Forms as normal and then POST as normal, but, since I'm building my forms with JS on the frontend, this feels like a violation of DRY.

Should I skip using ModelForms and Forms and just do all my validation with django-rest-framework? I haven't done it before, but it looks like you can build validation into django-rest-framework's serializers...

Adbot
ADBOT LOVES YOU

Ahz
Jun 17, 2001
PUT MY CART BACK? I'M BETTER THAN THAT AND YOU! WHERE IS MY BUTLER?!
I don't have years of experience with Django, but it seems like the main benefit of Forms/MF IS the validation backend. The rendering is just a plus on the side.

I'm curious what scenario you have where you're better off with js-built forms vs/ the alternative. I'm just getting into pretty-ing up some of my app and starting to learn jquery where i can.

Pumpkin Pirate
Feb 2, 2005
???????
Could you make a template tag or includable template that looks at a form instance and outputs the data that your JS code would need to render the form? It could, for example generate a dictionary of field names, labels and types, or just straight up generate the JS code to create the form. That could cut down on some of the repetition.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Ahz posted:

I don't have years of experience with Django, but it seems like the main benefit of Forms/MF IS the validation backend. The rendering is just a plus on the side.
I mean the rendering is not an insignificant part because you don't have to repeat yourself. You don't have to build forms in HTML and make sure you keep the HTML forms in-sync with your models when you change your models because the HTML is built from the models when you use Django's forms. If Django didn't render HTML from your Form classes, you'd basically describe a form twice...in Python and then in HTML.

Ahz posted:

I'm curious what scenario you have where you're better off with js-built forms vs/ the alternative. I'm just getting into pretty-ing up some of my app and starting to learn jquery where i can.
There's lots of things to mention about this, but the main thing that started me on this path is a modern and responsive feel. Using a JS framework like ReactJS or Ember or Angular or whatever makes it easier to build single page applications which feel closer to a native application (see the classic example, Gmail).

On a more granular level: it's easier to build complex forms with inter-dependent fields, related models, and custom widgets.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

Thermopyle posted:

What's the best practice for integrating javascript-heavy webapps that build their forms with JS with Django's form handling?

My first inclination is to build ModelForms and Forms as normal and then POST as normal, but, since I'm building my forms with JS on the frontend, this feels like a violation of DRY.

Should I skip using ModelForms and Forms and just do all my validation with django-rest-framework? I haven't done it before, but it looks like you can build validation into django-rest-framework's serializers...

Personally I didn't even bother with my JS app (for context it's a sea ice observation app, that takes entries on an hourly basis and needed to be platform agnostic). It's being built as a standalone offline capable app, so basically the client and server are independent. I'm using django-rest-framework for validation & serialisation, so my routes are just REST endpoints plus authentication. Things that are shared are being handled by some JSON files, so for example all of the multiple choice CharFields are populated by these JSON files of shared data.

That said though, in my use case the backend is literally just a data store. There isn't a lot that it needs to do so it works grand, obviously if your incoming data has some complicated requirements your mileage may vary, but for my purposes it works. I'm even doing the data analysis on the client because the number sets aren't particularly massive, and it means I can keep the back end as dumb and easy to deploy as possible (for when I have to hand the project over).

Maluco Marinero fucked around with this message at 00:26 on Apr 25, 2014

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
Re-bruteforcing my way through Django: I have an (aforementioned) Entry, and a Rating which refers to an entry via ForeignKey. I've been working on getting the average of an entry's ratings after the user has voted (with jQuery). On the view side:

return HttpResponse(serializers.serialize("json", entry.rating_set.all() ))

On the javascript side:

var parsed_input = $.parseJSON(input);
var numerator = 0;
var denominator = 0;
parsed_input.forEach(function(element){
numerator += element.fields.rating;
denominator++;
});
var replacement = (numerator/denominator).toFixed(2);

Except, of course, Entry has a perfectly good function for this purpose, and I look forward to the day I find out that Python and JavaScript have different precision and reloading the page from django and from javascript gives numbers embarrassingly differing by just 0.01.

Are my concerns valid? And is there a way to pass the average rating from an Entry in a more direct way?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

supermikhail posted:

Re-bruteforcing my way through Django: I have an (aforementioned) Entry, and a Rating which refers to an entry via ForeignKey. I've been working on getting the average of an entry's ratings after the user has voted (with jQuery). On the view side:

return HttpResponse(serializers.serialize("json", entry.rating_set.all() ))

On the javascript side:

var parsed_input = $.parseJSON(input);
var numerator = 0;
var denominator = 0;
parsed_input.forEach(function(element){
numerator += element.fields.rating;
denominator++;
});
var replacement = (numerator/denominator).toFixed(2);

Except, of course, Entry has a perfectly good function for this purpose, and I look forward to the day I find out that Python and JavaScript have different precision and reloading the page from django and from javascript gives numbers embarrassingly differing by just 0.01.

Are my concerns valid? And is there a way to pass the average rating from an Entry in a more direct way?

Return the result of the Entry function that calculates the average as the HTTP result instead of returning all the ratings to calculate it client side

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
Edit::doh: I'm a dunce. They call it "non-lateral thinking", I guess. Also, how do you debug views that work via JavaScript (assuming there is a clever trick, not just creating non-JavaScript implementation first :ohdear:).

supermikhail fucked around with this message at 07:09 on Apr 27, 2014

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

supermikhail posted:

Edit::doh: I'm a dunce. They call it "non-lateral thinking", I guess. Also, how do you debug views that work via JavaScript (assuming there is a clever trick, not just creating non-JavaScript implementation first :ohdear:).

Do you mean views that you are calling via javascript in your app? The same way you would debug any other view, really. Either some kind of output in the view itself (logging or print statements), or just look at what its returning directly (console.log). If the inputs aren't too complicated, it's usually easier to just use curl and call the endpoint directly rather than clicking around in your app to trigger it.

Ahz
Jun 17, 2001
PUT MY CART BACK? I'M BETTER THAN THAT AND YOU! WHERE IS MY BUTLER?!

supermikhail posted:

Edit::doh: I'm a dunce. They call it "non-lateral thinking", I guess. Also, how do you debug views that work via JavaScript (assuming there is a clever trick, not just creating non-JavaScript implementation first :ohdear:).

Pycharm is a pretty nifty Javascript debugger. It hooks right into a firefox/chrome instance and gives you some pretty great debug tools, breakpoints etc.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
:( I think I'm too much of a hobbyist to make good use of those tools (especially with PyCharm costing real money)... I think I just found out that Python print goes to my regular console, and the JavaScript output - to the devtools. :downs: (Previously Python didn't want to print due to errors elsewhere and I assumed that it was just somehow eaten up. You learn something new every day.) I am embarrassing.

Dominoes
Sep 20, 2007

Ahz posted:

Pycharm is a pretty nifty Javascript debugger. It hooks right into a firefox/chrome instance and gives you some pretty great debug tools, breakpoints etc.
Is there a way to get it to recognize javascript in html documents that use django's template inheritance (ie {% block %} syntax)? Ie have introspection, color-coding etc.

Dominoes fucked around with this message at 18:46 on Apr 27, 2014

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Dominoes posted:

Is there a way to get it to recognize javascript in html documents that use django's template inheritance (ie {% block %} syntax)? Ie have introspection, color-coding etc.

I've never had it not work for that. Maybe it's a difference between free and not-free PyCharm?

Dominoes
Sep 20, 2007

I'm using the paid version.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Dominoes posted:

I'm using the paid version.

Got an example file I can look at?

Dominoes
Sep 20, 2007

Example where PyCharm doesn't do magic on JS

It does magic on the HTML and Django in the file, and does magic on everything for the file it extends.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Dominoes posted:

Example where PyCharm doesn't do magic on JS

It does magic on the HTML and Django in the file, and does magic on everything for the file it extends.

I won't be on my PyCharm-havin' PC until tomorrow, but I bet you it's because it's not wrapped in script tags in that file. You may have them in the base file/block, but PyCharm doesn't introspect templates deeply enough to figure that out.

Throw some script tags in there to check...or I'll do it tomorrow.

I didn't look at your JS too closely, but I'd probably just insert another block in your base file to take the js from imagery.html and then use the script tags.

Dominoes
Sep 20, 2007

Thermopyle posted:

I won't be on my PyCharm-havin' PC until tomorrow, but I bet you it's because it's not wrapped in script tags in that file. You may have them in the base file/block, but PyCharm doesn't introspect templates deeply enough to figure that out.

Throw some script tags in there to check...or I'll do it tomorrow.

I didn't look at your JS too closely, but I'd probably just insert another block in your base file to take the js from imagery.html and then use the script tags.

Hey, that was it. I'll figure out how to rearrange the file to make it work, if appropriate. Ideally the JS would be in a separate static file, but the host I'm using, Openshift, doesn't play nice with those.

Dominoes fucked around with this message at 10:16 on Apr 29, 2014

Roll Fizzlebeef
Sep 9, 2003


I have the following model that has a fk to itself.

code:
def Assembly(models.Model):
    parent = models.ForeignKey(
        'Assembly', related_name='subassemblies',
        blank=True, null=True
    )
    # ... other non-relevant fields 
When I create a new assembly, I would like to be able to select from the existing assemblies to associate them with the new one. I know inlines can help create new assemblies that are associated but the base (leaf) assemblies already exist in the database and I want an easy way to pick them.

The idea that I have come up with so far is to make two forms. A ModelForm for the new assembly and another form that has the list of assemblies with checkboxes to select them. When the forms are processed, it would create the new assembly then loop the selections and set their parent fk.

Does this sound like a good idea? Does anyone know of a widget that makes it easier to do something like this? Another thing that would be nice is to have filters for the subassemblies so the user can drill down to the ones they are interested in adding rather than being overwhelmed with too many choices.

Roll Fizzlebeef fucked around with this message at 18:48 on May 5, 2014

Dominoes
Sep 20, 2007

Is there a recommended project structure for current versions of Django? Searching shows several different layouts. Mostly, I'm confused about where to put static/(staticfiles/?) and templates/.

Current setup:

code:
-project
    -project
        __init__.py
        settings.py
        urls.py
        views.py
        wsgi.py
    -static
        -app
    -templates
        -app
    -App
    -manage.py    
It looks like most tutorials are recommending referencing the project directory in settings.py as 'os.path.dirname(os.path.abspath(__file__))', but I need to use a pardir() in there to make it work. Does this mean the static and template dirs should be inside project/project instead of up a level like I'm using? Should static files be in 'static/' or 'staticfiles/' ?

xpander
Sep 2, 2004

Dominoes posted:

Is there a recommended project structure for current versions of Django? Searching shows several different layouts. Mostly, I'm confused about where to put static/(staticfiles/?) and templates/.

Current setup:

code:
-project
    -project
        __init__.py
        settings.py
        urls.py
        views.py
        wsgi.py
    -static
        -app
    -templates
        -app
    -App
    -manage.py    
It looks like most tutorials are recommending referencing the project directory in settings.py as 'os.path.dirname(os.path.abspath(__file__))', but I need to use a pardir() in there to make it work. Does this mean the static and template dirs should be inside project/project instead of up a level like I'm using? Should static files be in 'static/' or 'staticfiles/' ?

That's what Two Scoops of Django uses, as of 1.5 and 1.6.

https://github.com/twoscoops/django-twoscoops-project

MonkeyMaker
May 22, 2006

What's your poison, sir?

Dominoes posted:

Is there a recommended project structure for current versions of Django? Searching shows several different layouts. Mostly, I'm confused about where to put static/(staticfiles/?) and templates/.

Current setup:

code:
-project
    -project
        __init__.py
        settings.py
        urls.py
        views.py
        wsgi.py
    -static
        -app
    -templates
        -app
    -App
    -manage.py    
It looks like most tutorials are recommending referencing the project directory in settings.py as 'os.path.dirname(os.path.abspath(__file__))', but I need to use a pardir() in there to make it work. Does this mean the static and template dirs should be inside project/project instead of up a level like I'm using? Should static files be in 'static/' or 'staticfiles/' ?

Per-app templates dir and static dir, site-wide templates and static dirs for site-wide things. That'll help if you ever have to pull an app out, too.

Dominoes
Sep 20, 2007

Thanks - why do many deployment guides, such as this, recommend referring to the project path as this:?
PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))

With the layout I described, this is required instead, which I found out by trial and error:
PROJECT_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir)

For the initial line to work, wouldn't static/, templates/ etc have to be in the project/project directory?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Dominoes posted:

Thanks - why do many deployment guides, such as this, recommend referring to the project path as this:?
PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))

With the layout I described, this is required instead, which I found out by trial and error:
PROJECT_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir)

For the initial line to work, wouldn't static/, templates/ etc have to be in the project/project directory?

Why do you think you require the second line? What exactly goes wrong if you use the first?

I recommend picking up Two Scoopes of Django. It addresses a lot of this stuff.

Thermopyle fucked around with this message at 21:11 on May 6, 2014

Dominoes
Sep 20, 2007

Thermopyle posted:

Why do you think you require the second line? What exactly goes wrong if you use the first?

I recommend picking up Two Scoopes of Django. It addresses a lot of this stuff.
The first line points to a (nonexistant) 'project/project/static' directory when used with the rest of these guides. My actual static (or templates) directory is up a level in 'project/static'.

ie: in the guide I linked:

Python code:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

Dominoes fucked around with this message at 21:20 on May 6, 2014

Roll Fizzlebeef
Sep 9, 2003


You could just do something like os.path.join(BASE_DIR, '..', 'media') as needed.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Dominoes posted:

The first line points to a (nonexistant) 'project/project/static' directory when used with the rest of these guides. My actual static (or templates) directory is up a level in 'project/static'.

ie: in the guide I linked:

Python code:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

Well, I guess my point was that what matters is not what BASE_DIR is actually set to, it is if things work. BASE_DIR isn't actually a Django setting. It's just kind of a convention for the name of the variable you use to store a path that you then use to build other paths in the settings.

You could not define it at all and use absolute paths every where else you specify paths. You could specify a directory that was three levels too deep into a non-existent directory and use '../../..' in front of all of your other path declarations. The point is you just set BASE_DIR to whatever you want to make it easier to build your paths later in your settings.

As to your question about the recommended project structure, 2 Scoops details something like this:

pre:
- Project
   -Project
   urls.py
   wsgi.py
   manage.py
   blah, blah, blah
   -settings
      __init__.py
      base.py
      local.py
      staging.py
      production.py
   - ThisIsAnApp
      -static
         -ThisIsAnApp
            an_app_specific_jpg.jpg
            another_jpg.jpg
      -templates
         -ThisIsAnApp
            app_specific_template.html
      models.py
      etc, etc
   - ThisIsAnotherApp
      -static
         -ThisIsAnotherApp
            app_specific.js
            app_specific.png
      -templates
         -ThisIsAnotherApp
            app_specific_template.html
      models.py
      etc, etc
   - templates
      these.html
      are.html
      site-wide.html
      templates.html
   - static
      site_wide_static.png
      site_wide_static.css
      site_wide_static.js
For that kind of structure, they recommend settings like this in base.py:

Python code:
from unipath import Path

BASE_DIR = Path(__file__).ancestor(3)
MEDIA_ROOT = BASE_DIR.child("media")
STATIC_ROOT = BASE_DIR.child("static")
STATICFILES_DIRS = (BASE_DIR.child("assets"),)
TEMPLATE_DIRS=(BASE_DIR.child("templates"),)
As you can see they use a library for managing paths, but you could do it with standard library functions as well. They even give an example of that, but it was on the next page from where I copied the above from and I didn't realize it and don't want to type it out again.

Does this help you?

Thermopyle fucked around with this message at 23:19 on May 6, 2014

MonkeyMaker
May 22, 2006

What's your poison, sir?

Thermopyle posted:

Well, I guess my point was that what matters is not what BASE_DIR is actually set to, it is if things work. BASE_DIR isn't actually a Django setting. It's just kind of a convention for the name of the variable you use to store a path that you then use to build other paths in the settings.

You could not define it at all and use absolute paths every where else you specify paths. You could specify a directory that was three levels too deep into a non-existent directory and use '../../..' in front of all of your other path declarations. The point is you just set BASE_DIR to whatever you want to make it easier to build your paths later in your settings.

As to your question about the recommended project structure, 2 Scoops details something like this:

pre:
- Project
   -Project
   urls.py
   wsgi.py
   manage.py
   blah, blah, blah
   -settings
      __init__.py
      base.py
      local.py
      staging.py
      production.py
   - ThisIsAnApp
      -static
         -ThisIsAnApp
            an_app_specific_jpg.jpg
            another_jpg.jpg
      -templates
         -ThisIsAnApp
            app_specific_template.html
      models.py
      etc, etc
   - ThisIsAnotherApp
      -static
         -ThisIsAnotherApp
            app_specific.js
            app_specific.png
      -templates
         -ThisIsAnotherApp
            app_specific_template.html
      models.py
      etc, etc
   - templates
      these.html
      are.html
      site-wide.html
      templates.html
   - static
      site_wide_static.png
      site_wide_static.css
      site_wide_static.js
For that kind of structure, they recommend settings like this in base.py:

Python code:
from unipath import Path

BASE_DIR = Path(__file__).ancestor(3)
MEDIA_ROOT = BASE_DIR.child("media")
STATIC_ROOT = BASE_DIR.child("static")
STATICFILES_DIRS = (BASE_DIR.child("assets"),)
TEMPLATE_DIRS=(BASE_DIR.child("templates"),)
As you can see they use a library for managing paths, but you could do it with standard library functions as well. They even give an example of that, but it was on the next page from where I copied the above from and I didn't realize it and don't want to type it out again.

Does this help you?

BASE_DIR isn't a setting but it's in the default settings as of Django 1.6, calculated as dir above the dir holding the settings.py file.

Also, I don't see any reason to use Unipath anymore and I'm sorry I showed it to pydanny years ago. :(

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

MonkeyMaker posted:

BASE_DIR isn't a setting but it's in the default settings as of Django 1.6, calculated as dir above the dir holding the settings.py file.

Also, I don't see any reason to use Unipath anymore and I'm sorry I showed it to pydanny years ago. :(
Yeah, I was only mentioning that it wasn't a setting to try and illuminate the fact that it's only important as far as it increases the convenience of setting other settings.

And, yes, I've always thought the inclusion of Unipath in 2 Scoops was odd. Now I know who to blame.

Dominoes
Sep 20, 2007

Thanks - I redid my settings.py according to the 1.6 default. It looks like its method of 'BASE_DIR = os.path.dirname(os.path.dirname(__file__))' does the same as my parent method. I think the deployment guides I was referencing were outdated or nonstandard.

I like how in Monkey's example, the app-specific templates are in project/app/templates, instead of project/templates/app. Using the latter, you'd reference a template like so:

code:
return render_to_response('app/index.html', context_dict, context)
How do you do the same with the project/app/templates structure?

Do you add add 'BASE_DIR' to TEMPLATE_DIRS in settings, then reference the template as 'app/templates/index.html'? That seems to work. It looks like not adding to TEMPLATE_DIRS, and not adding '/template', but nesting the templates in an additional app folder, ie project/app/templates/app/index.html works too. Cleaner in some ways, but unnecessarily buried.

Dominoes fucked around with this message at 18:43 on May 8, 2014

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
Does anyone know why nothing happens when I click Submit on a login page:
code:
{% extends "upsets/title.html" %}

{% block content %}

{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}

<form method="post" action="/upsets/login/">
{% csrf_token %}
<table>
<tr>
    <td>{{ form.username.label_tag }}</td>
    <td>{{ form.username }}</td>
</tr>
<tr>
    <td>{{ form.password.label_tag }}</td>
    <td>{{ form.password }}</td>
</tr>
</table>

<input type="submit" value="login" />
</form>

{% endblock %}
I also have this line in urls.py:
code:
url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'upsets/login.html'})
As far as I've been able to figure out, this is the most basic code that should work, except that I've taken out the hidden "next" field, but I figure if that was the problem there at least would have been an error. Also I'm not sure how to provide the url for it.

Would writing my own view and form help?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Dominoes posted:

Thanks - I redid my settings.py according to the 1.6 default. It looks like its method of 'BASE_DIR = os.path.dirname(os.path.dirname(__file__))' does the same as my parent method. I think the deployment guides I was referencing were outdated or nonstandard.

I like how in Monkey's example, the app-specific templates are in project/app/templates, instead of project/templates/app. Using the latter, you'd reference a template like so:

code:
return render_to_response('app/index.html', context_dict, context)
How do you do the same with the project/app/templates structure?

Do you add add 'BASE_DIR' to TEMPLATE_DIRS in settings, then reference the template as 'app/templates/index.html'? That seems to work. It looks like not adding to TEMPLATE_DIRS, and not adding '/template', but nesting the templates in an additional app folder, ie project/app/templates/app/index.html works too. Cleaner in some ways, but unnecessarily buried.

The reason you should nest an extra app directory inside templates is because all of the template directories throughout your project are namespaced together by the app_directories.Loader. So, if you had project/app1/templates/index.html and project/app2/templates/index.html, project/templates/index.html and then you referenced index.html, Django doesn't know which one you want.

It would be better if you didn't have to nest that extra app directory, but ~history~.

So, to answer your question, you don't add your base dir to TEMPLATE_DIRS, you use project/app/templates/app/index.html. This is how the django.template.loaders.app_directories.Loader finds the template. (That loader is part of the default configuration for TEMPLATE_LOADERS).

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

supermikhail posted:

stuff

As far as I've been able to figure out, this is the most basic code that should work, except that I've taken out the hidden "next" field, but I figure if that was the problem there at least would have been an error. Also I'm not sure how to provide the url for it.

Would writing my own view and form help?

https://docs.djangoproject.com/en/1.5/topics/auth/default/#module-django.contrib.auth.views

I guess read that and then see if you've got any more questions. It specifically answers how to provide the url.

MonkeyMaker
May 22, 2006

What's your poison, sir?
My usual layout is something like:

code:
project-folder/
----project/
--------app/
------------static/
----------------app/
--------------------css/
------------------------app.css
------------templates/
----------------app/
--------------------models_list.html
--------------------[...]
--------static/
------------css/
----------------project.css
--------templates/
------------_layouts/
----------------base.html

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."

Thermopyle posted:

https://docs.djangoproject.com/en/1.5/topics/auth/default/#module-django.contrib.auth.views

I guess read that and then see if you've got any more questions. It specifically answers how to provide the url.

Yes. Oh, yes. Before I had "<input type="hidden" name="next" value="/upsets/" />" to go to the index, but that didn't do anything either. I have a suspicion that it should have stayed the "next" parameter as in the doc (although maybe it doesn't matter)... Well, let me say what I think is going on: You click "log in", it gets you to the default login view (over which I have no control) which goes to my "template_name" from which it should post back to the default login view, and from there to "next"... "Redirect_field_name" doesn't fix it, but maybe I'm doing it wrong:
code:
url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'upsets/login.html', 'redirect_field_name': '/upsets/'}),
(I'm pretty sure it's wrong, but I'm kind of at the end of my wits, so there, poking.)

ZShakespeare
Jul 20, 2003

The devil can cite Scripture for his purpose!
I'm A little late to the party but if I were to use django as a backend to one of these hipster JS front ends, I would use tastypie, which has the added benefit of being able to say "hey this resource maps onto this modelform so you can just reuse all of the validation". You're still going to run into the problem with making all the forms twice though.

Dominoes
Sep 20, 2007

MonkeyMaker posted:

My usual layout is something like:
Thanks for posting this.

Thermopyle posted:

The reason you should nest an extra app directory inside templates is because all of the template directories throughout your project are namespaced together by the app_directories.Loader. So, if you had project/app1/templates/index.html and project/app2/templates/index.html, project/templates/index.html and then you referenced index.html, Django doesn't know which one you want.

It would be better if you didn't have to nest that extra app directory, but ~history~.

So, to answer your question, you don't add your base dir to TEMPLATE_DIRS, you use project/app/templates/app/index.html. This is how the django.template.loaders.app_directories.Loader finds the template. (That loader is part of the default configuration for TEMPLATE_LOADERS).
Thanks, I'll go with this from now on.

supermikhail
Nov 17, 2012


"It's video games, Scully."
Video games?"
"He enlists the help of strangers to make his perfect video game. When he gets bored of an idea, he murders them and moves on to the next, learning nothing in the process."
"Hmm... interesting."
I put a LOGIN_REDIRECT_URL in my settings, and also augmented next with |escape as many examples do, still my submit button is as limp as something limp (but completely inoffensive). And the value for the 'next' field shows as empty in the source, unless I hardcode it in the template, but that doesn't help either. I'm starting to think my Django is djinxed. :(

NtotheTC
Dec 31, 2007


ZShakespeare posted:

I'm A little late to the party but if I were to use django as a backend to one of these hipster JS front ends, I would use tastypie, which has the added benefit of being able to say "hey this resource maps onto this modelform so you can just reuse all of the validation". You're still going to run into the problem with making all the forms twice though.

Tastypie isn't ideal anymore I don't think. Poorly maintained and not as functional. Use Django REST framework.

e: maybe "poorly maintained" is a bit harsh. But still REST Framework is better, use that :)

NtotheTC fucked around with this message at 11:56 on May 12, 2014

Adbot
ADBOT LOVES YOU

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I replaced django-openid-auth with python-social-auth and got confused when I started seeing exceptions like this:

quote:

ImproperlyConfigured: Error importing authentication backend django_openid_auth.auth.OpenIDBackend: "No module named django_openid_auth.auth"

Couldn't figure out why it was still trying to use it even though there were no references to django_openid_auth in the code and then it hit me: it was probably storing it with the session.

code:
>>> from django.contrib.sessions.models import Session
>>> s = Session.objects.get(pk='dslrhofmnk5f69m7py7j2e5ihw8zmopp')
>>> s.get_decoded()
{'_auth_user_id': 689L, '_auth_user_backend': 'django.contrib.auth.backends.ModelBackend'}
Durrrr what a stupid mistake on my part!

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