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
Cat Plus Plus
Apr 8, 2011

:frogc00l:
Well, first of all, you don't have any relation set up. Submission should have ForeignKey to User, not repeated steamID. Also, model names are singular by convention (single object is a Thing, not many Things).

Python code:
class Submission(models.Model):
     # ...
     user = models.ForeignKey(User)
Then you do it using reverse relationship property. Something like this:

Python code:
user = User.objects.get(steamID = '...')
submissions = user.submission_set.all()
Also take a look at select_related, because you might need it.

e: Now that I think about it your query will work as well, if you don't want to follow the relation backwards. user__steamID just requires user to be a foreign key.

Cat Plus Plus fucked around with this message at 21:27 on Oct 14, 2012

Adbot
ADBOT LOVES YOU

205b
Mar 25, 2007

Do the as_p(), as_ul(), etc. methods of a formset not output non-form errors? I could always stick them in the template manually but I thought I'd make sure this was the intended behavior.

Jo
Jan 24, 2005

:allears:
Soiled Meat
As evidenced by some posting earlier in this thread, I've had a few chances to cut my teeth on Django, but I'm not sure how cozy I am with it. I have an interview and possible job coming up, so for those of you who work with Django professionally, what sort of things do you really expect a coworker to know? Any interview questions you'd find worth mentioning?

EDIT: For clarity, I'm not asking for full start-to-finish Django lessons, but something to gauge proficiency would be handy. "If you had to do X with the ORM, how would you do it? If you had to use X auth, how? Why do you do X when Y?" Things of that sort.

Jo fucked around with this message at 19:35 on Oct 23, 2012

MonkeyMaker
May 22, 2006

What's your poison, sir?

Jo posted:

As evidenced by some posting earlier in this thread, I've had a few chances to cut my teeth on Django, but I'm not sure how cozy I am with it. I have an interview and possible job coming up, so for those of you who work with Django professionally, what sort of things do you really expect a coworker to know? Any interview questions you'd find worth mentioning?

EDIT: For clarity, I'm not asking for full start-to-finish Django lessons, but something to gauge proficiency would be handy. "If you had to do X with the ORM, how would you do it? If you had to use X auth, how? Why do you do X when Y?" Things of that sort.

  • Do you understand the reasoning behind model managers and when would you create one?
  • If you need to make sure that two form-submitted values are the same (or some how relate to each other in a predictable way), how would you go about that?
  • What's the easiest way to fill out a slug field on a model?
  • Why would someone use South?
  • I need a templatetag to show a user's profile info on any page. What kind of tag would you create?
  • If I have two templates, base.html and home.html, and I want to extend the content of a block on base.html in home.html (and home.html already extends base.html), what would I do in the template?
  • What's the difference between STATIC_ROOT and STATICFILES_DIRS in settings.py?
  • How many tests have you written?

These are the first things that come to mind that I've had to deal with with clients/projects and new hires.

Jo
Jan 24, 2005

:allears:
Soiled Meat

MonkeyMaker posted:

  • Do you understand the reasoning behind model managers and when would you create one?
  • If you need to make sure that two form-submitted values are the same (or some how relate to each other in a predictable way), how would you go about that?
  • What's the easiest way to fill out a slug field on a model?
  • Why would someone use South?
  • I need a templatetag to show a user's profile info on any page. What kind of tag would you create?
  • If I have two templates, base.html and home.html, and I want to extend the content of a block on base.html in home.html (and home.html already extends base.html), what would I do in the template?
  • What's the difference between STATIC_ROOT and STATICFILES_DIRS in settings.py?
  • How many tests have you written?

These are the first things that come to mind that I've had to deal with with clients/projects and new hires.

Outstanding! Thank you. This is very helpful.

Victor
Jun 18, 2004
I'm designing some models and would like the following four columns to be in pretty much every table:
code:
input_person_fk
input_date
update_person_fk
update_date
What is the best way to do this in Django? I know I can do
code:
input_date = models.TimeField(default=datetime.now)
, but I'm not sure about *_person_fk, or update_*. Passing the request object to the model (if that's possible) seems ugly. I suppose an alternative might be to somehow tell the DB what the person_pk is for the current connection, but I'm not sure how well that would work with connection pooling. I'm using PostgreSQL, which doesn't seem to have a direct analog to MSSQL's CONTEXT_INFO(). custom_variable_classes seems like an option, but an ugly one—and the documentation doesn't even specify the scope of the variables. I suppose one could maintain a table of open connections to the DB and what person_fk they're associated with, and update that table on authentication. That seems ugly, as well.

