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
reitetsu
Sep 27, 2009

Should you find yourself here one day... In accordance with your crimes, you can rest assured I will give you the treatment you deserve.
Has anyone ever used Django smart selects? I followed their example exactly and I cannot get it to work for the life of me.

I'm reviving a Django project I started earlier in the year - a character builder for a tabletop vampire game. A character can choose a bloodline based on their clan, so I'm trying to represent that with a chained selects thing. Theoretically, the list of available bloodlines should populate based on the character's clan, but it's doing no such thing.

code:
models.py

from django.db import models
from django.contrib.auth import get_user_model
from smart_selects.db_fields import ChainedForeignKey

. . .

class Character(models.Model):
    owner = models.ForeignKey(get_user_model())
    name = models.CharField(max_length=100)
. . .

class Bloodline(models.Model):
    name = models.CharField(
        max_length=100
    )
    parent_clan = models.CharField(
        max_length=100
    )
. . .

class Clan(models.Model):
    character = models.ForeignKey(Character)
    CLAN_CHOICES = (
        (u'Daeva', u'Daeva'),
        (u'Gangrel', u'Gangrel'),
        (u'Mekhet', u'Mekhet'),
        (u'Nosferatu', u'Nosferatu'),
        (u'Ventrue', u'Ventrue'),
    )
    clan = models.CharField(max_length=15, choices=CLAN_CHOICES)
    
    def __unicode__(self):
        return self.clan

class CharacterBloodline(models.Model):
    character = models.ForeignKey(Character)
    clan = models.ForeignKey(Clan)
    bloodline = ChainedForeignKey(
        Bloodline,
        chained_field="clan",
        chained_model_field="clan",
        show_all=False,
        auto_choose=False,
    )
    
    def __unicode__(self):
        return self.bloodline
I've added url(r'^chaining/', include('smart_selects.urls')), to my urls.py, 'smart_selects' is in my Installed Apps in settings.py... I'm really stumped. Under the bloodline field in the admin field... The clan is in the proper dropdown box, but the bloodline field is empty:

Adbot
ADBOT LOVES YOU

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'd like to tell a sad story (with a happy ending).

It began when I tried to use the default login view in my project. I suffered mightily over several sessions and resolved many issues, but in the end all was for naught since it just wouldn't process submit. So today I got depressed, ate a lot of unhealthy food, looked through all the debug tools available to me... and then something clicked - I had jQuery attached to submit events, that was located in the root template. But I realized that it only has to do with a different child template and nothing with the login, so I quickly moved it, and everything worked almost immediately.

So now I intend to have javascript linked in the template it's used in. I'm a bit confused by the fact that I have to put load staticfiles every time, and also am wondering if this is the right way, because I haven't seen any recommendations re: arranging javascript files and it seems to be the usual practice to have everything in the same file. I think I'm remembering jQuery, in fact.

MonkeyMaker
May 22, 2006

What's your poison, sir?

supermikhail posted:

So now I intend to have javascript linked in the template it's used in. I'm a bit confused by the fact that I have to put load staticfiles every time, and also am wondering if this is the right way, because I haven't seen any recommendations re: arranging javascript files and it seems to be the usual practice to have everything in the same file. I think I'm remembering jQuery, in fact.

Do you really want every template load to include all of the template tags used to render all of the parent templates w/o your say?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

supermikhail posted:

So now I intend to have javascript linked in the template it's used in. I'm a bit confused by the fact that I have to put load staticfiles every time, and also am wondering if this is the right way, because I haven't seen any recommendations re: arranging javascript files and it seems to be the usual practice to have everything in the same file. I think I'm remembering jQuery, in fact.

It's not the most efficient way to go about it but I just use django-pipeline to combine & minify all javascript files into one single file, and that gets included in my base.html (which all other templates extend). While DEBUG=True they all get included as separate un-minified files. There's still a somewhat loose correlation between the names of some javascript files and the names of some templates, but it's not very strict and there's some overlap here and there.

Dominoes
Sep 20, 2007

Looking for wisdom on moving from Sqlite to Postgres. I have a webapp that helps track things at work. It uses a Sqlite database, and is running on Openshift.

Openshift has been a pain in the rear end. It works, but I have multiple issues, ie no static files, convoluted directory structure/update process, and wrong system time. These issues might be fixable, but no there's no documentation or support available, so it's a lost cause.

