Search Results

Search found 5507 results on 221 pages for 'django cms'.

Page 17/221 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • Django facebook integration error

    - by Gaurav
    I'm trying to integrate facebook into my application so that users can use their FB login to login to my site. I've got everything up and running and there are no issues when I run my site using the command line python manage.py runserver But this same code refuses to run when I try and run it through Apache. I get the following error: Environment: Request Method: GET Request URL: http://helvetica/foodfolio/login Django Version: 1.1.1 Python Version: 2.6.4 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'foodfolio.app', 'foodfolio.facebookconnect'] Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'facebook.djangofb.FacebookMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'facebookconnect.middleware.FacebookConnectMiddleware') Template error: In template /home/swat/website-apps/foodfolio/facebookconnect/templates/facebook/js.html, error at line 2 Caught an exception while rendering: No module named app.models 1 : <script type="text/javascript"> 2 : FB_RequireFeatures(["XFBML"], function() {FB.Facebook.init("{{ facebook_api_key }}", " {% url facebook_xd_receiver %} ")}); 3 : 4 : function facebookConnect(loginForm) { 5 : FB.Connect.requireSession(); 6 : FB.Facebook.get_sessionState().waitUntilReady(function(){loginForm.submit();}); 7 : } 8 : function pushToFacebookFeed(data){ 9 : if(data['success']){ 10 : var template_data = data['template_data']; 11 : var template_bundle_id = data['template_bundle_id']; 12 : feedTheFacebook(template_data,template_bundle_id,function(){}); Traceback: File "/usr/lib/pymodules/python2.6/django/core/handlers/base.py" in get_response 92. response = callback(request, *callback_args, **callback_kwargs) File "/home/swat/website-apps/foodfolio/app/controller.py" in __showLogin__ 238. context_instance = RequestContext(request)) File "/usr/lib/pymodules/python2.6/django/shortcuts/__init__.py" in render_to_response 20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) File "/usr/lib/pymodules/python2.6/django/template/loader.py" in render_to_string 108. return t.render(context_instance) File "/usr/lib/pymodules/python2.6/django/template/__init__.py" in render 178. return self.nodelist.render(context) File "/usr/lib/pymodules/python2.6/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/pymodules/python2.6/django/template/debug.py" in render_node 71. result = node.render(context) File "/usr/lib/pymodules/python2.6/django/template/__init__.py" in render 946. autoescape=context.autoescape)) File "/usr/lib/pymodules/python2.6/django/template/__init__.py" in render 779. bits.append(self.render_node(node, context)) File "/usr/lib/pymodules/python2.6/django/template/debug.py" in render_node 81. raise wrapped Exception Type: TemplateSyntaxError at /foodfolio/login Exception Value: Caught an exception while rendering: No module named app.models

    Read the article

  • Javascript error when integrating django-tinymce and django-filebrowser

    - by jwesonga
    I've set up django-filebrowser in my app without any bugs, I already had django-tinymce set up and it loads the editor in the admin forms. I now want to use django-filebrowser with django-tinymce, but I keep getting a weird javascript error when I click on "Image URL" in the Image popup: r is undefined the error is js/tiny_mce/tiny_mce.js My settings.py file has the following configuration: TINYMCE_JS_URL=MEDIA_URL + 'js/tiny_mce/tiny_mce.js' TINYMCE_DEFAULT_CONFIG = { 'mode': "textareas", 'theme': "advanced", 'language': "en", 'skin': "o2k7", 'dialog_type': "modal", 'object_resizing': True, 'cleanup_on_startup': True, 'forced_root_block': "p", 'remove_trailing_nbsp': True, 'theme_advanced_toolbar_location': "top", 'theme_advanced_toolbar_align': "left", 'theme_advanced_statusbar_location': "none", 'theme_advanced_buttons1': "formatselect,styleselect,bold,italic,underline,bullist,numlist,undo,redo,link,unlink,image,code,template,visualchars,fullscreen,pasteword,media,search,replace,charmap", 'theme_advanced_buttons2': "", 'theme_advanced_buttons3': "", 'theme_advanced_path': False, 'theme_advanced_blockformats': "p,h2,h3,h4,div,code,pre", 'width': '700', 'height': '300', 'plugins': "advimage,advlink,fullscreen,visualchars,paste,media,template,searchreplace", 'advimage_update_dimensions_onchange': True, 'file_browser_callback': "CustomFileBrowser", 'relative_urls': False, 'valid_elements' : "" + "-p," + "a[href|target=_blank|class]," + "-strong/-b," + "-em/-i," + "-u," + "-ol," + "-ul," + "-li," + "br," + "img[class|src|alt=|width|height]," + "-h2,-h3,-h4," + "-pre," + "-code," + "-div", 'extended_valid_elements': "" + "a[name|class|href|target|title|onclick]," + "img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name]," + "br[clearfix]," + "-p[class<clearfix?summary?code]," + "h2[class<clearfix],h3[class<clearfix],h4[class<clearfix]," + "ul[class<clearfix],ol[class<clearfix]," + "div[class]," } TINYMCE_FILEBROWSER = False TINYMCE_COMPRESSOR = False i've tried switching back to older versions of tinyMCE Javascript but nothing seems to work. Would appreciate some help

    Read the article

  • While trying to set up Django on Windows: AttributeError: 'Settings' object has no attribute 'DATABA

    - by user326370
    I'm following these instructions in order to set up Django on Windows. I have installed Python 2.6, PostgreSQL 8.4, Psycopg 2.0.14 for Python 2.6 and the latest version of Django from SVN. I'm now following these instructions to run a test project (copied from the page linked to above): C:\Documents and Settings\John>cd C:\ C:\>mkdir django C:\>cd django C:\django>django-admin.py startproject testproject C:\django>cd testproject C:\django\testproject>python manage.py runserver When I run the last line, this is the output: Validating models... Unhandled exception in thread started by <function inner_run at 0x01ECB930> Traceback (most recent call last): File "J:\Python26\lib\site-packages\django\core\management\commands\runserver.py", line 48, in inn er_run self.validate(display_num_errors=True) File "J:\Python26\lib\site-packages\django\core\management\base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "J:\Python26\lib\site-packages\django\core\management\validation.py", line 22, in get_validat ion_errors from django.db import models, connection File "J:\Python26\lib\site-packages\django\db\__init__.py", line 14, in <module> if not settings.DATABASES: File "J:\Python26\lib\site-packages\django\utils\functional.py", line 273, in __getattr__ return getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'DATABASES' Did I forget to do something with the database? Any help will be appreciated. Thank you!

    Read the article

  • How to do custom display and auto-select in django admin multi-select field?

    - by rsp
    I'm new to django, so please feel free to tell me if I'm doing this incorrectly. I am trying to create a django ordering system. My order model: class Order(models.Model): ordered_by = models.ForeignKey(User, limit_choices_to = {'groups__name': "Managers", 'is_active': 1}) in my admin ANY user can enter an order, but ordered_by must be someone in the group "managers" (this is the behavior I want). Now, if the logged in user happens to be a manager I want it to automatically fill in the field with that logged in user. I have accomplished this by: class OrderAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "ordered_by": if request.user in User.objects.filter(groups__name='Managers', is_active=1): kwargs["initial"] = request.user.id kwargs["empty_label"] = "-------------" return db_field.formfield(**kwargs) return super(OrderAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) This also works, but the admin puts the username as the display for the select box by default. It would be nice to have the user's real name listed. I was able to do it with this: class UserModelMultipleChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return obj.first_name + " " + obj.last_name class OrderForm(forms.ModelForm): ordered_by = UserModelChoiceField(queryset=User.objects.all().filter(groups__name='Managers', is_active=1)) class OrderAdmin(admin.ModelAdmin): form = OrderForm My problem: I can't to both of these. If I put in the formfield_for_foreignkey function and add form = OrderForm to use my custom "UserModelChoiceField", it puts the nice name display but it won't select the currently logged in user. I'm new to this, but my guess is that when I use UserModelChoiceField it "erases" the info passed in via formfield_for_foreignkey. Do I need to use the super() function somehow to pass on this info? or something completely different?

    Read the article

  • Django: Filtering datetime field by *only* the year value?

    - by unclaimedbaggage
    Hi folks, I'm trying to spit out a django page which lists all entries by the year they were created. So, for example: 2010: Note 4 Note 5 Note 6 2009: Note 1 Note 2 Note 3 It's proving more difficult than I would have expected. The model from which the data comes is below: class Note(models.Model): business = models.ForeignKey(Business) note = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: db_table = 'client_note' @property def note_year(self): return self.created.strftime('%Y') def __unicode__(self): return '%s' % self.note I've tried a few different ways, but seem to run into hurdles down every path. I'm guessing an effective 'group by' method would do the trick (PostGres DB Backend), but I can't seem to find any Django functionality that supports it. I tried getting individual years from the database but I struggled to find a way of filtering datetime fields by just the year value. Finally, I tried adding the note_year @property but because it's derived, I can't filter those values. Any suggestions for an elegant way to do this? I figure it should be pretty straightforward, but I'm having a heckuva time with it. Any ideas much appreciated.

    Read the article

  • Website using open source Forums,Wikis and CMS (Single site)

    - by Daksh
    Hi, I want to develop a site using all three FOSS i.e. Forum,wikis and CMS.But i have few doubts. 1.Can you suggest which is the best software for each of the three(Forum,wikis and CMS).? 2.How should i make the front end preferably(i.e should i use Dreamweaver or just use the CMS for the front end too) 3.How do i integrate all the three(CMS,Forum and Wiki) into a single website. 4.Should i make my own CMS? 5.Site popularity and monetary techniques which really works. Please provide detailed explanations for your answers. Thanks in advance, Cheers!

    Read the article

  • Which is the best CMS?

    - by Nitz
    Hello Guys, My Boss wants to know about CMS. means he want to know which is best CMS We are using Drupal. But he still not satisfied with it? So i had thought, what is best resource for find that? Then I realize that who can give me better suggestion then big community like SO. So I am asking you as developer what will you suggest about CMS? CMS can be in any language but it should be use for building website. So what do you think which CMS is best?

    Read the article

  • How much knowledge do I need to begin a project in Django

    - by Smock
    I started learning django about a month ago. I have an intermediate C, Java programming experience. I read the first 8 chapters of the django book . Afterwards, I picked up Practical Django Projects by James Bennett and did the first two projects: CMS & Web Blog. Although, I started getting lost when he got to the generic views part. I know that's important but I'm not sure how important that is when trying to implement a project. Anyway, I have a project in mind that I'd like to start; however, I'm nervous as to where to begin. I'm overwhelmed with the number of things that I'd like my project to do but no knowledge or minimal knowledge as to how e.g. how do i implement css and javascript in my project. Moreover, I am aware that some django packages exists to ease development but I don't know if I should use them or not. Anyway, I apologize for my length message. I just want some advice/encouragement. I have a project in mind but do you think I need to read more materials/tutorials or is it smart to just start working on my project based on the minimal knowledge i've gained from those books? Any information that can be provided is much appreciated. I really want to get good at this but I just need some direction.

    Read the article

  • Single django instance with subdomains for each app in the django project

    - by jwesonga
    I have a django project (django+apache+mod_wsgi+nginx) with multiple apps, I'd like to map each app as a subdomain: project/ app1 (domain.com) app2 (sub1.domain.com) app3 (sub3.domain.com) I have a single .wsgi script serving the project, which is stored in a folder /apache. Below is my vhost file. I'm using a single vhost file instead of separate ones for each sub-domain: <VirtualHost *:8080> ServerAdmin [email protected] ServerName www.domain.com ServerAlias domain.com DocumentRoot /home/path/to/app/ Alias /admin_media/ /usr/local/lib/python2.6/dist-packages/django/contrib/admin/media <Directory /home/path/to/wsgi/apache/> Order deny,allow Allow from all </Directory> LogLevel warn ErrorLog /home/path/to/logs/apache_error.log CustomLog /home/path/to/logs/apache_access.log combined WSGIDaemonProcess domain.com user=www-data group=www-data threads=25 WSGIProcessGroup domain.com WSGIScriptAlias / /home/path/to/apache/kcdf.wsgi </VirtualHost> <VirtualHost *:8081> ServerAdmin [email protected] ServerName sub1.domain.com ServerAlias sub1.domain.com DocumentRoot /home/path/to/app Alias /admin_media/ /usr/local/lib/python2.6/dist-packages/django/contrib/admin/media <Directory /home/path/to/wsgi/apache/> Order deny,allow Allow from all </Directory> LogLevel warn ErrorLog /home/path/to/logs/apache_error.log CustomLog /home/path/to/logs/apache_access.log combined WSGIDaemonProcess sub1.domain.com user=www-data group=www-data threads=25 WSGIProcessGroup sub1.domain.com WSGIScriptAlias / /home/path/to/apache/kcdf.wsgi </VirtualHost> My Nginx configuration for the domain.com: server { listen 80; server_name domain.com; access_log off; error_log off; # proxy to Apache 2 and mod_wsgi location / { proxy_pass http://127.0.0.1:8080/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_max_temp_file_size 0; client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; } } Configuration for the sub.domain.com: server { listen 80; server_name sub.domain.com; access_log off; error_log off; # proxy to Apache 2 and mod_wsgi location / { proxy_pass http://127.0.0.1:8081/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_max_temp_file_size 0; client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; } } This set up doesn't seem to work, everything seems to point to the main domain. I've tried http://effbot.org/zone/django-multihost.htm which kind of worked but seems to have issues with loading my css,images,js files.

    Read the article

  • Best way to create an exact twitter clone? From scratch vs CMS vs any other way [closed]

    - by Akash
    I tried many already built Twitter clone scripts but none was having user-end functionality exactly as twitter. I know enough PHP to code all the twitter's features myself. But is there a faster way than coding myself? I've never used a CMS but if I do then won't I have to search a plugin for every twitter feature, like support for multiple users, options for following-unfollowing users, retweeting (reposting someone else's post), tagging? And I'm afraid that there might be some licensing issues with CMS.

    Read the article

  • Which Content Management System (CMS)/Wiki should I use?

    - by danlefree
    This is a general, community wiki catch-all question to address non-specific "I need a CMS or Wiki that does x, y, and z..." questions. If your question was closed as a duplicate of this question and you feel that the information provided here does not provide a sufficient answer, please open a discussion on Pro Webmasters Meta. I have a list of features that I want for my website's Content Management System (CMS) - where can I find a [free] script that includes all of them?

    Read the article

  • Should I design and then look for a CMS or vice versa? [closed]

    - by Livingston Storm
    I am currently designing an e-commerce site, and unfortunately my PHP is garbage at the moment so open source CMS's are out of the question. I am debating between Joomla and Big Commerce and as the title states I am unsure of whether to build first or try the CMS first to see what limitations I will face. I couldn't find any previous questions on this site, forgive me if this is a stupid/commonly asked question. Thanks for any feedback

    Read the article

  • In Django Combobox choices, how do you lookup description from short value?

    - by MikeN
    In Django models/forms the choices for a combobox often look like this: food_choices = (("",""), ("1", "Falafel"), ("2", "Hummus"), ("3", "Eggplant Stuff, Babaganoush???"), So the value to be stored in the database will be 1/2/3, but the displayed value on the form will be the long description. When we are working in code outside a form, how can we quickly lookup the long description given the short value stored in the model? So I want to map short values to long values: print foo("1") "Falafel"

    Read the article

  • Do Django Models inherit managers? (Mine seem not to)

    - by Zach
    I have 2 models: class A(Model): #Some Fields objects = ClassAManager() class B(A): #Some B-specific fields I would expect B.objects to give me access to an instance of ClassAManager, but this is not the case.... >>> A.objects <app.managers.ClassAManager object at 0x103f8f290> >>> B.objects <django.db.models.manager.Manager object at 0x103f94790> Why doesn't B inherit the objects attribute from A?

    Read the article

  • How to setup Joomla CMS as a backend for iPhone app

    - by srik
    I would like my iPhone app to get dynamic content off the net. This content should be managed using a CMS. I have gone ahead and installed Joomla on my server and will be using the Joomla web interface to create and manage content. I would now like the iPhone app to login to my server and fetch the content. I do not want the complete web pages for my iPhone app. Instead, I want the content in the form of XML or JSON or some serialized format so that I can use the data in a custom layout native to the app. So I am looking for 2 things in particular: 1. How to setup HTTP based authentication for my iPhone app to access data from my server. 2. How to access the content in a serialized format (XML, JSON etc) Are there plugins/extensions/components I can use to achieve the same. Any advice on how this can be achieved would be helpful. I am completely new to setting up/using CMS.

    Read the article

  • How to setup Joomla CMS as a backend for iPhone app

    - by srik
    I would like my iPhone app to get dynamic content off the net. This content should be managed using a CMS. I have gone ahead and installed Joomla on my server and will be using the Joomla web interface to create and manage content. I would now like the iPhone app to login to my server and fetch the content. I do not want the complete web pages for my iPhone app. Instead, I want the content in the form of XML or JSON or some serialized format so that I can use the data in a custom layout native to the app. So I am looking for 2 things in particular: 1. How to setup HTTP based authentication for my iPhone app to access data from my server. 2. How to access the content in a serialized format (XML, JSON etc) Are there plugins/extensions/components I can use to achieve the same. Any advice on how this can be achieved would be helpful. I am completely new to setting up/using CMS.

    Read the article

  • Open source Java CMS for Google App Engine?

    - by markvgti
    I am looking for an open source Java CMS (Web CMS, actually) to run on Google App Engine. I have looked at related older questions on this topic (What CMS runs on Google AppEngine?, CMS over Google App Engine, with SEO etc.) but the problem is that they all largely list Python-based CMSes. Plus these questions are pretty old, and since GAE is a fast-moving target, I thought it might be worthwhile to ask again. I want a CMS for creating some websites (for myself and for others), but would rather not start writing one from scratch. A "good" (very subjective, I know) open source WCMS allows me to start using a product, while still being able to add to/extend the product/project. On the one hand I am looking for a somewhat mature product/project, on the other hand it's easier to start contributing to the development cycle of a young product/project (conflicting, I know :-). Here are some features that would be preferable: [X]HTML/XML/CSS based templating Ability to create multiple blogs Galleries Ability to create a "Downloads" section (is this pretty much standard?) Separate management for digital assets (images, PDFs, binary files etc.) Roles like "Administrator", "Editor", "Contributor" etc. (or their equivalents) Ability to move/reorganize pages Export to PDF Reformat content for printing Is the CMS you are about to suggest especially well-suited to publishing an online book? My idea is that while the book may be offered as a downloadable eBook, the latest, most current version will be the one available on the website.

    Read the article

  • CMS for managing plain-text content, with tagging

    - by user575606
    Hi, We have some quite-specific requirements for our app that a CMS may help us with, and were hoping that someone may know of a CMS that matches these requirements (it's quite a laborous task to download each CMS and verify this manually). We want a CMS to allow users to create and manage articles, but storing the articles in plain-text only. All of the CMSs that we have looked at so far are geared towards creating HTML pages. We want the CMS to manage workflow (approval process), and tracking of history. The requirements for plain text only is that the intent is to allow business people to generate content which we are going to display in our Silverlight application - we don't want to go down the route of hosting and displaying arbitrary HTML in the app as we want the styling to be seamless with our app, amongst other reasons. We would also want to allow the user to be able to link between articles, but not to external sites (i.e. HTML with no formatting, or some other way of specifying article links), and the third requirement is the ability to tag articles and search on articles. Does anyone know of any non-HTML targetted CMS systems that may match these requirements? Thanks, Gary

    Read the article

  • South migration error: NoMigrations exception for django.contrib.auth

    - by danpalmer
    I have been using South on my project for a while, but I recently did a huge amount of development and changed development machine and I think something messed up in the process. The project works fine, but I can't apply migrations. Whenever I try to apply a migration I get the following traceback: danpalmer:pest Dan$ python manage.py migrate frontend Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 222, in execute output = self.handle(*args, **options) File "/Library/Python/2.6/site-packages/South-0.7-py2.6.egg/south/management/commands/migrate.py", line 102, in handle delete_ghosts = delete_ghosts, File "/Library/Python/2.6/site-packages/South-0.7-py2.6.egg/south/migration/__init__.py", line 182, in migrate_app applied = check_migration_histories(applied, delete_ghosts) File "/Library/Python/2.6/site-packages/South-0.7-py2.6.egg/south/migration/__init__.py", line 85, in check_migration_histories m = h.get_migration() File "/Library/Python/2.6/site-packages/South-0.7-py2.6.egg/south/models.py", line 34, in get_migration return self.get_migrations().migration(self.migration) File "/Library/Python/2.6/site-packages/South-0.7-py2.6.egg/south/models.py", line 31, in get_migrations return Migrations(self.app_name) File "/Library/Python/2.6/site-packages/South-0.7-py2.6.egg/south/migration/base.py", line 60, in __call__ self.instances[app_label] = super(MigrationsMetaclass, self).__call__(app_label_to_app_module(app_label), **kwds) File "/Library/Python/2.6/site-packages/South-0.7-py2.6.egg/south/migration/base.py", line 88, in __init__ self.set_application(application, force_creation, verbose_creation) File "/Library/Python/2.6/site-packages/South-0.7-py2.6.egg/south/migration/base.py", line 159, in set_application raise exceptions.NoMigrations(application) south.exceptions.NoMigrations: Application '<module 'django.contrib.auth' from '/Library/Python/2.6/site-packages/django/contrib/auth/__init__.pyc'>' has no migrations. I am not that experienced with South and I haven't met this error before. The only helpful mention I can find online about this error is for pre-0.7 I think and I am on South 0.7. I ran 'easy_install -U South' just to make sure. Thanks for any help that you can provide. I really appreciate it.

    Read the article

  • Django App for Image heavy Magazine Publishing?

    - by stapler
    I'm about to begin work on a Django project for an image heavy non-profit "community arts" magazine. The magazine is published monthly with about 6-8 articles that include with 4-10 images. I've been looking around for other projects that people have started specifically for publishing in Django... Are there any publishing specific Django apps you'd recommend? At the moment the only thing I can find is django-newsroom which looks interesting. Currently I'm just Image Kit / Photologue to attach galleries to an Article Model... but I'd love to figure out a way to more fully integrate images into the article content. Thanks in advance

    Read the article

  • Why can't I use __getattr__ with Django models?

    - by Joshmaker
    I've seen examples online of people using __getattr__ with Django models, but whenever I try I get errors. (Django 1.2.3) I don't have any problems when I am using __getattr__ on normal objects. For example: class Post(object): def __getattr__(self, name): return 42 Works just fine... >>> from blog.models import Post >>> p = Post() >>> p.random 42 Now when I try it with a Django model: from django.db import models class Post(models.Model): def __getattr__(self, name): return 42 And test it on on the interpreter: >>> from blog.models import Post >>> p = Post() ERROR: An unexpected error occurred while tokenizing input The following traceback may be corrupted or invalid The error message is: ('EOF in multi-line statement', (6, 0)) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /Users/josh/project/ in () /Users/josh/project/lib/python2.6/site-packages/django/db/models/base.pyc in init(self, *args, **kwargs) 338 if kwargs: 339 raise TypeError("'%s' is an invalid keyword argument for this function" % kwargs.keys()[0]) -- 340 signals.post_init.send(sender=self.class, instance=self) 341 342 def repr(self): /Users/josh/project/lib/python2.6/site-packages/django/dispatch/dispatcher.pyc in send(self, sender, **named) 160 161 for receiver in self._live_receivers(_make_id(sender)): -- 162 response = receiver(signal=self, sender=sender, **named) 163 responses.append((receiver, response)) 164 return responses /Users/josh/project/python2.6/site-packages/photologue/models.pyc in add_methods(sender, instance, signal, *args, **kwargs) 728 """ 729 if hasattr(instance, 'add_accessor_methods'): -- 730 instance.add_accessor_methods() 731 732 # connect the add_accessor_methods function to the post_init signal TypeError: 'int' object is not callable Can someone explain what is going on? EDIT: I may have been too abstract in the examples, here is some code that is closer to what I actually would use on the website: class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() date_published = models.DateTimeField() content = RichTextField('Content', blank=True, null=True) # Etc... Class CuratedPost(models.Model): post = models.ForeignKey('Post') position = models.PositiveSmallIntegerField() def __getattr__(self, name): ''' If the user tries to access a property of the CuratedPost, return the property of the Post instead... ''' return self.post.name # Etc... While I could create a property for each attribute of the Post class, that would lead to a lot of code duplication. Further more, that would mean anytime I add or edit a attribute of the Post class I would have to remember to make the same change to the CuratedPost class, which seems like a recipe for code rot.

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >