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
fuf
Sep 12, 2004

haha
I think this is a pretty basic question and I'm embarrassed I can't find the answer.

I have a view for displaying a single blog post:

code:
post = Post.objects.get(pk=int(post_id))
and I want to get primary keys of the next and previous posts, ordered by my "created" DateTimeField, and add them to the context so I can use them in navigation links.

How do I get the primary keys of the posts that are before and after the current post? I guess I have to start with something like this:

code:
posts = Post.objects.all().order_by("-created")
but then what?

Adbot
ADBOT LOVES YOU

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
edit: Better answer in next post, it uses the Primary Key as a tie breaker so it's more reliable.

Dunno if this is the most efficient but you could go up and take the first and then down and take the first, ie

Python code:
post = Post.objects.get(pk=int(post_id))
next = Post.objects.order_by("created").filter(created__gt=post.created)[0]
              # order ascending - get rid off everything earlier than - get the first item
prev = Post.objects.order_by("-created").filter(created__lt=post.created)[0]
              # order descending - get rid off everything later than - get the first item
Make life easier if you're doing this alot and make it a property or method on your Post model.

Python code:
@property
def next(self):
    try:
        return self.__class__.objects.order_by("created")\
                             .filter(created__gt=post.created)[0]
    except IndexError: # list was empty, must be latest post.
        return None
Now you can use post.next to retrieve either the next post, or nothing, making it dead simple to put whatever you need into your templates.

edit: Haha, well there ya go, forgot about that. I'll leave this here anyway.

Maluco Marinero fucked around with this message at 16:08 on Jun 3, 2012

Yay
Aug 4, 2007
If you've got a non-null datetime field, you're in luck, Django's handled it for you with get_[next|previous]_by_[yourfield]

fuf
Sep 12, 2004

haha
Thanks both. I'm glad Yay's solution worked so I didn't have to try and understand yours Maluco. :shobon:

lunar detritus
May 6, 2009


Are there any resources (like the Django Book) that explain how to use the class-based generic views and their templates?

I'm stuck trying to override DetailView to add extra info to the view. :smith:

EDIT: Nevermind, I ended up creating a view instead of using a generic one.

lunar detritus fucked around with this message at 05:06 on Jun 4, 2012

Sparta
Aug 14, 2003

the other white meat

Sharktopus posted:

Do you mean how would you represent this within python or how would you take user input for this?

How to represent it in python/django (getting user input I figure would depend on how it's represented).

I apologize for the low-level question, still very much learning this.

Sharktopus
Aug 9, 2006

Sparta posted:

How to represent it in python/django (getting user input I figure would depend on how it's represented).

I apologize for the low-level question, still very much learning this.

How about a dict of lists?

{
'a': [True, False],
'b': [True, False],
'c': [1, 2, 3],
'd': ['a', 'b', 'c']
}

MonkeyMaker
May 22, 2006

What's your poison, sir?

gmq posted:

Are there any resources (like the Django Book) that explain how to use the class-based generic views and their templates?

I'm stuck trying to override DetailView to add extra info to the view. :smith:

EDIT: Nevermind, I ended up creating a view instead of using a generic one.

CBVs are really simple once you get down their basic API. But, sadly, there aren't good docs for it yet.

code:
from django.views.generic import DetailView

from myapp.models import MyModel


class MyDetailView(DetailView):
    model = MyModel
    template_name = "path/to/my/detail.html"
And you're done. In the template's context, the selected object will be {{ object }}. By default DetailViews expect a slug or pk kwarg to come in. You can override that, but it's obviously easier not to.

deimos
Nov 30, 2006

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

MonkeyMaker posted:

CBVs are really simple once you get down their basic API. But, sadly, there aren't good docs for it yet.

code:
from django.views.generic import DetailView

from myapp.models import MyModel


class MyDetailView(DetailView):
    model = MyModel
    template_name = "path/to/my/detail.html"
And you're done. In the template's context, the selected object will be {{ object }}. By default DetailViews expect a slug or pk kwarg to come in. You can override that, but it's obviously easier not to.

Do not confound CBVs and G(eneric)CBVs, two different beasts altogether.

Sparta
Aug 14, 2003

the other white meat

Sharktopus posted:

How about a dict of lists?

{
'a': [True, False],
'b': [True, False],
'c': [1, 2, 3],
'd': ['a', 'b', 'c']
}

I can make a model out of a dict? I don't know what will be in it beforehand.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
We need to know more about the problem you're solving before we can do anything. What is a switch? What will it do?

hitze
Aug 28, 2007
Give me a dollar. No, the twenty. This is gonna blow your mind...

deimos posted:

Do not confound CBVs and G(eneric)CBVs, two different beasts altogether.
Why are they getting rid of FBVs :mad:

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

hitze posted:

Why are they getting rid of FBVs :mad:

Because the Django developers are terrible at making good decisions.

Sharktopus
Aug 9, 2006

Sparta posted:

I can make a model out of a dict? I don't know what will be in it beforehand.

So you need a way to represent it as a Django Model.

If you need the fieldnames or choice values to be searchable then it's a bit tricky.

However, if you just need a place to store and retrieve I would just serialize with whatever format you want (JSON, BSON, pickle) and stick it into a textfield.

You should write some methods on the model to get and set and handle the serialization for you. Then you can define a property and just get/set the dict right on the model. This will also easily let you change serialization formats or storage method in the future.

MonkeyMaker
May 22, 2006

What's your poison, sir?

hitze posted:

Why are they getting rid of FBVs :mad:

They're not. They're getting rid of the existing generic function-based views. You can write all the if-filled function-based views you want.

Hed
Mar 31, 2004

Fun Shoe
I'm working on a project for fun and I have a model in particular:
Python code:
class ChargeEntry(models.Model):
    """Time Charge Entry"""
    charge_code = models.ForeignKey(ChargeCode)
    hours = models.DecimalField(max_digits=3,decimal_places=1)
    charge_date = models.DateField(help_text="""Date of Charge""")
    user = models.ForeignKey(User)

    datetime_added = models.DateTimeField(auto_now_add=True)
    datetime_updated = models.DateTimeField(auto_now=True)

    objects = ChargeEntryManager()
I am finding myself repeating a pattern of:
  • go get ChargeEntry model in the period specified (usually a month)
  • bin the set into weeks
  • for each week show me the unique charge codes used
  • amalgamate this into a large view of the month with weekly grids (say, tables with each row as a charge code and the days of the week as the columns)

For viewing I have a view function that does a lot of the heavy lifting like steps 2-3 and packages this stuff into a custom data type that I have a custom templatetag pick up and parse.

Now I find myself thinking about the editing part, where I'd like to have all of this be a form where you can edit the values for a month. I could do a formset of formsets thing for the month-week-codes, but this sounds like an awful lot of repeating myself.

Should I load up the ChargeEntryManager with some custom functions to return packages of data in the format I need? I'm really having trouble wrapping my head around a container for all of these objects that I will eventually be slicing different ways... while not repeating myself and not making redundant queries to the db.

ufarn
May 30, 2009
I am having a weird problem on dotCloud, and I don't know if the fault is theirs or mine. One of the symptoms is that the static files don't work in 500 templates, whereas they do for 404. For 500, the {{ STATIC }} variable gives me /css/style.css, instead of the defined /static/css.style.css. Path is fine in 404, not so in 500.

Here are the two different templates; I don't think there is any logic about the two elsewhere in neither URLS.py nor views.py:

code:
{% extends 'base.html' %}

{% block title %}Page Not Found (404){% endblock %}

{% block content %}
    <div id="content">
        <span id="error">The page you looked could not be found.</span>
    </div>
{% endblock %}
code:
{% extends 'base.html' %}

{% block title %}Page Not Found (500){% endblock %}

{% block content %}
    <div id="content">
        <span id="error">An internal error happened.</span>
    </div>
{% endblock %}
base.html has static file references like <link rel="stylesheet" type="text/css" media="all" href="{{ STATIC_URL }}css/style.css" />.

Any idea what causes the error? I already get a database error, when I deploy on dotCloud, which is why I get the 500 error to begin with.

ufarn fucked around with this message at 17:09 on Jun 7, 2012

Yay
Aug 4, 2007
You don't get context processors in 500 responses* (so no MEDIA_URL, STATIC_URL, request etc), so mostly you want to avoid extending a template, and hard code "all the things"

* This is partly because the context processor itself may be throwing the exception, and partly because all kinds of other things could be. Too many moving parts.

Yay fucked around with this message at 18:13 on Jun 7, 2012

ufarn
May 30, 2009

Yay posted:

You don't get context processors in 500 responses* (so no MEDIA_URL, STATIC_URL, request etc), so mostly you want to avoid extending a template, and hard code "all the things"

* This is partly because the context processor itself may be throwing the exception, and partly because all kinds of other things could be. Too many moving parts.
Hardcoding the template fixed it. Thanks a million.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Apparently I'm the only person who keeps running into Django gotchas. It's awesome when trying to use transactions means that Django drops any exception in the function on the floor. Welp.

deimos
Nov 30, 2006

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

Suspicious Dish posted:

Apparently I'm the only person who keeps running into Django gotchas. It's awesome when trying to use transactions means that Django drops any exception in the function on the floor. Welp.

Yes, you're the unique snowflake that has run into a framework's warts, no one else ever has had issues with django ever. Solution Soon™. For development you can use this gist.

deimos fucked around with this message at 16:24 on Jun 8, 2012

repugnant
Jun 29, 2005

You can only think of me.

Cross-posting from StackOverflow - http://stackoverflow.com/questions/10953548/.

I'm having a problem similar to nbv4's:

The difference is that his problem field, PosBase, is visible, but mine is not. It is a required field, so I populate it in a call to add_fields() and use the HiddenInput widget on it.

But the form validation always fails because Django it assumes the formset is only partially filled out. I've been banging my head against this problem all day - is there a different way I should be handling this nested formset?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

deimos posted:

Yes, you're the unique snowflake that has run into a framework's warts, no one else ever has had issues with django ever.

I just seem to keep running into them every day, and I want to tear my hair out. How can anyone think this framework is a good idea if it makes you do you extra work to debug an issue like this?

deimos posted:

Solution Soon™. For development you can use this gist.

Four years? Does nobody ever use transactions or something?

how!!
Nov 19, 2011

by angerbot

Suspicious Dish posted:

I just seem to keep running into them every day, and I want to tear my hair out. How can anyone think this framework is a good idea if it makes you do you extra work to debug an issue like this?


Four years? Does nobody ever use transactions or something?

In the four years I've done django development, I've never had to handle transactions manually. I've only ever seen it done as a hack to get around some other bug in the code base.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

how!! posted:

In the four years I've done django development, I've never had to handle transactions manually. I've only ever seen it done as a hack to get around some other bug in the code base.

Is the stupidity of ManyToManyField requiring a model to be in the database and to have a PK considered a bug to you?

how!!
Nov 19, 2011

by angerbot

Suspicious Dish posted:

Is the stupidity of ManyToManyField requiring a model to be in the database and to have a PK considered a bug to you?

It may be a little annoying (and easy to work around), but what does that have to do with manual transaction management?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
I set up a transaction, create my model, set up M2M entries and all that, then validate the model afterwards (validation is complex which relies on a lot of things, so I can't effectively do it pre-creation) commit if successful, rollback if failed.

epswing
Nov 4, 2003

Soiled Meat
Ok, hopefully this makes sense...

In the template...

Python code:
{% for form in formset %}
	{{ form.id }}
	{{ form.name }}
	{{ form.amount }}
	{{ form.DELETE }}
{% endfor %}
which gives me the fields in each form, and a nice deletion checkbox.

In the view...

Python code:
if formset.is_valid():
	formset.save() # this works
	for form in formset.deleted_forms:
		form.instance.delete() # fails here
The error is "object can't be deleted because its id attribute is set to None."

When I take a look at the html generated by {{ form.id }} I now realize that this isn't the id of the object, it's the id django uses to keep track of the forms in its formset (something like <input type="hidden" name="myobj_set-1-id" value="2" id="id_myobj_set-1-id" /> for the 2nd form in the formset, note value="2"), essentially 'hiding' the id of the object.

How should I handle this?

how!!
Nov 19, 2011

by angerbot
if I'm not mistaken, you don't need to manually iterate over all the forms in a formset to delete them, that part is handled by formset.save()

epswing
Nov 4, 2003

Soiled Meat

how!! posted:

if I'm not mistaken, you don't need to manually iterate over all the forms in a formset to delete them, that part is handled by formset.save()

Oh, drat...thanks!

fuf
Sep 12, 2004

haha
The Django Book is broken up into paragraphs, each of which has its own comments. How do you think they did that?

I'd like to do something similar with some papers that are about 5000 words each. I've never really thought about how to deal with large volumes of text before. What would the database look like? Do you think each paragraph should be stored separately? How would I make sure they're in the right order? What about preserving italics, or even footnotes?

Any general advice would be appreciated before I start fumbling towards a solution.

fuf fucked around with this message at 12:31 on Jun 11, 2012

Captain Capacitor
Jan 21, 2008

The code you say?
Does anyone have any advice/articles/gists on how to do nested forms? Be it inline forms or whatever. Only dealing with one-to-many relationships.

ufarn
May 30, 2009
This is an old bug that has resurfaced: when I refresh my local runserver instance by pressing F5 three times, I get a huge database error. I think I caught the entire error message, but it's a huge mess. Would love of anyone could shed some light on this, because I haven't the faintest idea what caused this, and when it happened in my commit history:

http://dpaste.com/757602/

It sounds a lot like this and this.

ufarn fucked around with this message at 16:38 on Jun 11, 2012

Jo
Jan 24, 2005

:allears:
Soiled Meat

ufarn posted:

This is an old bug that has resurfaced: when I refresh my local runserver instance by pressing F5 three times, I get a huge database error. I think I caught the entire error message, but it's a huge mess. Would love of anyone could shed some light on this, because I haven't the faintest idea what caused this, and when it happened in my commit history:

http://dpaste.com/757602/

It sounds a lot like this and this.

Out of curiosity, do you have a Windows firewall running or Execution Prevention jumping in and blocking ports? Maybe some other sort of software security which is killing connections?

ufarn
May 30, 2009

Jo posted:

Out of curiosity, do you have a Windows firewall running or Execution Prevention jumping in and blocking ports? Maybe some other sort of software security which is killing connections?
Just tried this on my Ubuntu installation with postgreSQL (instead of windows with MySQL), and I get the same error. Looks like it's something in the code.

Here's a much more readable dpaste of what happens on the Ubuntu computer: http://dpaste.com/759013/.

EDIT: Sounds like this is a :airquote:known problem:airquote::

ufarn fucked around with this message at 12:49 on Jun 13, 2012

deimos
Nov 30, 2006

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

ufarn posted:

EDIT: Sounds like this is a :airquote:known problem:airquote::

It doesn't seem like a DB error, seems like the naive implementation of the development http server having timing issue. If your requests take long enough it'll throw that error.

Mulozon Empuri
Jan 23, 2006

A bunch of videos from djangocon europe 2012. I do love that they tape all the talks.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
Does anyone have any opinions of Mezzanine (https://github.com/stephenmcd/mezzanine) they could share? Obviously I'll install / try it out, but if the mere mention of it makes you all recoil in horror, I'll save that time =)

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
Just starting out using crispy-forms, it's a pretty cool form handler, although I am overloading the templates for it so I can control my display a little more.

Forewarning, I was having a dumb moment where I just couldn't figure out whether it was actually reading from the template I thought it was. I was deliberately breaking the template and it would throw exceptions, but then when I was rendering it properly it wasn't showing my changes. Turns out crispy-forms caches the templates, had to reload the dev server to see changes. Don't code tired, otherwise you waste ages chasing stuff like this.

Adbot
ADBOT LOVES YOU

Master Stur
Jun 13, 2008

chasin' tail
So I just started learning this stuff and I'm new to apache/webservers in general.

I read and wrote up the django tutorial app on their website, the one that makes a simple admin interface and lets you create polls. I want to eventually put stuff out on a webserver so I made a VM using the bitnami djangostack and copied the tutorial app over there. Everything is working correctly except the actual poll details and results page. The index of polls works, but when you click a poll I get a "URL not found" error although the same code works perfectly using the internal test server on my regular pc.

This is the error that apache puts in the log:

code:
[Mon Jun 18 20:01:51 2012] [error] [client ip] File does not exist: /opt/bitnami/apps/django/django_projects/mysite/polls/1, referer: [url]http://ip/mysite/polls/[/url]
I'm thinking it has something to do with documentroot or wsgi aliases not set up correctly? Apache tries to find the URL to whatever I set the documentroot as, but no matter where I point it to I get the same error.

edit: Nevermind I figured it out... It was as obvious as I suspected :saddowns:

I had my wsgi alias set as /mysite /directory/path after following the djangostack quick start guide and bumming their .conf and .wsgi files for my purposes. I changed it back to / /directory/path and boom!

I really need to read up more on this stuff before jumping in.

Master Stur fucked around with this message at 02:36 on Jun 19, 2012

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