I'm moving to Heroku, which doesn't support SQlite. I've got Postgres working on Heroku, and on my personal computer. I need to migrate my database, which has 1000s of records. With Sqlite, it was easy to just upload/download the file - I don't think I can do that with Postgres. Locally, I've been able to use Django's dumpdata and load data to export the data as json. I can't seem to do that on Heroku. If I use 'heroku run python manage.py loaddata', it can't find the file. (the file's local) How should I approach this?

Dominoes fucked around with this message at 20:50 on May 16, 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."

MonkeyMaker posted:

Do you really want every template load to include all of the template tags used to render all of the parent templates w/o your say?

Not that much, but it seemed to me like it was doing it anyway. I am corrected.

fletcher posted:

It's not the most efficient way to go about it but I just use django-pipeline to combine & minify all javascript files into one single file, and that gets included in my base.html (which all other templates extend). While DEBUG=True they all get included as separate un-minified files. There's still a somewhat loose correlation between the names of some javascript files and the names of some templates, but it's not very strict and there's some overlap here and there.

I don't see what the point of this is. Is it a performance boost if upon deployment everything is in a single file?

Molten Llama
Sep 20, 2006

Dominoes posted:

Locally, I've been able to use Django's dumpdata and load data to export the data as json. I can't seem to do that on Heroku. If I use 'heroku run python manage.py loaddata', it can't find the file. (the file's local) How should I approach this?

The file's local to what? If it's not in the repo that's getting pushed to Heroku, you need to get it there some other way or directly connect to Heroku Postgres from your local dev machine.

The latter would be my preference as there are fewer moving parts. heroku config will give you your Postgres URL. Temporarily sub that in for your development database and let 'er rip.

Heroku instances have curl installed if you just want to suck the file down over HTTP. You can run it directly (heroku run curl ...) or by opening a bash session (heroku run bash).

Molten Llama fucked around with this message at 21:28 on May 16, 2014

Dominoes
Sep 20, 2007

Thanks. I went with your second option, and it worked! Connecting directly seems like a pretty powerful and useful feature.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

supermikhail posted:

I don't see what the point of this is. Is it a performance boost if upon deployment everything is in a single file?

Minimizing the number of HTTP requests is definitely something you can do to improve performance. There are tradeoffs though, since you don't want to load a ton of code that you aren't going to use. The site I do it on doesn't have a ton of JavaScript so it's not a huge deal.

It keeps things simple though, I don't have to think about what JavaScript is loaded for which page, it's just all there all the time on every page.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Is there a standard convention for where you declare all your signal handlers?

edit: found this on the signals page https://docs.djangoproject.com/en/dev/topics/signals/

quote:

Where should this code live?
Strictly speaking, signal handling and registration code can live anywhere you like, although it’s recommended to avoid the application’s root module and its models module to minimize side-effects of importing code.

In practice, signal handlers are usually defined in a signals submodule of the application they relate to. Signal receivers are connected in the ready() method of your application configuration class. If you’re using the receiver() decorator, simply import the signals submodule inside ready().
Changed in Django 1.7:

Since ready() didn’t exist in previous versions of Django, signal registration usually happened in the models module.

I'm using 1.5. In the end of my models.py do I just do an import myapp.signals or something?

fletcher fucked around with this message at 23:29 on May 16, 2014

Chosen
Jul 11, 2002
Vibrates when provoked.

fletcher posted:

Is there a standard convention for where you declare all your signal handlers?

edit: found this on the signals page https://docs.djangoproject.com/en/dev/topics/signals/


I'm using 1.5. In the end of my models.py do I just do an import myapp.signals or something?

I just went through this problem as well. The bottom of models.py is the most common place to keep it, but it's kinda gross:
  • People put it there to register the signal handlers as a side effect of models.py being loaded -- kinda like the older hacks to put things in urls.py to force the right timing.
  • The registration of the signals itself is a side effect of importing a module, instead of an explicit call.
  • It's put at the bottom to avoid circular imports from your handlers using models.

One alternative I've been trying out is doing explicit calls to register the handlers in the app's __init__.py. It feels a little less gross, but it's still open to some circular import problems if you're not careful.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Awesome! Thanks for the tips.

Luigi Thirty
Apr 30, 2006

Emergency confection port.

I'm importing a bunch of XML objects from an API into a database. I don't run the API and I get 1000 entries or nothing. The objects have an ID field that's the same as in the database. There can be no duplicates. The table at the moment has 100,000 rows and the model is very complex. So I have two data sets, items is an ElementTree representing the XML document and then I have the model.

[i for i in items if i.get("id") not in Model.objects.all().values_list('id', flat=True)] seems to be extremely slow but produces what I'm looking for, a list of objects I can feed to an import function. Aside from abusing INSERT IGNORE or some other abortion, what would be a better way to combine the two to produce one list of objects that do not have an ID already in the database?

Pumpkin Pirate
Feb 2, 2005
???????
Written that way, it will re-run the query for each element.

code:
existing = Model.objects.all().values_list('id', flat=True)
[i for i in items if i.get("id") not in existing]
or
code:
[i for i in items if not Model.objects.filter(id=i.get("id")).exists()]
are possible alternatives. The top one is one query returning 100k results, and the bottom is 1k small queries. I'm not sure which would be faster, so you might want to test both.

Luigi Thirty
Apr 30, 2006

Emergency confection port.

:doh: I knew it was something simple like that. I had the 1000 small queries solution before and I was trying to implement the one big query solution. I'll test the speeds of each and see which one works better.

Blinkz0rz
May 27, 2001

MY CONTEMPT FOR MY OWN EMPLOYEES IS ONLY MATCHED BY MY LOVE FOR TOM BRADY'S SWEATY MAGA BALLS

Luigi Thirty posted:

:doh: I knew it was something simple like that. I had the 1000 small queries solution before and I was trying to implement the one big query solution. I'll test the speeds of each and see which one works better.

I bet you'd get better performance on an inverse query if you used a Q object like
code:
Model.objects.filter(~Q(id=i.get('id')).all()

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've got the following code that produces some strange html:
code:
{% for rating in upset.rating_set.all %}
   {% if rating in user.rating_set.all %}
      <input class="rating {{ upset.id }}" value="{{ rating.rating }}">
      <button class="vote {{ upset.id }} success">Vote</button>
   {% else %}
      <input class="rating {{ upset.id }}" value="0">
      <button class="vote {{ upset.id }}">Vote</button>
   {% endif %}
{% endfor %}
Rating has Upset and User as ForeignKeys. For some reason it randomly decides to print both the if and the else statement for a single rating. That is, as it goes down the list of Upsets, it sometimes prints the correct rating in value, but sometimes also adds the 0 underneath in an additional line. Although now that I've rechecked it, it's not actually random, but each reload the same Upsets appear with this glitch. I wonder if this could be due to the fact that I completely rewired my models at some time without restarting the database. It actually broke one model completely, but I haven't worked on it yet, so I haven't bothered restarting the database. (Because as I understand it, I have to delete the file, then create it anew.)

Yay
Aug 4, 2007

Luigi Thirty posted:

I'm importing a bunch of XML objects from an API into a database
[...]
[i for i in items if i.get("id") not in Model.objects.all().values_list('id', flat=True)] seems to be extremely slow but produces what I'm looking for
[...]
what would be a better way to combine the two to produce one list of objects that do not have an ID already in the database?
Off, the top of my head, something like this:
code:
from_xml = set(x['id'] for x in items)
from_db = set(MyModel.objects.filter(id__in=from_xml).values_list('pk', flat=True))
need_inserting = from_xml.difference(from_db)
One query; sets used because in and not in are slower the larger the list/tuple (though the difference is negligible at 1000 items, I'm sure) and who knows when you want to ramp up the number of things you check.

You may run into issues with the above if you're using SQLite, because it only supports up to 999 parameters or something IIRC.

Ahz
Jun 17, 2001
PUT MY CART BACK? I'M BETTER THAN THAT AND YOU! WHERE IS MY BUTLER?!
What's the preferred method of querying a whole mess of related data from the ORM and displaying it in a template.

I am talking about something like an order with about 8 other related tables, traversing multiple joins up to maybe 5 levels deep from a single parent table.

I can query the data easily enough as the query params are simple, in this case all client orders. But I am wondering how far to chain things together in the view vs. passing a master obj to the template and then referencing relationships via child _set memberships.

For instance I can get everything I need in the view as a number of query set objects and pass them back individually. Or I could try to pass them back to the template in as few objects as possible and then have the ORM hit the related tables as I iterate through the query sets for additional data.

Ideas?

If this was a standard SQL recordset, I would make a single big query and pass back a large recordset with all the data I needed in a single obj so that I only hit the DB once.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Ahz posted:

If this was a standard SQL recordset, I would make a single big query and pass back a large recordset with all the data I needed in a single obj so that I only hit the DB once.

You can do that in Django as well through the use of select_related and prefetch_related. Just use those with your original query for the order and then you don't have to worry about your loops in templates generating additional queries.

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

fletcher posted:

You can do that in Django as well through the use of select_related and prefetch_related. Just use those with your original query for the order and then you don't have to worry about your loops in templates generating additional queries.

Yeah I've got a good handle on how select_related automatically traces up the line of parents. Prefetch_related is a little trickier for me to understand.

If I want to start at the parent and then progress 3 levels down to a child, then back up another way up the 'tree', I could do this with some inner and outer join action. It's a little harder to conceptually understand how the ORM handles deep traversal, especially across more than 1 level of parent->child relationships that select_related cannot do.

Dominoes
Sep 20, 2007

I've been troubleshooting getting forms to display cleanly in Django. The way I learned to display forms in the template from the Polls tutorial looks like this:

code:
        <form id="target_form" method="post" action="/target/">
            {% csrf_token %}

            {% for hidden in form.hidden_fields %}
                {{ hidden }}
            {% endfor %}

            {% for field in form.visible_fields %}
                {{ field.errors }}
                {{ field.help_text}}
                {{ field }}<br/>
            {% endfor %}

        <input class="btn btn-primary" type="submit" name="submit" value="Submit"/>
You'd use 'help_text' in the form class for display text.

Unable to get it formatted cleanly, I found online that using '{{ form.as_p }}' will show anything with 'label' in the form class as a label tag, which you can then manipulate with CSS. The method I used with help_text showed un-tagged text above the <input> tags in source view. The official docs on forms mention both methods. Thoughts? Also looking for advice on getting the labels/help_text to align left, and the fields to align right.


I've tried this:
code:
        <form id="target_form" method="post" action="/target/">
            {% csrf_token %}

        <div id="form-left">
            {% for field in form.visible_fields %}
                {{  field.label }}<br/>
            {% endfor %}
        </div>


        <div id="form-right">
            {% for field in form.visible_fields %}
                {{ field.errors }}
                {{ field }}<br/>
            {% endfor %}
        </div>


        <input class="btn btn-primary" type="submit" name="submit" value="Submit"/>
        </form>
This provides some CSS flexibility, but I still can't get a solution where the forms are aligned, the labels are aligned, and the labels are on the same line as the field.

Dominoes fucked around with this message at 10:20 on May 26, 2014

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Dominoes posted:

I've been troubleshooting getting forms to display cleanly in Django. The way I learned to display forms in the template from the Polls tutorial looks like this:

code:
        <form id="target_form" method="post" action="/target/">
            {% csrf_token %}

            {% for hidden in form.hidden_fields %}
                {{ hidden }}
            {% endfor %}

            {% for field in form.visible_fields %}
                {{ field.errors }}
                {{ field.help_text}}
                {{ field }}<br/>
            {% endfor %}

        <input class="btn btn-primary" type="submit" name="submit" value="Submit"/>
You'd use 'help_text' in the form class for display text.

Unable to get it formatted cleanly, I found online that using '{{ form.as_p }}' will show anything with 'label' in the form class as a label tag, which you can then manipulate with CSS. The method I used with help_text showed un-tagged text above the <input> tags in source view. The official docs on forms mention both methods. Thoughts? Also looking for advice on getting the labels/help_text to align left, and the fields to align right.


I've tried this:
code:
        <form id="target_form" method="post" action="/target/">
            {% csrf_token %}

        <div id="form-left">
            {% for field in form.visible_fields %}
                {{  field.label }}<br/>
            {% endfor %}
        </div>


        <div id="form-right">
            {% for field in form.visible_fields %}
                {{ field.errors }}
                {{ field }}<br/>
            {% endfor %}
        </div>


        <input class="btn btn-primary" type="submit" name="submit" value="Submit"/>
        </form>
This provides some CSS flexibility, but I still can't get a solution where the forms are aligned, the labels are aligned, and the labels are on the same line as the field.


Python code:
{% for field in form.visible_fields %}
<div class="fieldWrapper">
                {{  field.label }}
                {{ field.errors }}
                {{ field }}
</div>
 {% endfor %}
Now use CSS to lay out .fieldWrapper input, .fieldWrapper label, etc. If you post an image of what you want (even just crudely drawn boxes) and a JSFiddle of what the HTML that comes out looks like, I'll be happy to CSS it up for you.

Dominoes
Sep 20, 2007

Lumpy posted:

Python code:
{% for field in form.visible_fields %}
<div class="fieldWrapper">
                {{  field.label }}
                {{ field.errors }}
                {{ field }}
</div>
 {% endfor %}
Now use CSS to lay out .fieldWrapper input, .fieldWrapper label, etc. If you post an image of what you want (even just crudely drawn boxes) and a JSFiddle of what the HTML that comes out looks like, I'll be happy to CSS it up for you.
Thanks a lot. Here's the default Django implementation, which is still better than anything I've been able to do myself messing with the position, float, display css tags:


Here's an MS-paint mockup of what I'd like:

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."
Sorry for hijacking, but is this applicable to your problem: http://stackoverflow.com/questions/2820586/how-can-i-control-the-width-of-a-label-tag?

Dominoes
Sep 20, 2007

Dude! That worked!

CSS code:
label {
    width: 180px;
    float: left;
}
Django code:
{% for field in form.visible_fields %}
                {{ field.errors }}
                <label>
                    {{ field.label }}
                </label>
{#                {{ field.help_text}}#}
                {{ field }}<br/>
            {% endfor %}
Should I be using Django's label, or help_text? They both appear to do the same thing.

Dominoes fucked around with this message at 20:09 on May 26, 2014

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Don't be sorry, it's one less thing I need to think about! :effort:

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

Dominoes posted:

Dude! That worked!

CSS code:
label {
    width: 180px;
    float: left;
}
Django code:
{% for field in form.visible_fields %}
                {{ field.errors }}
                <label>
                    {{ field.label }}
                </label>
{#                {{ field.help_text}}#}
                {{ field }}<br/>
            {% endfor %}
Should I be using Django's label, or help_text? They both appear to do the same thing.

Hey! https://docs.djangoproject.com/en/1.6/ref/forms/fields/#help-text Also, I'm pretty sure {{ field.label }} comes with <label> tags... Oh. No. But you should use field.label_tag instead https://docs.djangoproject.com/en/1.6/topics/forms/#looping-over-the-form-s-fields because it a) comes with the label tags, b) points to the corresponding field, otherwise it's pretty pointless.

Dominoes
Sep 20, 2007

Thanks. Any words on how to make a login page redirect to page that triggered it? This Stack Overflow post addresses it, but the solution only works if logging in from a link; I'm using the @login_required method, with no link to reference.

I've tried this:
Python code:
 if user.is_active:
                # If the account is valid and active, we can log the user in.
                # We'll send the user back to the homepage.
                login(request, user)
                origin_url = request.GET.get('next')
                return HttpResponseRedirect(origin_url)
request.GET.get('next') works initially when the page requiring login loads, but is then empty when I need it. Perhaps I could pass it through two requests?

I feel like this is a very common problem - most major websites I use that have logins don't address this - and it's really annoying! Ie you navigate a few pages deep in a website, are met with a login wall, then are spit out at the top after logging in.

Dominoes fucked around with this message at 08:20 on May 28, 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."
One (rather complicated) way I can think of is have the login button be part of a form with a hidden field for the current url (found like this http://stackoverflow.com/questions/2882490/get-the-current-url-within-a-django-template). This goes to your GET login view which passes the hidden field on to the login page, from which you POST it back to the login view, and voila. But maybe I'm overthinking it.

Edit: I'm sure you can have log in with a link and pass the current url as an argument, too.

supermikhail fucked around with this message at 08:39 on May 28, 2014

Nimrod
Sep 20, 2003

Dominoes posted:

Thanks. Any words on how to make a login page redirect to page that triggered it? This Stack Overflow post addresses it, but the solution only works if logging in from a link; I'm using the @login_required method, with no link to reference.

I've tried this:
Python code:
 if user.is_active:
                # If the account is valid and active, we can log the user in.
                # We'll send the user back to the homepage.
                login(request, user)
                origin_url = request.GET.get('next')
                return HttpResponseRedirect(origin_url)
request.GET.get('next') works initially when the page requiring login loads, but is then empty when I need it. Perhaps I could pass it through two requests?

I feel like this is a very common problem - most major websites I use that have logins don't address this - and it's really annoying! Ie you navigate a few pages deep in a website, are met with a login wall, then are spit out at the top after logging in.
request.META['HTTP_REFERER'] ?

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've discovered the following contrivance, which is useful for my situation, on stackoverflow:
code:
    sorted_list = sorted(upset_list, key=lambda u: u.avg_rating())
    print(sorted_list)
    list_of_ids = []
    for upset in sorted_list:
        list_of_ids.append(upset.id)
    print(list_of_ids)
    sorted_list = Upset.objects.filter(id__in=list_of_ids)
    print(sorted_list)
However somehow in the filter query it manages to jumble the objects again. The first "print(sorted_list)" gives the required order, while the second doesn't. Any ideas?

Thermopyle
Jul 1, 2003

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

Dominoes posted:

Thanks. Any words on how to make a login page redirect to page that triggered it? This Stack Overflow post addresses it, but the solution only works if logging in from a link; I'm using the @login_required method, with no link to reference.

I've tried this:
Python code:
 if user.is_active:
                # If the account is valid and active, we can log the user in.
                # We'll send the user back to the homepage.
                login(request, user)
                origin_url = request.GET.get('next')
                return HttpResponseRedirect(origin_url)
request.GET.get('next') works initially when the page requiring login loads, but is then empty when I need it. Perhaps I could pass it through two requests?

I feel like this is a very common problem - most major websites I use that have logins don't address this - and it's really annoying! Ie you navigate a few pages deep in a website, are met with a login wall, then are spit out at the top after logging in.

FWIW, I use django-allauth on all my projects requiring registration and login stuff, and when you get redirect to a login page it appends the url to redirect to on login to the url.

So, like if you visit www.example.com/dashboard/ it will redirect you to www.example.com/login/?next=/dashboard/ and then, on login redirects back to www.example.com/dashboard/.

It's been awhile since I configured any of this on any project, so I can't recall if I had to do anything specific to set that up or not...

ufarn
May 30, 2009
@Dominoes

Here is what project of mine looks like:

In login.html:

HTML code:
<input type="submit" value="Submit" />
<input type="hidden" value="{{ next }}" name="next" />
In views.py (I'm currently using django-registration):

Python code:
from django.contrib.auth.views import login

# ...

def custom_login(request, **kwargs):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('myproject.views.home', args=()))
    else:
        return login(request, **kwargs)
Maybe you're not passing the `next` token in your kwargs, or you're forgetting to send it via the HTML form in the first place.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Should I be avoiding the use of auto_now and auto_now_add?

MonkeyMaker
May 22, 2006

What's your poison, sir?

fletcher posted:

Should I be avoiding the use of auto_now and auto_now_add?

nope. I don't see any warnings or deprecations, do you?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

MonkeyMaker posted:

nope. I don't see any warnings or deprecations, do you?

Yeah I figured it was probably ok. I was googling around and saw some people had pretty strong opinions about how they were evil and should be avoided, but the posts were quite a few years old.

Aaaaand I just realized that I've had auto_now and auto_now_add backwards in all my field definitions this whole time :downs:

MonkeyMaker
May 22, 2006

What's your poison, sir?

fletcher posted:

Yeah I figured it was probably ok. I was googling around and saw some people had pretty strong opinions about how they were evil and should be avoided, but the posts were quite a few years old.

Aaaaand I just realized that I've had auto_now and auto_now_add backwards in all my field definitions this whole time :downs:

They were deprecated at one point but then...they weren't.

I think part of the problem is people started doing

code:
created_at = models.DateTimeField(default=datetime.datetime.now())
and having so many more problems, so they just fixed whatever was wrong with those two kwargs and pretended like nothing ever happened.

(BTW, if you don't see what's wrong with that line, read up on when Python initializes values)

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

supermikhail posted:

I've discovered the following contrivance, which is useful for my situation, on stackoverflow:
code:
    sorted_list = sorted(upset_list, key=lambda u: u.avg_rating())
#this poo poo is embarrassing
    print(sorted_list)
    list_of_ids = []
    for upset in sorted_list:
        list_of_ids.append(upset.id)
    print(list_of_ids)
    sorted_list = Upset.objects.filter(id__in=list_of_ids)
    print(sorted_list)
However somehow in the filter query it manages to jumble the objects again. The first "print(sorted_list)" gives the required order, while the second doesn't. Any ideas?
I'm an idiot, if anyone cares. I wanted to sort by a method, but sorted() returns a python list, not query set, and the template was glitching out. I thought it just didn't want the list. Actually, I iterated over it with "upset_list.all", instead of just "upset_list". :doh: :doh: :doh: No shenanigans required, after all.

Adbot
ADBOT LOVES YOU

Blinkz0rz
May 27, 2001

MY CONTEMPT FOR MY OWN EMPLOYEES IS ONLY MATCHED BY MY LOVE FOR TOM BRADY'S SWEATY MAGA BALLS
Do you guys have any suggestions for implementing the "user activity or logout" functionality that a lot of banks have?

I found a library called session_security but for some weird reason even though it hits the logout(request) line in the library middleware, the user isn't actively logged out and redirected.

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