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
ufarn
May 30, 2009

Yay posted:

But much of the basics are the same (date oriented, facted content), only posts don't go in categories, they go in threads, and then the threads go in categories. Throw in multiple users, and you've got the rudimentary beginnings of a simple forum. You can probably get that far with the ORM and generic views.
I know how similar they are, it's just that I've already tortured myself by making one in ExpressionEngine, and I need something new to drive the motivation.

Right now I'm reading djangobook in the hope of being able to create something by myself at some point.

Adbot
ADBOT LOVES YOU

Jabab
Feb 25, 2006
A couple of questions on how best to do things in django.

I'm using model inheritance:
code:
class Article(models.Model):
    author = models.CharField(max_length=100)
    title = models.CharField(max_length=150)
    body = tinymce_models.HTMLField()

class NewsArticle(Article):
    categories = models.ManyToManyField("NewsArticleCategory")
        
class Review(Article):
    product = models.CharField(max_length=150)
    categories = models.ManyToManyField("ReviewCategory")
In my view i've got:
code:
def index(request, page=1):
    home_articles_raw = Article.objects.raw("""SELECT ar.*, na.article_ptr_id as is_news, rev.article_ptr_id as is_review
        FROM `cms_article` ar
        LEFT JOIN `cms_newsarticle` na ON ar.id = na.article_ptr_id
        LEFT JOIN `cms_review` rev ON ar.id = rev.article_ptr_id""")
    all_home_articles = []
    for article in home_articles_raw:
        if article.is_news:
            article.link = '/news/' + str(article.id)
        if article.is_review:
            article.link = '/review/' + str(article.id)
        all_home_articles.append(article)
Is there a better way of doing this?

Also there's some stuff that's on every page, like news articles in a sidebar. So I have
code:
latest_news = NewsArticle.objects.all().order_by('-pub_date')[:5] 

outside of a function in my views.py and just pass that into every render_to_response . Is there a better or more convenient way of doing that?

Yay
Aug 4, 2007

Jabab posted:

Also there's some stuff that's on every page, like news articles in a sidebar. So I have [...] outside of a function in my views.py and just pass that into every render_to_response . Is there a better or more convenient way of doing that?
That's the kind of thing templatetags are for.

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

Jabab posted:

code:
def index(request, page=1):
    home_articles_raw = Article.objects.raw("""SELECT ar.*, na.article_ptr_id as is_news, rev.article_ptr_id as is_review
        FROM `cms_article` ar
        LEFT JOIN `cms_newsarticle` na ON ar.id = na.article_ptr_id
        LEFT JOIN `cms_review` rev ON ar.id = rev.article_ptr_id""")
    all_home_articles = []
    for article in home_articles_raw:
        if article.is_news:
            article.link = '/news/' + str(article.id)
        if article.is_review:
            article.link = '/review/' + str(article.id)
        all_home_articles.append(article)
Is there a better way of doing this?

If you want to avoid raw sql, I believe you can name the child's ptr as such:

code:
class Article(models.Model):
    author = models.CharField(max_length=100)
    title = models.CharField(max_length=150)
    body = tinymce_models.HTMLField()

class NewsArticle(Article):
    base = models.OneToOneField(Article,parent_link=True,related_name="News")
    categories = models.ManyToManyField("NewsArticleCategory")
        
class Review(Article):
    base = models.OneToOneField(Article,parent_link=True,related_name="Review")    
    product = models.CharField(max_length=150)
    categories = models.ManyToManyField("ReviewCategory")
then in the view, just for example, you can distinguish like so

code:
for ar in Article.objects.all():
    try:
        article.link = ar.News.id
    except AttributeError:
        article.link = ar.Review.id
However, I wouldn't do this in the view, I would pass the results to the template and loop through them in there and use the {% url %} template tag to display the link. Look at naming your urls.

http://docs.djangoproject.com/en/dev/topics/http/urls/#naming-url-patterns

Basically it would look something like this in your template
code:
{% for ar in articles %}
    {% if ar.News %}
    <a href="{% url news_article ar.News.id %}">{{ ar.title }}</a>
    {% else %}
    <a href="{% url review_article ar.Review.id %}">{{ ar.title }}</a>
    {% endif %}
{% endfor %}
that's just how I would do things anyway.

Yay
Aug 4, 2007

Wulfeh posted:

