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
MonkeyMaker
May 22, 2006

What's your poison, sir?

Blinkz0rz posted:

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.

It'd be easy enough to write a view mixin (assuming CBVs, use a decorator if you're using FBVs) that, on required recent-login views, checks their login time against a timedelta. If it's over a certain threshold, make 'em log in again.

If you want it to be based on activity, just store an additional last_action_time datetime in their session. That'd be best solved with a middleware.

Someone actually proposed something like this to django-braces so we might build and include it in that soon.

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 decided that I want a view to add a message to a template depending on in what way it was called. That is to say, for example, if you go to the login page when already logged in, it redirects to the homepage and displays a helpful message. The "redirects" part works, but the "message" part has hit a few snags.

Right now, it looks like this:
code:
def custom_login(request, **kwargs):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('upsets:index'))
    else:
        return login(request, **kwargs)
(Copied from a stackoverflow page with some modifications)

I want the 'upsets:index' part to say "You're already logged in". I know that reverse takes kwargs, but it would be kind of stupid to expose this functionality in the url as the goal is foolproofing.

NtotheTC
Dec 31, 2007


I might be misunderstanding, but is this not a job for the messaging framework in django?

https://docs.djangoproject.com/en/1.6/ref/contrib/messages/

ufarn
May 30, 2009
Sounds like it.

Dominoes
Sep 20, 2007

supermikhail posted:

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.

Nimrod posted:

request.META['HTTP_REFERER'] ?

Thermopyle posted:

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 posted:

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.

Thank you very much. I used Nimrod's solution of request.META['HTTP_REFERER']:
Python code:
referer = request.META['HTTP_REFERER']
# The last part of the referring URL corresponds to the view in urls.py.
origin = re.search(r'/[a-z]*/$', referer).group()
return HttpResponseRedirect(origin)

Dominoes fucked around with this message at 12:35 on May 31, 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."

NtotheTC posted:

I might be misunderstanding, but is this not a job for the messaging framework in django?

https://docs.djangoproject.com/en/1.6/ref/contrib/messages/

ufarn posted:

Sounds like it.

Thanks!

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."
Are there conventional ways of doing update and comments feeds in Django?

Blinkz0rz
May 27, 2001

MY CONTEMPT FOR MY OWN EMPLOYEES IS ONLY MATCHED BY MY LOVE FOR TOM BRADY'S SWEATY MAGA BALLS
Is there any way to not cache template fragments?

My notifications (messages, form errors, etc.) are loaded via an include and they never dismiss correctly. My guess is that something is caching the template and so the message sticks around even though it's not in the message store anymore.

I can't think that this is an uncommon request. Maybe I'm just doing something wrong?

MonkeyMaker
May 22, 2006

What's your poison, sir?

Blinkz0rz posted:

Is there any way to not cache template fragments?

My notifications (messages, form errors, etc.) are loaded via an include and they never dismiss correctly. My guess is that something is caching the template and so the message sticks around even though it's not in the message store anymore.

I can't think that this is an uncommon request. Maybe I'm just doing something wrong?

I haven't had them stick around, even when using a message include.

But it's really hard to debug code I can't see.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Let's say I have a couple models: Blog and BlogComment. BlogComment has a ForeignKey to Blog. How to I use the ORM to find all the Blogs that have at least 1 comment? Or should I add a comment_count field to Blog and just filter on that?

Blinkz0rz
May 27, 2001

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

fletcher posted:

Let's say I have a couple models: Blog and BlogComment. BlogComment has a ForeignKey to Blog. How to I use the ORM to find all the Blogs that have at least 1 comment? Or should I add a comment_count field to Blog and just filter on that?

Annotations to the rescue!

code:
from django.db.models import Count

Blog.objects.annotate(num_comments=Count('comments')).filter(num_comments__gt=0)

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Haven't used annotate or Count yet. That's pretty sweet! Thanks Blinkz0rz!!

Here's the SQL it generated:
code:
 SELECT blog.id,
       blog.author_id,
       blog.publish_date,
       blog.title,
       blog.slug_title,
       blog.text,
       Count(blogcomment.id) AS num_comments
FROM   blog
       LEFT OUTER JOIN blogcomment
                    ON ( blog.id = blogcomment.blog_id )
GROUP  BY blog.id
HAVING Count(blogcomment.id) > 0  

Pumpkin Pirate
Feb 2, 2005
???????
Because you're specifically looking to distinguish zero from non-zero, you can also do it like this:

Blog.objects.filter(comments__pk__isnull=False).distinct()

That will do an inner join, so blogs with no comments won't be in the result.

Blinkz0rz
May 27, 2001

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

Pumpkin Pirate posted:

Because you're specifically looking to distinguish zero from non-zero, you can also do it like this:

Blog.objects.filter(comments__pk__isnull=False).distinct()

That will do an inner join, so blogs with no comments won't be in the result.

