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
fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I'm trying to get Django setup on a Fedora Core box. I installed python, postgresql, mod_wsgi, and finally django. I added the following to my httpd.conf:

code:
<VirtualHost *:80>
        WSGIScriptAlias / /home/fletch/projects/domain/apache/django.wsgi
        ServerName domain.com
        ServerAlias *.domain.com
</VirtualHost>
Reloaded the httpd.conf and when I go to domain.com in my browser I get the "Firefox can't find the server at https://www.domain.com." No errors thrown in my apache error_log. Not sure where to go from here...any tips?

edit: I can ping the domain and it resolves to my server

edit2: gently caress I don't know what the deal was but it finally started logging the error in error_log, it was a typo in my django.wsgi file, couldn't find my settings file

Can I still use an htaccess file to password protect my dev environment? How would I do that?

fletcher fucked around with this message at 01:48 on Jun 25, 2009

Adbot
ADBOT LOVES YOU

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

bitprophet posted:

Since you've got access to the Apache config, just plunk whatever you would've put in a .htaccess file, into a <Location> block, e.g.

Ahh, that's what I had tried originally. Forgot to put it in a Location block. Thanks!

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I'm a bit confused on how to organize my code into different apps, what portions deserve their own app, which ones to lump together, etc. Can somebody help me clarify this?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I'm attempting to add the django-rest-framework SearchFilter with an existing Django project.

settings.py:
code:
REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.SearchFilter','rest_framework.filters.OrderingFilter')
}
I created my Serializer & ViewSet:
code:
class EmployeeSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Employee
        fields = ('id', 'first_name', 'last_name')

class EmployeeViewSet(viewsets.ModelViewSet):
    model = models.Employee
    serializer_class = EmployeeSerializer
    search_fields = ('last_name')
But when I hit the URL /api/employees?search=smith I get an error message like this:

quote:

FieldError at /api/employees/

Cannot resolve keyword u'l' into field. Choices are: id, first_name, last_name, ..., etc

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Finally got PyCharm setup so I could step through it. It didn't like search_fields being a str...I added a trailing comma to make it a tuple and now it works. Hooray!

code:
class EmployeeViewSet(viewsets.ModelViewSet):
    model = models.Employee
    serializer_class = EmployeeSerializer
    search_fields = ('last_name',)

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Any of you guys used django-pipeline before?

I tried to follow these instructions but I can't seem to get it to work right.

Installed the css & js compressor in my virtualenv:
code:
pip install cssmin
pip install slimit
Added it to my INSTALLED_APPS:
code:
INSTALLED_APPS = (
...
    'pipeline',
...
)
Added some configuration parameters:
code:
STATIC_ROOT = '/home/fletcher/static-test/'

STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'

PIPELINE_CSS_COMPRESSOR = 'pipeline.compressors.cssmin.CSSMinCompressor'

PIPELINE_CSSMIN_BINARY = 'cssmin'

PIPELINE_JS_COMPRESSOR = 'pipeline.compressors.slimit.SlimItCompressor'

PIPELINE_CSS = {
    'myapp': {
        'source_filenames': (
            'css/file1.css',
            'css/file2.css',
        ),
        'output_filename': 'combined.min.css',
    },
}

PIPELINE_JS = {
    'myapp': {
        'source_filenames': (
            'js/file1.js',
            'js/fil2.js',
        ),
        'output_filename': 'combined.min.js',
    }
}
Then I run:
code:
python manage.py collectstatic
And in the output I can see it copying all my files and doing the post-processing:
code:
139 static files copied, 141 post-processed.
I go to check the contents of /home/fletcher/static-test/ and I see a couple folders for the static resources from each app, but combined.min.css is completely empty, and combined.min.js contains only this:
code:
(function(){}).call(this);
Added the following to my base template:
code:
{% load compressed %}
{% compressed_css 'myapp' %}
{% compressed_js 'myapp' %}
But no static resources are loaded. Don't see anything in the resulting html actually, not even links to static resources that result in 404s. This should still work even though I'm using manage.py runserver for dev work, right? From my understanding it should just be loading the unminified versions since I have DEBUG = True.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Bah! Finally figured it out! I needed to have the source_filenames start with myapp/ like this:

code:
PIPELINE_CSS = {
    'myapp': {
        'source_filenames': (
            'myapp/css/file1.css',
            'myapp/css/file2.css',
        ),
        'output_filename': 'combined.min.css',
    },
}

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I've got an ImageField that I want to use in Django REST Framework. How do I intercept the file upload so I can do things like rename the file or resize it and whatnot?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Worked out great, thanks MonkeyMaker!

Got another question now...

My model has the following field:
code:
last_touched = models.DateTimeField(auto_now=True, auto_now_add=True)
But I get the following error when I try to save a record:

quote:

Warning: Field 'last_touched' doesn't have a default value

Shouldn't auto_now_add take care of that for me? So I also tried:
code:
last_touched = models.DateTimeField(default=datetime.datetime.now, auto_now=True, auto_now_add=True)
But I still got the error - what's the deal?

fletcher fucked around with this message at 20:20 on Sep 12, 2013

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Yup I've been using South from the get-go, it is pretty sweet!

Not sure what was up before with my auto_now, but it seems to be working now...

Got another question now. Django REST Framework appears to respect the blank=True/False on my model definitions, which is great. Is it possible to make that dynamic though? Like, I want it to be blank=True if some_field='foo', but if some_field was set to 'bar' then I want blank=False. How should I go about doing that? I can sorta get there with custom permissions but then it just returns a 403 permission denied, rather than a 400 bad request with useful error messages.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I've got an object that I need to access to all over the place, on every request. I've just been retrieving it as needed, but now when I look at my mysql query log I see the same query being executed 5 times within a single http request, obviously this is no good. I want it to be available like request.user is available, should I write a middleware component and stick this object on the request object?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Ok cool, thanks for the advice!

Got another one specific to Djangeo Rest Framework now that I'm looking at this query log.

I added a SlugRelatedField to one of my serializers and the number of queries it's executing shot up quite a bit. I tried to add select_related() to my get_queryset method, and now it uses an INNER JOIN to get one of the relationships. This particular model has a ForeignKey to self though, and it doesn't seem to want to use an INNER JOIN to get to that one, it just executes a bunch of individual queries. Any ideas what might be causing that behavior?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Is there any way to get access to the request object when overriding the model save() method? I was thinking I'd create a base model that has fields like modified_by, modified_datetime, etc and automatically populate them in the save() method of this base model, but I don't seem to have access to the request object to determine the value for modified_by (which is a ForeignKey to a Player object, not User, if that matters).

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I find myself creating nearly identical templates sometimes, one for Django and then one for Handlebars. Obviously this isn't ideal, since I have to maintain them in both places. I'm tempted to just use the Handlebars templates for all those cases, and simply render them in $(document).ready(). This has me wanting to be able to use my Django Rest Framework serializers in my Django templates, so the output of my Django template would just be a little placeholder element with a json object stuck in a data attribute or something, so it can be rendered using the Handlebars template client side. Is that possible? Is there some other way I should go about dealing with this?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Anybody else have performance problems with the built in development server running inside a virtual machine? I've got Windows 7 for my host OS, Linux Mint 15 for my guest OS. When I hit a URL for my app using Firefox on Windows, it takes 20 seconds to load. Hitting the same URL with Firefox from inside the VM takes about 3 seconds to load. It is excruciating watching my CSS styles being applied rule by rule! Same crap performance using Chrome on the host OS. I suppose I could just use the browser in my VM all the time, but figured I might as well ask in case anybody else has run into this and knew how to fix it.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Maluco Marinero posted:

You might not have the correct virtualization flags set in your BIOS. They can make a huge difference to performance, and also allow you to run 64bit VMs. I would check that before troubleshooting other stuff.

Went through and double checked all that stuff, seemed to look ok. Virtualization options enabled in the BIOS, IO APIC enabled, 4GB RAM allocated, 4 CPU cores, PAE/NX enabled, VT-x/AMD-V enabled, use host i/o cache, solid-state drive checked. Performance in the VM itself seems excellent, just the network performance from host to guest seems to suffer. I wonder if it's because I'm using NAT?

As a test, I did a wget from the host OS to a 10MB file being served by runserver. Took a couple seconds to start and then transferred at 2MB/s.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I'm trying to run ./manage.py test but I get:

quote:

DatabaseError: (1071, 'Specified key was too long; max key length is 767 bytes')

I'm using MySQL, and the default charset is set to utf8mb4. From looking at the MySQL log, the test runner appears to be attempting to create the following table:
code:
CREATE TABLE `auth_customuser` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `password` varchar(128) NOT NULL,
    `last_login` datetime NOT NULL,
    `email` varchar(255) NOT NULL UNIQUE,
    `is_active` bool NOT NULL,
    `is_admin` bool NOT NULL,
    `date_of_birth` date NOT NULL
)
I understand why the email field causes this error, but why is the test runner even creating this table in the first place? It doesn't exist in my app normally.

edit: oh and I tried setting TEST_CHARSET to latin1 in my settings.py, but that didn't seem to do anything? I don't want to use latin1 for my tests anyways but I thought that would allow me to temporarily get around this issue...

fletcher fucked around with this message at 00:37 on Oct 16, 2013

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Of course I go weeks of putting up with that VM performance problem and it magically goes away hours after I decide to finally bitch about it. Seems nice and snappy now :shrug:

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
If I leave a field blank, I get a nice little This field is required. error message. If I put whitespace in there, it gets around the standard validation and does not throw that same error message.

Some googling led me to this ticket where they concluded that is how the behavior will remain. I can't quite figure out how to implement that behavior myself though. I ended up with something like this:

code:
class Whatever(models.Model):
    awesome_field = models.CharField(max_length=100)

    def clean(self):
        strip_fields = [ 'awesome_field' ]

        for field in strip_fields:
            if getattr(self, field) is not None:
                setattr(self, field, getattr(self, field).strip())
It seems to strip the whitespace...but it's not throwing the This field is required. message like I thought it would. What am I doing wrong?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Thermopyle posted:

I'm a little confused about what you're trying to do. Can you not use blank=True, null=True on the field?

I have a field that is required, so I want blank=False, null=False. If you enter only whitespace as the value, it gets around the validation. So I just want to strip the whitespace from the value they enter, and if all they entered was whitespace, I want it to say "This field is required." without having to write the validation message myself.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Pumpkin Pirate posted:

The check for required fields being empty is done by the individual form fields. Form field cleaning is the first step of form cleaning, which happens before model cleaning, so by the time you're stripping the whitespace off, the check has already happened and succeeded.

You could simply check after you've stripped the field, and raise a ValidationError if it's blank, but I think the expected way to do something like this is with validators. You would write a function that raises ValidationError with the "required" message if it's given a string of only whitespace, and then pass it to the field constructor for awesome_field.

Thanks for the input guys. I suppose I'll go with the validator. It really seems like this should be the default behavior in Django though. I mean who would actually want to store whitespace as a value for a required field?

Also, is there some convention for where the code for custom validators should live?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Hmmm I'm not actually using any ModelForms, since all my froms post to Django REST Framework endpoints. That's why I was trying to do it at the model level.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Anybody using AngularJS with your Django application? How's that working out?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Is there a way to reconfigure a logging handler after it has been defined in settings.py? I want to override the filename of my FileHandler without touching settings.py.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Thanks Thermopyle.

For some reason nothing is being written to the log file in production (nginx + uwsgi), but it works fine in development with runserver. (this is without any dynamic handlers stuff)

The file exists and is writable by the uwsgi user (0777). Didn't see anything unusual in the uwsgi log. Here's my logging settings:

code:
LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': '[%(asctime)s] %(levelname)s %(pathname)s:%(lineno)d %(message)s'
        }
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'formatter': 'verbose',
            'filename': '/var/log/django/mysite.log'
        },
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        '': {
            'handlers': ['file'],
            'level': 'DEBUG'
        },
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}
edit: This seems to write to the log file just fine...why can't my app?
code:
$ source ./my-venv/bin/activate
(my-env) $ python manage.py shell
>>> import logging
>>> log = logging.getLogger('test')
>>> log.debug('hello world')
edit2: This script, however, writes nothing to the log?
code:
(my-env) $ cat /tmp/logtest.py
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

import logging

log = logging.getLogger('test')
log.debug('hello world')
(my-env) $ python /tmp/logtest.py

fletcher fucked around with this message at 23:45 on Oct 31, 2013

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Well, it looks like it was actually working after all? I thought it wasn't working because I wasn't seeing sql queries being logged by django.db.backends.util. I added a log.debug() statement in urls.py and it made it into the log file. So now it's a question of why the sql queries are not being logged.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Yay posted:

Django's pretty quiet by default; you need to opt-in to most of the loggers that might be available, specficially 'django.db' in your case.

But wouldn't my root logger for '' handle that?

At any rate, I added 'django.db' but I'm still not getting any sql queries in the logs.

code:
LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': '[%(asctime)s] %(levelname)s %(pathname)s:%(lineno)d %(message)s'
        }
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'formatter': 'verbose',
            'filename': '/var/log/django/mysite.log'
        },
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        '': {
            'handlers': ['file'],
            'level': 'DEBUG'
        },
        'django.db': {
            'handlers': ['file'],
            'level': 'DEBUG'
        }
    }
}

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

NtotheTC posted:

I do have the paid version, I didn't see the options for that though (admittedly I haven't looked thoroughly yet)

Settings->Project Interpreters->Python Interpreters

Click the green plus button on the right side and you can add a remote interpreter

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
What's the workflow/environment setup if there's a Django package that I want to contribute to?

I forked the repo, cloned it down, created a virtualenv, created a little demo app. At first I just did a pip install ./local/path/to/fork but that doesn't seem like the easiest way to start making changes to the library. I'm not supposed to make changes in site-packages and then merge them back into ./local/path/to/fork right?

Am I suppose to use ./local/path/to/fork as my project root, and create my demo app inside there?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

MonkeyMaker posted:

What's wrong with pip installing the local package, like you did? You might have to re-run your server or re-install your package sometimes, but it should work just fine. That's how I normally do it.

Oh ok, I'll give that a shot then :)

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Baby Nanny posted:

Use pip install -e. This will install the package in editable mode at the location of the code and will let you use it normally while still being able to code on it without having to re-run setup tools a bunch.

Perfect!! Thank you.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I still can't find out why queries are not being logged when I crank up the logging level...anybody have any other ideas?? Here's my last post about it.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Pollyanna posted:

So if I were to set up a simple one-page website that was more or less a set of posts (a database), a basic HTML template, a style sheet, and a .js for opening and collapsing posts or whatever, does that count as an app or is that something completely different? If it's not an app, what about it would have to change to make it count as one?

Sounds like an app to me. In addition to what Baby Nanny mentioned, check out Projects vs. Apps on this page. Maybe your project is pollyanas_site and your only app is blog_app, which consists of exactly what you described.

pollyanas_site has your settings.py, because that has stuff that is specific to you, like your email address or your database credentials. blog_app on the other hand, is more generic. If somebody also wanted blog_app, you could package it up, publish it, and tell them to pip install Django and then pip install blog_app.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Pollyanna posted:

Okay, I'm actually having some trouble now. I first tried Zinnia, but I ran into an issue where one of the modules it expected Django to have didn't exist (:confused:), so I tried to update Django. (I'm running in a venv now, so no worries) pip told me to upgrade it but then Django bitched about there already being an install, and told me to delete the sitepackages/django directory. I did that then tried to reinstall, but I can't because pip and easy_install say it's already installed. :byodood:

I might just wipe Django from my main installation and work from virtualenv from now on.

edit: Amazing. Mezzanine fucks up my installation too because it hasn't updated to 1.6. :tizzy:

1.6 is hot off the presses, you may want to stick with 1.5.5 for now until the libraries have a chance to catch up.

I've never had to manually delete anything from sitepackaegs, not sure what happened there. What module was it complaining about Django missing? Copy/pasta the exact errors in here, somebody will be able to help you out.

It sounds like maybe Django is installed outside of your virtualenv? Run deactivate to get out of your venv, then you should be able to do pip uninstall django to get rid of it.

Otherwise you can tell venv to ignore those packages when you create your venv by using --no-site-packages. You don't even have to install Django in your venv before installing mezzanine, since mezzanine lists all the dependencies it needs, pip will automatically install the right versions of them:

code:
greg@mint $ virtualenv --no-site-packages mezz_test
greg@mint $ source ./mezz_test/bin/activate
(mezz-test)greg@mint $ pip install mezzanine
...
...
Successfully installed mezzanine django filebrowser-safe grappelli-safe html5lib bleach pytz requests requests-oauthlib pillow oauthlib
Cleaning up...
(mezz-test)greg@mint $

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
For those of you that use virtualenv-burrito, is there any reason I wouldn't want to source /home/fletcher/.venvburrito/startup.sh automatically when a shell is opened? Is ~/.bashrc the right place for that kind of thing?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
What are some good libraries to look at for caching models and querysets? django-cache-machine looks pretty nice. Or should I just use the low level caching API built into Django and just cache a few specific things here and there?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
It's safe to leave django-debug-toolbar in INSTALLED_APPS and MIDDLEWARE_CLASSES on production right? I know it's not supposed to do anything when DEBUG = False but I just wanted to double check.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I'm playing around with django-mptt and I want cheap access to len(node.get_children()) so I don't have execute N queries to get the children count of N nodes. Any suggestions for how to go about this? I was thinking I might have to just add a children_count field on the model and calculate it in a cron job that runs in the background. I don't need this value to always be up to date, it's fine if there is a bit of a delay on it.

I started going down the route of trying to cache the serialized response data to at least reduce the frequency that those N queries get executed, but it started to feel not quite right.

edit: Nevermind, I just shoved it in memcached and called it a day. Don't want to spend forever trying to optimize this just yet.

fletcher fucked around with this message at 23:48 on Dec 5, 2013

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I think something like this might also work. Basically since you want each MoodLog to be able to have multiple Feeling & Rating combos associated with it, those could be their own model, with a key that points back to the MoodLog they are associated with. Django then makes it easy to query the relationships between these tables.

Python code:
class Feeling(models.Model):
    name = models.CharField(max_length=100)


class MoodLog(models.Model):
    publish_date = models.DateField()
    event = models.CharField(max_length=100)


class MoodLogEntry(models.Model):
    moodlog = models.ForeignKey(MoodLog)
    feeling = models.ForeignKey(Feeling)
    rating = models.IntegerField()
Now in python manage.py shell (or Admin UI) you can create some test data:
code:
>>> from moodlogger.models import *
>>> bad = Feeling.objects.create(name='Bad')
>>> sad = Feeling.objects.create(name='Sad')
>>> mad = Feeling.objects.create(name='Mad')
>>> glad = Feeling.objects.create(name='Glad')
>>> rad = Feeling.objects.create(name='Rad')
Create a MoodLog:
code:
>>> mylog = MoodLog.objects.create(publish_date='2013-12-05', event='First snowboarding backflip')
Create a couple MoodLogEntry records for mylog:
code:
>>> MoodLogEntry.objects.create(moodlog=mylog, feeling=glad, rating=75)
<MoodLogEntry: MoodLogEntry object>
>>> MoodLogEntry.objects.create(moodlog=mylog, feeling=rad, rating=100)
<MoodLogEntry: MoodLogEntry object>
Want all the feelings associated with a particular event? (Django created this *_set automatically because of our moodlog ForeignKey in the MoodLogEntry model)
code:
>>> for entry in mylog.moodlogentry_set.all():
...     print('Feeling: %s, Rating: %d' % (entry.feeling.name, entry.rating))
...     
Feeling: Glad, Rating: 75
Feeling: Rad, Rating: 100

Adbot
ADBOT LOVES YOU

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
edit: hah you beat me :)

Pollyanna posted:

Syncing the DB gives me this error, though:

code:
CommandError: One or more models did not validate:
logs.moodlog: Accessor for field 'automatic_thought' clashes with related field 'Thought.moodlog_set'.
Add a related_name argument to the definition for 'automatic_thought'.
logs.moodlog: Accessor for field 'revised_thought' clashes with related field 'Thought.moodlog_set'.
Add a related_name argument to the definition for 'revised_thought'.
What am I missing? I thought I was just defining what a Thought was and making a few different instances of them. Is that not possible...?

Also, is there an easier way to mess around with models without having to destroy and recreate your database? :(

Since you have multiple foreign keys to Thought, Django is getting confused when it tries to create that *_set accessor, because they all end up with the same default name. Fortunately Django lets you specify a name, so they don't clash.

Simplest way is to fix it is to tell Django not to create those *_set accessors, but doing:
Python code:
automatic_thought = models.ForeignKey(Thought, related_name='+')
revised_thought = models.ForeignKey(Thought, related_name='+')
So if you want all the MoodLogs where your automatic_thought is Happy:
Python code:
MoodLog.objects.filter(automatic_thought=Feeling.objects.get(name='Happy')).all()
Or if you do want those accessors (they can be handy, depending on how you are querying your data):
Python code:
automatic_thought = models.ForeignKey(Thought, related_name='moodlog_automatic_thoughts')
revised_thought = models.ForeignKey(Thought, related_name='moodlog_revised_thoughts')
Then you could find all the MoodLogs where your automatic_thought is Happy going the other way:
code:
Feeling.objects.get(name='Happy').moodlog_automatic_thoughts.all()

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