Basically it would look something like this in your template
code:
{% for ar in articles %}
    {% if ar.News %}
    <a href="{% url news_article ar.News.id %}">{{ ar.title }}</a>
    {% else %}
    <a href="{% url review_article ar.Review.id %}">{{ ar.title }}</a>
    {% endif %}
{% endfor %}
that's just how I would do things anyway.
'Better' still, move the object testing into get_absolute_url and wire up permalink decorators, which leaves both your views and your template clean and maintainable.

(I ignored the question about how to improve the view originally, as I was focusing on the SQL and what it'd return, rather than what it was actually used for. Sorry!)

Jabab
Feb 25, 2006
Thanks Yay, I ended up defining get_absolute_url in Article, NewsArticle, and Review.
code:
class Article(models.Model):
    author = models.CharField(max_length=100)
    title = models.CharField(max_length=150)
    body = tinymce_models.HTMLField()
    @models.permalink
    def get_absolute_url(self):
        if self.is_news:
            return ('cms.views.news', [str(self.id)])
        else:
            return ('cms.views.review', [str(self.id)]) 
code:
class Review(Article):
    product = models.CharField(max_length=150)
    categories = models.ManyToManyField("ReviewCategory")
    def get_absolute_url(self):
        return ('cms.views.review', [str(self.id)])
I can now keep my raw SQL without having to iterate through everything or hit the database more than once, and have urls that aren't hardcoded. I use article.get_absolute_url in my template, saving doing {% if article.news %} messy stuff.

code:
def show_sidebar(context):
    latest_news = NewsArticle.objects.all().order_by('-pub_date')[:5]
    news_cats = NewsArticleCategory.objects.all()
    context['latest_news'] = latest_news
    context['news_cats'] = news_cats
    return context

register.inclusion_tag('sidebar.html', takes_context=True)(show_sidebar)
This is much better than passing in latest_news and news_cats into every render_to_response. Is there a one liner for:
code:
    context['latest_news'] = latest_news
    context['news_cats'] = news_cats
perhaps something like:
code:
context += {'latest_news': latest_news, 'news_cats': news_cats}

Wulfeh
Dec 1, 2005

The mmo worth playing: DAoC

quote:

Is there a one liner for:
code:
    context['latest_news'] = latest_news
    context['news_cats'] = news_cats
perhaps something like:
code:
context += {'latest_news': latest_news, 'news_cats': news_cats}

adding to a python dict object is just as easy as you thought

code:
context.update( {'latest_news': latest_new, 'news_cats': news_cats} )

Jabab
Feb 25, 2006

Wulfeh posted:

adding to a python dict object is just as easy as you thought

code:
context.update( {'latest_news': latest_new, 'news_cats': news_cats} )

Weird, I thought I tried this and the context only contained the 'updated' stuff. I must have mixed up variable names, because I tried it again and it works fine!

EDIT: Also I got rid of my raw SQL using select_related

Jabab fucked around with this message at 22:38 on Mar 13, 2011

HardCorey
Jan 11, 2010
I'm needing a little help setting up a django site for public consumption. The project looks great accessed on my machine via the built in webserver, but I'm having trouble viewing it on my hosting server. I have hosting through lithium hosting and I think their instructions are a little out of date. I set up the .htaccess file in the appropriate directory
code:
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE mysite1.settings
PythonOption django.root /mysite1
PythonDebug On
PythonPath "['/home/USERNAME/django-code/'] + sys.path"
# replace USERNAME with your shell username
SetEnv PYTHON_EGG_CACHE /home/USERNAME/.python-eggs/
# replace USERNAME with your shell username

I have my project files in the "django-code" directory and I'm assuming (maybe wrongly?) that this causes the mysite1 url to point to the right directory.

However when I navigate to myurl/mysite1 I get an error:

code:
ImportError: Could not import settings 'mysite1.settings' (Is it on sys.path? Does it have 
syntax errors?): No module named mysite1.settings
I'm fairly new to django so maybe I'm making a small error somewhere.

Yay
Aug 4, 2007
I've never used mod_python (it's deprecated and rubbisher), but I'm assuming [...]/django-code/ has a folder called 'mysite1' beneath it, with appropriate __init__.py?

HardCorey
Jan 11, 2010
yea I'm not sure. I just went ahead and switched hosting to one that officially supports django to save myself a headache.