I didn't know you could do a null test against a RelatedManager model property. That's pretty awesome.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Is there a way to programatically set an ImageField to an existing local file and have it run through my upload_to override?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
This seemed to work for me: http://stackoverflow.com/questions/3723220/how-do-you-convert-a-pil-image-to-a-django-file

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
How come django.core.context_processors.request isn't part of the default TEMPLATE_CONTEXT_PROCESSORS? Any reason you wouldn't want to have it in there?

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

fletcher posted:

How come django.core.context_processors.request isn't part of the default TEMPLATE_CONTEXT_PROCESSORS? Any reason you wouldn't want to have it in there?

I dunno, I've never used it. Surely most of the request information is handled by the view, so that leaves cherry picking certain properties for your template, which a dedicated context processor is probably better suited for.

I imagine more than anything not having it as the default is a way to discourage certain anti patterns like switchs based on the request method in the template.

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'm trying to implement a simple search, and use the same view as for normal browsing. Maybe it's not the best idea, as now I don't know how to implement the combined navigation, so that if search is going on it navigates over the search items. My first thought was to somehow pass the search_form via the navigation link, but I'm not sure that's even possible. What's the normal procedure? I guess I could attach the form with javascript, but that seems like a convoluted solution for a commonplace problem.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.

supermikhail posted:

I'm trying to implement a simple search, and use the same view as for normal browsing. Maybe it's not the best idea, as now I don't know how to implement the combined navigation, so that if search is going on it navigates over the search items. My first thought was to somehow pass the search_form via the navigation link, but I'm not sure that's even possible. What's the normal procedure? I guess I could attach the form with javascript, but that seems like a convoluted solution for a commonplace problem.

What exactly is the desired result? Do you want a search form as part of the navigation and on every page? If that is what you want then you can just add a context processor that always brings the form into your template.

Maybe I've misunderstood what you're trying to do though.

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."
Hm. The desired result is that during search when you click a ">" link it takes you to the next page of search, with the search form (that, yes, is present everywhere) filled as before. That's as opposed to regular browsing, when it's the next page of the whole list. I'm not sure if context processors help there (admittedly, I just skimmed the documentation for the first time).

MonkeyMaker
May 22, 2006

What's your poison, sir?

supermikhail posted:

Hm. The desired result is that during search when you click a ">" link it takes you to the next page of search, with the search form (that, yes, is present everywhere) filled as before. That's as opposed to regular browsing, when it's the next page of the whole list. I'm not sure if context processors help there (admittedly, I just skimmed the documentation for the first time).

So long as you always instantiate the search form using the data that it expects (request.GET, I'd suspect), you'll get it filled in like you expect.

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 guess I should pass the form data along the link then. It kind of feels stupid having all that form validation stuff, and then just passing the search term as a simple argument. But I guess it doesn't matter since the form is not processed at this point. Also additional url patterns. Or can you add to GET in a link, other than by javascript?

MonkeyMaker
May 22, 2006

What's your poison, sir?

supermikhail posted:

I guess I should pass the form data along the link then. It kind of feels stupid having all that form validation stuff, and then just passing the search term as a simple argument. But I guess it doesn't matter since the form is not processed at this point. Also additional url patterns. Or can you add to GET in a link, other than by javascript?

Search forms aren't changing data so they should just be passed through the GET. You'll probably want a templatetag that re-adds the GET params to your next/prev/# links.

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.
Turns out my code from the last post was in the wrong order, but now I'm on to a new and exciting problem...

Has anyone ever used django-dynamic-formset before? It adds information well, but I can't seem to get it to prefill in my UpdateView. I'm starting to become concerned that it was only designed with creating data in mind...

Hed
Mar 31, 2004

Fun Shoe
Today I started getting a few "Invalid HTTP_HOST header:" that point back to my Amazon AWS external IP. Should I be concerned about this? Django is running through WSGI to nginx on a local tcp socket.

From quick googling it looks like something not to worry about (just spoofers) but wanted to make sure and kind of understand what's going on here. Are people just forging headers with a from address of my public IP?

Hed fucked around with this message at 01:16 on Jun 21, 2014

Ahz
Jun 17, 2001
PUT MY CART BACK? I'M BETTER THAN THAT AND YOU! WHERE IS MY BUTLER?!
I have a situation where I want to make a third party request INSIDE a current users request.

Essentially I want to alter the traditional oauth2 flow where the user is redirected back to the Application after authorizing their credentials for the first time. I would like the Application to receive the authorization code once the user approves it via an internal Request inside Django. But I want to redirect the user to stay within my site for some additional account process wizards.

This is a situation where oath is being used to authorize a third part iOS or Android application, not a browser app so I essentially don't care if the user is redirected to the Application's own post-authorization splash page.

Don Mega
Nov 26, 2005
What's the easiest way to read a fixture while writing tests to confirm the test data is showing up properly in my views? I don't want to have to have a bunch of constants at the top of the file, i.e. TEST_USERNAME, TEST_EMAIL, etc. Should I just open it and decode the JSON or is there already a method supplied by Django?

Edit: I guess I can just retrieve the test data out of the database on a start up method. Some times the most obvious answer comes to you without thinking about the problem.

Don Mega fucked around with this message at 00:34 on Jul 27, 2014

Thermopyle
Jul 1, 2003

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

Don Mega posted:

What's the easiest way to read a fixture while writing tests to confirm the test data is showing up properly in my views? I don't want to have to have a bunch of constants at the top of the file, i.e. TEST_USERNAME, TEST_EMAIL, etc. Should I just open it and decode the JSON or is there already a method supplied by Django?

Use model_mommy to make a bunch of test models in your tests.

Ahz
Jun 17, 2001
PUT MY CART BACK? I'M BETTER THAN THAT AND YOU! WHERE IS MY BUTLER?!
What is the recommended way to load test an app? Primarily I want to load test and optimize my queries.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Ahz posted:

What is the recommended way to load test an app? Primarily I want to load test and optimize my queries.

I like using Django Debug Toolbar to figure out where I am missing some select_related and prefetch_related type stuff. A lot of my app is AJAX based though, so I also tend to just tail the General Query Log in MySQL. I also use the Slow Query Log in MySQL.

As far as throwing a bunch of requests at your app, Apache Bench, Siege, JMeter, and httperf are a few to take a look at.

Chosen
Jul 11, 2002
Vibrates when provoked.
I recommend http://locust.io it's got a low barrier of entry.

Storgar
Oct 31, 2011
Hi all,

I'm messing around with Django and I'm trying to make a sample app (called "blog") and I'm running into a problem with using the url template tag. I have one app "blog" inside a project called "orion". I've been googling this for almost two days and it seems to be a common problem. I've double checked and tried a lot of things, however, most of the problems that people have online seem to have a root cause unrelated to mine (mostly typos and stuff). I beg you, goons, help me.

Here is the root urls.py file:

code:
from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'(|^blog/)', include('blog.urls', namespace="blog")),
    url(r'^admin/', include(admin.site.urls)),
)
And here is the blog urls.py file:

code:
from django.conf.urls import patterns, url

from blog import views

urlpatterns = patterns('',
    url(r'', views.index, name='index'),
    url(r'^dashboard/', views.dashboard, name='dashboard'),
    url(r'^new_post/', views.new_post, name='new_post'),
    url(r'^login/', views.user_login, name='login'),
    url(r'^logout/', views.user_logout, name='logout'),
)
When I try and put "{% url 'blog:login' %}" into an html template somewhere, I get this message:

code:
NoReverseMatch at /
Reverse for 'login' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'(|^blog/)login/']
I can see from the output that it is finding the right url pattern, but for some reason there is no match...

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
What if you change r'(|^blog/)' to just r'^blog/'?

The March Hare
Oct 15, 2006

Je rêve d'un
Wayne's World 3
Buglord

Storgar posted:

<<snip>>


1 pattern(s) tried: [u'(|^blog/)login/']

Looks like it is trying to find <url>/(|^blog/)login/ which is almost certainly not what you intended.


e:f;b

Storgar
Oct 31, 2011
Ah ok. I was trying to make localhost:8000 and localhost:8000/blog/ both redirect to the index view of the blog app. I separated that into two lines. Also I should learn more about regex.

Additionally, I noticed that the index view of the blog app matches ''. I think this was causing the index view to be matched to everything. I changed this to ^$.

Works now...

Thanks!

Thermopyle
Jul 1, 2003

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

I'm thinking about totally forgoing Django's views and forms and doing everything with django-rest-framework. Anyone else doing this? Stupid idea? Brilliant idea?

My motivation for this is that it seems like a lot of redundant effort maintaing views, forms, serializers, and viewsets when really you could do it all with serializers and viewsets along with JS on the client.

ufarn
May 30, 2009

Thermopyle posted:

I'm thinking about totally forgoing Django's views and forms and doing everything with django-rest-framework. Anyone else doing this? Stupid idea? Brilliant idea?

My motivation for this is that it seems like a lot of redundant effort maintaing views, forms, serializers, and viewsets when really you could do it all with serializers and viewsets along with JS on the client.
This is pretty much what forum CMS Microco.sm does. It's written in Django, so it'd probably be a perfect example to comb through.

The March Hare
Oct 15, 2006

Je rêve d'un
Wayne's World 3
Buglord

Thermopyle posted:

I'm thinking about totally forgoing Django's views and forms and doing everything with django-rest-framework. Anyone else doing this? Stupid idea? Brilliant idea?

My motivation for this is that it seems like a lot of redundant effort maintaing views, forms, serializers, and viewsets when really you could do it all with serializers and viewsets along with JS on the client.

I'm with you on this in theory. Haven't actually done it, but I have thought about it and it honestly doesn't seem like a bad idea.

Adbot
ADBOT LOVES YOU

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Thermopyle posted:

I'm thinking about totally forgoing Django's views and forms and doing everything with django-rest-framework. Anyone else doing this? Stupid idea? Brilliant idea?

My motivation for this is that it seems like a lot of redundant effort maintaing views, forms, serializers, and viewsets when really you could do it all with serializers and viewsets along with JS on the client.

That's what I did for my Django project. It's been great, I would definitely do it again.

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