Also, is there a good way to add these fields to every model without having copy/paste?

Finally, is there a nice way to change the default primary key name Django gives from id to table_name_pk? Other than doing this for each table:
code:
person_pk = models.AutoField(primary_key=True)

Victor
Jun 18, 2004
Ok I figured out how to do part of what I wanted, from here:
code:
from django.db import models
from datetime import datetime
from django.db.models.signals import class_prepared

def add_field(sender, **kwargs):
    # does not work; the class has already had a PK column added by this point
    #models.AutoField(primary_key=True).contribute_to_class(sender, "%s_pk" % sender.__name__.lower())
    models.DateTimeField(default=datetime.now).contribute_to_class(sender, 'input_date')

class_prepared.connect(add_field)

class Person(models.Model):
    person_pk = models.AutoField(primary_key=True)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

class Object(models.Model):
    object_pk = models.AutoField(primary_key=True)
    text = models.TextField()
code:
$ ./manage.py sql data
BEGIN;
CREATE TABLE "data_person" (
    "person_pk" serial NOT NULL PRIMARY KEY,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(30) NOT NULL,
    "input_date" timestamp with time zone NOT NULL
)
;
CREATE TABLE "data_object" (
    "object_pk" serial NOT NULL PRIMARY KEY,
    "text" text NOT NULL,
    "input_date" timestamp with time zone NOT NULL
)
;
COMMIT;

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

Victor posted:

code:
input_date = models.TimeField(default=datetime.now)
use the auto_now or auto_now_add parameters for this

quote:

Also, is there a good way to add these fields to every model without having copy/paste?
Define an abstract base class for the models to inherit from.

quote:

Finally, is there a nice way to change the default primary key name Django gives from id to table_name_pk? Other than doing this for each table:
code:
person_pk = models.AutoField(primary_key=True)

No, not really.

Victor
Jun 18, 2004
Thanks; I'll have to decide whether or not I like the fact that using auto_now will write a value on insert—meaning it will always look like a record was updated. (One can always test for insert_date == update_date, of course.)

quote:

Define an abstract base class for the models to inherit from.
I tried this, but I wasn't a big fan of the auditing columns coming at the beginning of the class instead of the end.

Thermopyle
Jul 1, 2003

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

Victor posted:

Ok I figured out how to do part of what I wanted, from here:

FYI, you can use [ code=Python ] like this:

Python code:
from django.db import models
from datetime import datetime
from django.db.models.signals import class_prepared

def add_field(sender, **kwargs):
    # does not work; the class has already had a PK column added by this point
    #models.AutoField(primary_key=True).contribute_to_class(sender, "%s_pk" % sender.__name__.lower())
    models.DateTimeField(default=datetime.now).contribute_to_class(sender, 'input_date')

class_prepared.connect(add_field)

class Person(models.Model):
    person_pk = models.AutoField(primary_key=True)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

class Object(models.Model):
    object_pk = models.AutoField(primary_key=True)
    text = models.TextField()

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

Victor posted:

I tried this, but I wasn't a big fan of the auditing columns coming at the beginning of the class instead of the end.

You mean having to define the base class above the child classes in models.py? Define it somewhere else and import it.

Victor
Jun 18, 2004

Thermopyle posted:

FYI, you can use [ code=Python ] like this:
Thanks; I'm not sure that the python option existed when I last used [code] tags.

Sailor_Spoon posted:

You mean having to define the base class above the child classes in models.py? Define it somewhere else and import it.
No, I mean in the actual DB table. If I do a select *, I'd like to have the columns come out in a sensible order. I suppose I could futz with the output of ./manage.py app_name sql and run it myself, instead of using ./manage.py syncdb, but that just seems ugly.

good jovi
Dec 11, 2000

'm pro-dickgirl, and I VOTE!

Victor posted:

No, I mean in the actual DB table. If I do a select *, I'd like to have the columns come out in a sensible order. I suppose I could futz with the output of ./manage.py app_name sql and run it myself, instead of using ./manage.py syncdb, but that just seems ugly.

Oh. I guess I use Django so I don't ever have to care about stuff like that.

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
wait nm, idiot I am.

Jo
Jan 24, 2005

:allears:
Soiled Meat

Victor posted:

Thanks; I'm not sure that the python option existed when I last used [code] tags.

No, I mean in the actual DB table. If I do a select *, I'd like to have the columns come out in a sensible order. I suppose I could futz with the output of ./manage.py app_name sql and run it myself, instead of using ./manage.py syncdb, but that just seems ugly.

There's a general philosophy surrounding the Django ORM (or, really, most ORMs) that one should be database agnostic. It defeats the purpose of using an ORM if you're going to get down and dirty with the database details. I'm sure you have your reasons for wanting this sort of control. If you can share these reasons, I think we might be able to find a more workable solution. Are you interfacing with an already existing database? Or do you have another application which is going to be working with the same database that Django is working on? :gonk:

Victor
Jun 18, 2004

Jo posted:

There's a general philosophy surrounding the Django ORM (or, really, most ORMs) that one should be database agnostic. It defeats the purpose of using an ORM if you're going to get down and dirty with the database details. I'm sure you have your reasons for wanting this sort of control. If you can share these reasons, I think we might be able to find a more workable solution. Are you interfacing with an already existing database? Or do you have another application which is going to be working with the same database that Django is working on? :gonk:
I'm not just going to be using the DB as a dumb data store; I'm also going to be doing ad-hoc analysis on it. I'll be using SQL for that ad-hoc analysis, because SQL is a tremendously powerful language. But the thing I'm talking about—order of columns—should never be relevant to an ORM, other than creation of the table. Any ORM that does select * should be taken out and shot.

Your :gonk: has me a bit concerned. Is it particular to Django that it doesn't play well with others? Or were you just talking about the general annoyance of having to make one platform/framework/whatever you want to call it, play well with another?

I just realized that I could perhaps do this through setattr, by passing the fields to the base, abstract class's ctor, so that it could sandwich those with a properly-named PK field and the input/update user/name. Seems ugly, though. Or perhaps there's a way to take a dictionary and merge it with a class's attributes. Haven't done anything particularly fancy with Python yet.

Victor fucked around with this message at 18:20 on Oct 24, 2012

My Rhythmic Crotch
Jan 13, 2011

If I want to dynamically generate or update javascript based on model content (so I don't have to update my javascript if fields are added/removed from models) what kind of options do I have? My google-fu is not revealing much. Of course I understand how to pass a single variable from a template into a script, but doing that for a whole lot of content seems like a bad idea.

IsotopeOrange
Jan 28, 2003

My Rhythmic Crotch posted:

If I want to dynamically generate or update javascript based on model content (so I don't have to update my javascript if fields are added/removed from models) what kind of options do I have? My google-fu is not revealing much. Of course I understand how to pass a single variable from a template into a script, but doing that for a whole lot of content seems like a bad idea.

You could try having your javascript fields be conditional based on some variables set by a smaller, inline script in the header. Then you could set those variables using the template logic in the inline script. On .load() or whatever your javascript should behave accordingly.

However it sounds like you might want static javascript based on your models.py, or more specifically your database schema. In that case you're probably better off writing a small script that generates that static javascript from a template beforehand. There's nothing stopping you from using templates 'offline' for preprocessing.

Suspicious Dish
Sep 24, 2011

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

My Rhythmic Crotch posted:

If I want to dynamically generate or update javascript based on model content (so I don't have to update my javascript if fields are added/removed from models) what kind of options do I have? My google-fu is not revealing much. Of course I understand how to pass a single variable from a template into a script, but doing that for a whole lot of content seems like a bad idea.

This is a terrible idea. Don't do this.

MonkeyMaker
May 22, 2006

What's your poison, sir?

My Rhythmic Crotch posted:

If I want to dynamically generate or update javascript based on model content (so I don't have to update my javascript if fields are added/removed from models) what kind of options do I have? My google-fu is not revealing much. Of course I understand how to pass a single variable from a template into a script, but doing that for a whole lot of content seems like a bad idea.

Models have a `__dict__` method that'll return a dict of their content, but it's not really useful as JSON since simplejson can't handle M2M and the like. I'd suggest setting up some ad hoc views with Django's serializer or use something like Tastypie or Django-REST-Framework. I'd recommend the latter over the former if you're not awesome at grokking fairly large, verbose, and complex Python source code.

Victor
Jun 18, 2004

My Rhythmic Crotch posted:

If I want to dynamically generate or update javascript based on model content (so I don't have to update my javascript if fields are added/removed from models) what kind of options do I have? My google-fu is not revealing much. Of course I understand how to pass a single variable from a template into a script, but doing that for a whole lot of content seems like a bad idea.
Can your template dump a list of model fields somewhere, as a javascript array? Then your javascript iterates through the array, instead of being hardcoded to field names.

Jo
Jan 24, 2005

:allears:
Soiled Meat

Victor posted:

I'm not just going to be using the DB as a dumb data store; I'm also going to be doing ad-hoc analysis on it. I'll be using SQL for that ad-hoc analysis, because SQL is a tremendously powerful language. But the thing I'm talking about—order of columns—should never be relevant to an ORM, other than creation of the table. Any ORM that does select * should be taken out and shot.

Your :gonk: has me a bit concerned. Is it particular to Django that it doesn't play well with others? Or were you just talking about the general annoyance of having to make one platform/framework/whatever you want to call it, play well with another?

I just realized that I could perhaps do this through setattr, by passing the fields to the base, abstract class's ctor, so that it could sandwich those with a properly-named PK field and the input/update user/name. Seems ugly, though. Or perhaps there's a way to take a dictionary and merge it with a class's attributes. Haven't done anything particularly fancy with Python yet.

Clarifying the gonk: There are two points of concern, first is that Django will be making some changes to the names of the columns inside the database. If memory serves, the app MyApp with object Book will have a table named myDjangoProject_MyApp_Book, or something to this effect. (I'll let another more experienced Djangoer correct me.) It's not a huge encumbrance, just be careful when you perform your selects. Second, I gonked because I thought there would be simultaneous access and modification by an outside application, which seems like a bad thing to do. I'm assuming that analytics are a mostly read operation, so that shouldn't cause problems.

IsotopeOrange
Jan 28, 2003

Victor posted:

I'm not just going to be using the DB as a dumb data store; I'm also going to be doing ad-hoc analysis on it. I'll be using SQL for that ad-hoc analysis, because SQL is a tremendously powerful language. But the thing I'm talking about—order of columns—should never be relevant to an ORM, other than creation of the table. Any ORM that does select * should be taken out and shot.

Your :gonk: has me a bit concerned. Is it particular to Django that it doesn't play well with others? Or were you just talking about the general annoyance of having to make one platform/framework/whatever you want to call it, play well with another?

I just realized that I could perhaps do this through setattr, by passing the fields to the base, abstract class's ctor, so that it could sandwich those with a properly-named PK field and the input/update user/name. Seems ugly, though. Or perhaps there's a way to take a dictionary and merge it with a class's attributes. Haven't done anything particularly fancy with Python yet.

If you really don't want to work with the Django ORM there's nothing stopping you from using the excellent SQLAlchemy for your database needs and just using Django for routing / tempates / etc.

My Rhythmic Crotch
Jan 13, 2011

Suspicious Dish posted:

This is a terrible idea. Don't do this.
Care to say why or would you prefer to remain vague?

Suspicious Dish
Sep 24, 2011

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

My Rhythmic Crotch posted:

Care to say why or would you prefer to remain vague?

I'm not sure what kind of JavaScript you want to generate, since your question is a bit vague itself. From my initial reading, I somehow came to the conclusion you wanted to generate the model description (this is a StringField, this is an IntField) and use it somehow in JavaScript. I have no idea why I came to that conclusion, so sorry.

If you want to make it easy to read your model by JavaScript, just write a JSON serializer method, and use the model client-side. You can do this by grabbing the proper data with AJAX, or embedding it into a variable by emitting an inline script tag. You shouldn't be generating JavaScript, but instead JSON.

More information about your use case would allow me to give you better ideas.

My Rhythmic Crotch
Jan 13, 2011

Didn't mean to come off like a a jerk so yes, I can give you more details.

Basically I would ultimately like it if, from some kind of admin interface, new fields could be added to a model schema. The models in question get manipulated through javascript editable grids, and get dumped to CSV, XLS and PDF. So from the admin interface, the user needs to be able to define column descriptions, column widths, etc for use with the editable grid and file exports.

That's a lofty goal (for me anyway). So my intermediate goal is just to transport the column descriptions and column widths from the back end to javascript. Then at least that data can be entered just once and I won't have to propagate any changes to several javascript files.

edit, I do have a json API in place already.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
That first thing (the ultimate goal of having random users manipulate databases) sounds like a terrible idea for me for all sorts of reasons. It's certainly not a good fit for Django, so I'd think about using something like SQLAlchemy for that instead, which might be a bit more amenable. Django has the idea that the set of models throughout an application is constant pretty deeply embedded in its brains, so creating tables on the fly is going to break it.

As for the first one, export your model description as JSON, and then add something to read it. You want to know about Model._meta, but as far as I'm aware it's more or less undocumented, so you're on your own with that one. Open up a Django shell and use dir and help to navigate around.

My Rhythmic Crotch
Jan 13, 2011

Well it would not be just any random user, it would be a one-time "setup your app" kind of thing carried out by whoever the customer chooses as their admin. But I agree and I can understand that Django is not meant to be used in this way. I'm trying to give the customer the flexibility to customize without having to modify source, but it just might not be possible. So anyway, yeah, that's the idea. Thanks for the thoughts, I appreciate it.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
I have never seen a single one of those that has turned out well, although many have tried. That should be a warning sign.

MonkeyMaker
May 22, 2006

What's your poison, sir?
Wouldn't it be easier to not worry about modifying model-models and just build a JSON interpreter that creates models for you? I built something like that for creating forms on the fly. Shouldn't be too hard.















Doesn't mean it's a good idea, though.

latexenthusiast
Apr 22, 2008
This is more of a theoretical question that probably demonstrates what a terrible programmer I am, but it may just be due to the fact that I'm a novice.

Ok, let's say that I'm keeping track of the performance of a team of basketball players over a series of games (in a single season with no trades--my code probably wouldn't work otherwise). As it is right now, my code is something like this:
Python code:
class Organization(models.Model):
    name = models.CharField(max_length=100)
    city = models.CharField(max_length=100)

class School(Organization):
    pass

class Team(Organization):
    pass

class Stadium(Orgamization):
    pass

class Player(models.Model):
    name = models.CharField(max_length=100)
    team = models.ForeignKey(Team)
    alma_mater = models.ForeignKey(School)
    birthday = models.DateField()
    height = models.IntegerField()

class PlayerResults(models.Model):
    player = models.ForeignKey(Player)
    
    score = models.IntegerField()
    assists = models.IntegerField()
    rebounds = models.IntegerField()
    
    field_goal_attempts = models.IntegerField()
    field_goal_successes = models.IntegerField()
    
    free_throw_attempts = models.IntegerField()
    free_throw_successes = models.IntegerField()
    
    fouls = models.IntegerField()
    technical_fouls = models.IntegerField()
    
    game_time = models.IntegerField()

class Game(models.Model):
    date = models.DateField()
    location = models.ForeignKey(Stadium)
    
    winner = models.ForeignKey(Team)
    winner_score = models.IntegerField()
    loser = models.ForeignKey(Team)
    loser_score = models.IntegerField()
    
    player_results = models.ManyToManyField(PlayerResults)
So that might not be the most efficient way of doing things for a program that actually tracks player stats in basketball--the real program does something so horrible that I don't want to admit to it in a public forum. Just trust me, it's theoretically similar. In any case, what I'm wondering about is the PlayerResults class. It seems like there should be some better way of populating instances of the Game class with the each player's performance without cluttering up the database with tons of PlayerResults, but I don't know how else to do this. Since I'm just entering this stuff from the Django admin page, it's going to look really messy really quickly because in all likelihood none of the PlayerResults will be used more than once. Please help!

MonkeyMaker
May 22, 2006

What's your poison, sir?

I'd probably start with something like:

Python code:
class PointType(models.Model):
    name = models.CharField(max_length=255)


class PlayerActions(models.Model):
    player = models.ForeignKey(Player, related_name="performances")
    point_amount = models.IntegerField()
    point_type = models.ForeignKey(PointType)
    game = models.ForeignKey("Game", related_name="performances")


class Game(models.Model):
    date = models.DateField()
    location = models.ForeignKey(Stadium)
    
    winner = models.ForeignKey(Team)
    winner_score = models.IntegerField()
    loser = models.ForeignKey(Team)
    loser_score = models.IntegerField()

    game_time = models.IntegerField()  # maybe hold onto num. of secs/mins?
Then I can select point types that are the same across different players and games, etc.

latexenthusiast
Apr 22, 2008

MonkeyMaker posted:

I'd probably start with something like:

Then I can select point types that are the same across different players and games, etc.
This looks like a more elegant solution, and will probably make managing data in the admin section easier. It's been quite awhile since I've touched Django, so I'm relearning how to make database queries. The only problem I see with this is that it's not going to be quite as straightforward for me, but I'm sure I'll manage. Thanks!

MonkeyMaker
May 22, 2006

What's your poison, sir?
If any of you are interested on Django's Form Wizard views, I just posted about how to use them. http://brack3t.com/not-exactly-tim-the-enchanter.html

Mulozon Empuri
Jan 23, 2006

MonkeyMaker posted:

If any of you are interested on Django's Form Wizard views, I just posted about how to use them. http://brack3t.com/not-exactly-tim-the-enchanter.html

I keep reading that logo as Gracket.

MonkeyMaker
May 22, 2006

What's your poison, sir?

Mulozon Empuri posted:

I keep reading that logo as Gracket.

but...but...but, it's MADE WITH BRACKETS! it's so meta!

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

MonkeyMaker posted:

but...but...but, it's MADE WITH BRACKETS! it's so meta!

Don't you mean |\/|eta?

Good article, btw! Can't wait for your new getting started videos as well. Will there be one on unit testing in python / django? As a stupid django newbie, I'm overwhelmed with opinions and options from google searching, so I need someone to just tell me what to do!

MonkeyMaker
May 22, 2006

What's your poison, sir?

Lumpy posted:

Don't you mean |\/|eta?

Good article, btw! Can't wait for your new getting started videos as well. Will there be one on unit testing in python / django? As a stupid django newbie, I'm overwhelmed with opinions and options from google searching, so I need someone to just tell me what to do!

Testing will be there from (almost) the beginning. Nothing fancy but there'll be unit tests and coverage.py.

Captain Capacitor
Jan 21, 2008

The code you say?

MonkeyMaker posted:

Testing will be there from (almost) the beginning. Nothing fancy but there'll be unit tests and coverage.py.

I for one will welcome a good introduction to class-based views. I'm old school Django and I just can't get the hang of them.

Adbot
ADBOT LOVES YOU

MonkeyMaker
May 22, 2006

What's your poison, sir?

Captain Capacitor posted:

I for one will welcome a good introduction to class-based views. I'm old school Django and I just can't get the hang of them.

What has you flummoxed? They're (honestly) really simple. Say you want to show a particular blog post by slug.

Old way:

code:
url("blog/(?P<slug>[-\w]+)/$", "blogpost", name="post")
code:
def blogpost(request, slug):
    post = get_object_or_404(BlogPost, slug=slug)
    return render("blog/post.html", {"post": post})
(obviously a bit simplified)

CBV:

code:
url("blog/(?P<slug>[-\w]+)/$", BlogPostDetailView.as_view(), name="post")
code:
class BlogPostDetailView(DetailView):
    model = BlogPost
    template_name = "blog/post.html"
Since CBVs assume that, on a DetailView, UpdateView, or DeleteView, that you'll pass in a slug or pk argument that'll resolve to that field on the model. You can override all of these, of course.

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