nbv4
Aug 21, 2002

by Duchess Gummybuns
code:
ipdb> qs.values('user')
[{'user': 321}, {'user': 321}, {'user': 321}, {'user': 11}, {'user': 11}, {'user': 11}]
ipdb> qs.values('user').count()
6
ipdb> qs.values('user').distinct()
[{'user': 321}, {'user': 321}, {'user': 321}, {'user': 11}, {'user': 11}, {'user': 11}]
ipdb> qs.values('user').distinct().count()
2
Can anyone explain this?

Lamacq
Jun 15, 2001

Breezeblock RIP

nbv4 posted:

code:
ipdb> qs.values('user')
[{'user': 321}, {'user': 321}, {'user': 321}, {'user': 11}, {'user': 11}, {'user': 11}]
ipdb> qs.values('user').count()
6
ipdb> qs.values('user').distinct()
[{'user': 321}, {'user': 321}, {'user': 321}, {'user': 11}, {'user': 11}, {'user': 11}]
ipdb> qs.values('user').distinct().count()
2
Can anyone explain this?

I believe it's because the queryset, unless you tell it otherwise, will add the model's default Meta.ordering to its query, and behind the scenes whatever fields are in the Meta.ordering will be added to the query and thus to the DISTINCT clause and you won't get the results you expect. Try:

code:
qs.values('user').distinct().order_by()

duck monster
Dec 15, 2004

Whats peoples vibe on using passenger for serving django? The site seems to claim its a bit dicky, but people seem to be having good times with it too. Thoughts?

king_kilr
May 25, 2007
Wouldn't touch it. Just use mod_wsgi or gunicorn behind nginx and be happy.

ps: 1.3 is out

bitprophet
Jul 22, 2004
Taco Defender

duck monster posted:

Whats peoples vibe on using passenger for serving django? The site seems to claim its a bit dicky, but people seem to be having good times with it too. Thoughts?

Reasonably sure the only people using Passenger for its WSGI capabilities are those who want a single backend server running both Rails and Django child processes. Which probably isn't a ton of folks :) (Not zero...just not many.)

multigl
Nov 22, 2005

"Who's cool and has two thumbs? This guy!"
I'm having an issue with logging -- anything emitted from views (normal circumstances, Apache + mod_wsgi) get's a duplicate entry. If I open a manage.py shell and manually import logging and issue a logger.info I only get one entry. My logging configuration is here:

http://dpaste.com/525571/

Again, it's only for things that happen through apache -> mod_wsgi -> django that get duplicated.

ufarn
May 30, 2009
I want to get a Django intro book with some good, hands-on examples and walkthroughs. A little like Mining the Social Web by O'Reilly.

I'm just about to pull the trigger on Django 1.0 Website Development. It's supposed to have some great examples, but I don't really know where to go for book feedback. Basically all Django books have so few reviews that they may as well all have been written by friends of the author.

djangobook.com and all of those were too generic for my taste. They were good for installing everything, though, but the tone was incredibly tedious.

And then there are the problem with obsolescence ...

ufarn fucked around with this message at 22:59 on Mar 27, 2011

epswing
Nov 4, 2003

Soiled Meat
I really enjoyed this one:

http://www.amazon.com/Definitive-Guide-Django-Development-Right/dp/143021936X/ref=dp_ob_title_bk

Lots of examples, good explanations.

DICTATOR OF FUNK
Nov 6, 2007

aaaaaw yeeeeeah
I'm sorta stumped. I just began building a work order system in Django, and for some reason every time I attempt to access the admin (in this case, at /manage), Django throws this error:

ImproperlyConfigured at /manage/

Module "django.core.context_processors" does not define a "static" callable request processor

django.core.context_processors.static is set in TEMPLATE_CONTEXT_PROCESSORS in my settings.py file. Anybody else seen this / any additional info I need to provide for diagnosis?

duck monster
Dec 15, 2004

Where the hell does the Django communities bizzare boner for Postgres come from?

I'm having to use it due to postgis stuff, and good grief I've never encountered such a fragile database, and I've used many.

Or is this fragile "look at it the wrong way and it explodes" thing just a postgis thing?

Also anyone know wtf this error means?

code:
ERROR:  current transaction is aborted, commands ignored until end of transaction block
:confused:

It turns up all over the place, syncdb (which works with mysql flawlessly. However geodjangos mysql driver doesnt do distance_lte queries so its actually not useful for anything)does it, Trying to copy data with navicat does it, whenever theres postgis stuff.

It just gets depressing after a while because I can't figure out, and rather than my nice south migration history that I used putting this together on the dev server, I'm fighting this loving thing tooth and nail.

Django really needs to rethink its hostile attitude to mysql. At least it works.

duck monster fucked around with this message at 08:28 on Mar 29, 2011

king_kilr
May 25, 2007
Putting MySQL in the working category, that's cute. Just try: referential integrity at the same time as full text search, actually useful GIS queries, deferred constraints, optimizing queries using IN, the list goes on...

The error you're seeing is because you got an error in your transaction and ignored it, once a transaction enters an error state it must be rolled back.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
Not to mention the licensing issues with bundling MySQL with your application.

multigl
Nov 22, 2005

"Who's cool and has two thumbs? This guy!"

duck monster posted:

Where the hell does the Django communities bizzare boner for Postgres come from?.

python programmers love postgres

A A 2 3 5 8 K
Nov 24, 2003
Illiteracy... what does that word even mean?
The progression from MySQL to PostgreSQL is like the progression from PHP to Python or Ruby. You won't know why you ever put up with what you used to.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

A A 2 3 5 8 K posted:

The progression from MySQL to PostgreSQL is like the progression from PHP to Python or Ruby. You won't know why you ever put up with what you used to.

Conversely you'll run into a lot of problems that stem from bad habits that MySQL lets you get away with.

duck monster
Dec 15, 2004

king_kilr posted:

Putting MySQL in the working category, that's cute.

To clarify;- "Isn't broken".

quote:

Just try: referential integrity at the same time as full text search, actually useful GIS queries, deferred constraints, optimizing queries using IN, the list goes on...

The error you're seeing is because you got an error in your transaction and ignored it, once a transaction enters an error state it must be rolled back.

syncdb is a black box. And for reference, I've tried putting

DISABLE_TRANSACTION_MANAGEMENT = True

in the settings.py

It still implodes bitching about the transaction.



quote:

root@debian:/home/don/yacht# ./manage.py syncdb
SELECT postgis_lib_version()
None
SELECT "django_content_type"."id", "django_content_type"."name", "django_content_type"."app_label", "django_content_type"."model" FROM "django_content_type" WHERE ("django_content_type"."model" = %s AND "django_content_type"."app_label" = %s )
('account', 'directory')
Syncing...

SELECT c.relname
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r', 'v', '')
AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
AND pg_catalog.pg_table_is_visible(c.oid)
()
Traceback (most recent call last):
File "./manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 351, in handle
return self.handle_noargs(**options)
File "/usr/local/lib/python2.6/dist-packages/south/management/commands/syncdb.py", line 90, in handle_noargs
syncdb.Command().execute(**options)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 351, in handle
return self.handle_noargs(**options)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/commands/syncdb.py", line 59, in handle_noargs
tables = connection.introspection.table_names()
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/__init__.py", line 792, in table_names
return self.get_table_list(cursor)
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/postgresql/introspection.py", line 31, in get_table_list
AND pg_catalog.pg_table_is_visible(c.oid)""")
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/util.py", line 34, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/postgresql_psycopg2/base.py", line 46, in execute
return self.cursor.execute(query, args)
django.db.utils.DatabaseError: current transaction is aborted, commands ignored until end of transaction block

root@debian:/home/don/yacht#


The SQL (and parameter tuple) is in there because I dropped in code in the cursor execute code to print the queries to the console while trying to find where in djangos code its imploding.

For reference this happens on both the mac when I try and syncdb to an empty database, and on the debian box.

The macs 8.3, debian box is 8.4. Both djangos are 1.3

Its using the geodjango code.

The thing syncs perfectly on mysql AND spatialite, but neither appear to support distance queries as I need them.

e: If anyone wants to have a look at this and fix it, I have money to spend and a client going loving batshit at me because I cant get this working on the server :(

duck monster fucked around with this message at 05:13 on Mar 30, 2011

Profane Obituary!
May 19, 2009

This Motherfucker is Dead
Have you tried manually running that query to see if it's giving you an error message?

edit: And just so you know, there is a good chance that mysql works just fine because mysql does not invalidate the current transaction when it encounters an error where postgres throws the error and do not run other query until the current transaction is not aborted.

edit2: More information if you can provide it would be helpful, settings.py, models.py. I don't know what your app is exactly, and how much you can share but anything you can provide in that realm can help.

Profane Obituary! fucked around with this message at 05:31 on Mar 30, 2011

entr0py
Jan 31, 2004


A real-life robot.
Do you have a module doing database interaction upon being imported during Django's bootstrapping? I'm p sure the syncdb management command is not generating the second query in your debugging output. If you have an empty database, then obviously that query is going to fail (thus causing the transaction to be aborted); the tables don't exist:
code:
SELECT 
   "django_content_type"."id", 
   "django_content_type"."name", 
   "django_content_type"."app_label", 
   "django_content_type"."model" 
FROM "django_content_type"  -- breaks horribly because this table doesn't exist
WHERE ("django_content_type"."model" = 'account' AND "django_content_type"."app_label" = 'directory' )

entr0py fucked around with this message at 05:48 on Mar 30, 2011

duck monster
Dec 15, 2004

entr0py posted:

Do you have a module doing database interaction upon being imported during Django's bootstrapping? I'm p sure the syncdb management command is not generating the second query in your debugging output. If you have an empty database, then obviously that query is going to fail (thus causing the transaction to be aborted); the tables don't exist:
code:
SELECT 
   "django_content_type"."id", 
   "django_content_type"."name", 
   "django_content_type"."app_label", 
   "django_content_type"."model" 
FROM "django_content_type"  -- breaks horribly because this table doesn't exist
WHERE ("django_content_type"."model" = 'account' AND "django_content_type"."app_label" = 'directory' )

FOUND IT.

I had a bunch of registration code (content types + tagging) in the models.py (cos I dont know where else to put it), and that was busting its arse.

But mysql/sqlite wasn't bitching cos it seems to be a silent failure, and msql/sqlite are not quite as paranoic about transaction integrity.

Where SHOULD I put those?

Profane Obituary!
May 19, 2009

This Motherfucker is Dead
Depending on what exactly your registration code is doing you could make a function that does that, and call it from within urls.py that should work just fine.

DICTATOR OF FUNK
Nov 6, 2007

aaaaaw yeeeeeah
Apparently I have some sort of mental block that prevents me from understanding relational databases.

Right now I have a model that looks like this:

code:
class Order(models.Model):
    title = models.CharField(max_length=30) #summary, dropdown
    description = models.TextField()
    author = models.CharField(max_length=20)
    assigned_to = models.ManyToManyField(User)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    def __unicode__(self):
       return self.description
It's the very basics of a workorder system. Each order can have multiple users assigned to it, and vice versa.

Right now, a ModelForm is generated that shows a multiselect with a list of users in it, and I can submit the form and all that fun stuff great. However, I can't access the users. The User model is just Django's built in one.

Any time I try to pull a list of users out of the database (e.g.,
code:
Order.assigned_to.all() 
Order.assigned_to.through.objects.all()
Order.objects.get(pk=id).assigned_to.all()
, and some other combinations that aren't working at all), it either returns nothing or throws an error.

Trying to call "assigned_to_set" in any shape or form anywhere returns an error saying it doesn't exist too.

I'm trying really hard to wrap my brain around it but so far this is the only major Django roadblock I've not been able to figure out myself.

DICTATOR OF FUNK fucked around with this message at 18:07 on Mar 31, 2011

Lamacq
Jun 15, 2001

Breezeblock RIP

root beer posted:

problems

So if you have an instance of your Order class, you can access its related users through the assigned_to attribute.

code:
# get an order instance using the default "objects" manager
some_order = Order.objects.get(pk=some_order_id)

# get the users assigned to this order
assigned_users = some_order.assigned_to.all()

# I have this user, what orders are assigned to her?
these_orders = some_user.order_set.all()

# assign her to some_order if she's not already
if some_user not in assigned_users:
    some_order.assigned_to.add(some_user)
I'm sure king_kilr will point out something wrong with my code, but that's the gist of it :)

ufarn
May 30, 2009
EDIT: I am an idiot.

Lamacq
Jun 15, 2001

Breezeblock RIP
^^^^^^^^ OK then :)

Lamacq fucked around with this message at 20:06 on Mar 31, 2011

DICTATOR OF FUNK
Nov 6, 2007

aaaaaw yeeeeeah

Lamacq posted:

So if you have an instance of your Order class, you can access its related users through the assigned_to attribute.

code:
# get an order instance using the default "objects" manager
some_order = Order.objects.get(pk=some_order_id)

# get the users assigned to this order
assigned_users = some_order.assigned_to.all()

# I have this user, what orders are assigned to her?
these_orders = some_user.order_set.all()

# assign her to some_order if she's not already
if some_user not in assigned_users:
    some_order.assigned_to.add(some_user)
I'm sure king_kilr will point out something wrong with my code, but that's the gist of it :)
I really appreciate this, and it helped my understanding, but it still doesn't work. some_order.assigned_to.all() is blank, and it looks like no matter how many work orders I create and assign (via my ModelForm), the orders_order_assigned_to table Django generated for the ManyToManyField stays blank with user_id and order_id columns.

I'm using MySQL; I'm beginning to think that this might be a sign of a deeper problem. Any way this could be MySQL's fault?

EDIT: I of course changed your code to fit mine. I didn't just copy and paste as-is :downs:

ufarn
May 30, 2009
Another thing!

Using a Django 1.0 book. Things have obviously changed since. I am given this code:

code:
<html>
	<head>
		<title>Django Bookmarks - User Login</title>
	</head>
	<body>
		<h1>User Login</h1>
		{% if form.errors %}
			<p>Your username and password didn't match.
			Please try again.</p>
		{% endif %}
		<form method="post" action".">
			<p><label for="id_username">Username:</label>
				{{ form.username }}</p>
			<p><label for="id_password">Password:</label>
				{{ form.password }}</p>
			<input type="hidden" name="next" value"/" />
			<input type="submit" value="login" />
		</form>
	</body>
</html>
which returns a Forbidden (403) - CSRF verification failed. Request aborted when trying to log in.

I get that I need to include something CSRF-related, but I'm not sure about the details. (Especially considering that I'm at the very start of a Learning Django book.

Help?

Lamacq
Jun 15, 2001

Breezeblock RIP

root beer posted:

I really appreciate this, and it helped my understanding, but it still doesn't work. some_order.assigned_to.all() is blank, and it looks like no matter how many work orders I create and assign (via my ModelForm), the orders_order_assigned_to table Django generated for the ManyToManyField stays blank with user_id and order_id columns.

I'm using MySQL; I'm beginning to think that this might be a sign of a deeper problem. Any way this could be MySQL's fault?

EDIT: I of course changed your code to fit mine. I didn't just copy and paste as-is :downs:

I guess I don't know what you mean by "blank". some_order.assigned_to.all() should at least return an empty list. Are you sure the order instance you're working with in the interactive interpreter is the same one you're updating via the form? (I'm assuming you're using "./manage.py shell" to play with your django models in the interactive interpreter)

DICTATOR OF FUNK
Nov 6, 2007

aaaaaw yeeeeeah

ufarn posted:

Another thing!

Using a Django 1.0 book. Things have obviously changed since. I am given this code:

code:
<html>
	<head>
		<title>Django Bookmarks - User Login</title>
	</head>
	<body>
		<h1>User Login</h1>
		{% if form.errors %}
			<p>Your username and password didn't match.
			Please try again.</p>
		{% endif %}
		<form method="post" action".">
			<p><label for="id_username">Username:</label>
				{{ form.username }}</p>
			<p><label for="id_password">Password:</label>
				{{ form.password }}</p>
			<input type="hidden" name="next" value"/" />
			<input type="submit" value="login" />
		</form>
	</body>
</html>
which returns a Forbidden (403) - CSRF verification failed. Request aborted when trying to log in.

I get that I need to include something CSRF-related, but I'm not sure about the details. (Especially considering that I'm at the very start of a Learning Django book.

Help?
Here, this will be your best bet: http://docs.djangoproject.com/en/dev/ref/contrib/csrf/

My advice is just to use RequestContext(request) on each of your render_to_response calls, like so:

code:
return render_to_response('foo.html', {'bar':baz}, RequestContext(request))

Adbot
ADBOT LOVES YOU

Lamacq
Jun 15, 2001

Breezeblock RIP

ufarn posted:

csrf problems

http://docs.djangoproject.com/en/1.3/ref/contrib/csrf/

Long story short: add a {% csrf_token %} template tag inside your form element.

e:f,b

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