WordPress models and views for Django.

Overview

django-wordpress

Models and views for reading a WordPress database. Compatible with WordPress version 3.5+.

django-wordpress is a project of ISL and the Sunlight Foundation.

Features

Read-only models to protect your content

This package is designed to be read-only. Writing is enabled by adding WP_READ_ONLY = False to settings.py. None of the WordPress specific logic is included while writing to the database so there is a good chance you will break your WordPress install if you enable writing.

WordPress table prefix

The default table prefix is wp. To change the table prefix, add WP_TABLE_PREFIX = 'yourprefix' to settings.py.

Multiple database support

Added the ability to specify which database the WordPress content is coming from. Set it using the WP_DATABASE setting. Defaults to "default".

Database routers need be set to:

DATABASE_ROUTERS = ['wordpress.router.WordpressRouter']

Default templates

Default templates are provided only for development purposes so you can see content in your browser! Please override these with customized templates for your application.

Export Management Commands

  • wpexport Dump published posts in WXR format.
  • wpexportauthors Export authors as CSV.

Working With WordPress Models

Ten most recent published posts:

Posts.objects.published()[:10]

Posts tagged wordpress:

Posts.objects.term("wordpress")

Post attachments:

for attachment in post.attachments():
    pass

Post tags:

post.tags()

Installation

pip install the-real-django-wordpress

Add to INSTALLED_APPS in settings.py:

'wordpress'

Include the following in urls.py:

url(r'^path/to/blog/', include('wordpress.urls')),
Comments
  • Handle exception if not able to connect to Wordpress database

    Handle exception if not able to connect to Wordpress database

    I would like to display an error message if the Wordpress database happens to be offline, but I get an exception when going to mydjangoapp.com/blog

    OperationalError: (2003, "Can't connect to MySQL server on '10.0.2.2' (110)")
    

    What should I do?

    Also have a look at: http://stackoverflow.com/questions/25839018/handle-unhandled-exception-from-python-package

    opened by stephanebruckert 8
  • Post requires a parent even though null=True

    Post requires a parent even though null=True

    I'm using django-wordpress to import some existing content into a Wordpress installation, and I've got a management command that creates Post objects using the ORM (and I've set wordpress.models.READ_ONLY = False).

    I've got something like:

    post = Post()
    post.title = '...'
    post.author = user  # I've created a wordpress.models.User object
    ... # additional content & required fields (e.g. the DateTimeFields), but I omit the parent field
    post.save()
    

    At this point, I get a Traceback like the following. It appears that the parent field is required, even tho it is defined with null=True.

    Traceback (most recent call last):
      File "./manage.py", line 10, in <module>
        execute_from_command_line(sys.argv)
      File ".venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
        utility.execute()
      File ".venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
        self.fetch_command(subcommand).run_from_argv(self.argv)
      File ".venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv
        self.execute(*args, **options.__dict__)
      File ".venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute
        output = self.handle(*args, **options)
      File "myapp/management/commands/export_blog_to_wordpress.py", line 22, in handle
        self.export_posts()
      File "myapp/management/commands/export_blog_to_wordpress.py", line 160, in export_posts
        wp.save()  # We need the id before we can assign Categories
      File ".venv/local/lib/python2.7/site-packages/wordpress/models.py", line 81, in save
        super(WordPressModel, self).save(**kwargs)
      File ".venv/local/lib/python2.7/site-packages/django/db/models/base.py", line 463, in save
        self.save_base(using=using, force_insert=force_insert, force_update=force_update)
      File ".venv/local/lib/python2.7/site-packages/django/db/models/base.py", line 551, in save_base
        result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
      File ".venv/local/lib/python2.7/site-packages/django/db/models/manager.py", line 203, in _insert
        return insert_query(self.model, objs, fields, **kwargs)
      File ".venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 1576, in insert_query
        return query.get_compiler(using=using).execute_sql(return_id)
      File ".venv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 910, in execute_sql
        cursor.execute(sql, params)
      File ".venv/local/lib/python2.7/site-packages/django/db/backends/util.py", line 40, in execute
        return self.cursor.execute(sql, params)
      File ".venv/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 114, in execute
        return self.cursor.execute(query, args)
      File ".venv/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 201, in execute
        self.errorhandler(self, exc, value)
      File ".venv/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
        raise errorclass, errorvalue
    django.db.utils.IntegrityError: (1048, "Column 'post_parent' cannot be null")
    

    Any ideas what's going on, here, and is this a bug or am I just doing something wrong?

    My current workaround is this:

    1. Insert a dummy post with no content directly into the database: insert into wp_posts (ID) values (1);
    2. Set the following: post.parent = Post.objects.get(id=1) before calling post.save()

    Thanks in advance!

    opened by bradmontgomery 7
  • Change IPAddressField to GenericIPAddressField for Django 1.9 Support

    Change IPAddressField to GenericIPAddressField for Django 1.9 Support

    Warning during django-admin migrate:

    System check identified some issues:
    
    WARNINGS:
    wordpress.Comment.author_ip: (fields.W900) IPAddressField has been deprecated. Support for it (except in historical migrations) will be removed in Django 1.9.
        HINT: Use GenericIPAddressField instead.
    
    opened by wyc 4
  • Forward Compatibility for Django 1.5

    Forward Compatibility for Django 1.5

    Simply removed verify_exists=False from some models. This is the default value anyways so this code just breaks in Django 1.5 :)

    Also added blank=True for two of the fields that are not always set

    https://docs.djangoproject.com/en/dev/internals/deprecation/

    opened by wadewilliams 4
  • ValueError: Database returned an invalid value in QuerySet.datetimes(). Are time zone definitions for your database and pytz installed?

    ValueError: Database returned an invalid value in QuerySet.datetimes(). Are time zone definitions for your database and pytz installed?

    I created the tables with wordpress (http://codex.wordpress.org/Installing_WordPress), but got an new error:

    ValueError: Database returned an invalid value in QuerySet.datetimes(). Are time zone definitions for your database and pytz installed?

    I have pytz installed.

    opened by weasteam 2
  • How are we supposed to set the database name, user and password for distant DB?

    How are we supposed to set the database name, user and password for distant DB?

    I installed django-wordpress successfully. I am willing to connect to a distant database.

    INSTALLED_APPS += ('wordpress',)
    WP_DATABASE = "db1234567890.db.xxx.com"
    DATABASE_ROUTERS = ['wordpress.router.WordpressRouter']
    

    However, the previous gives:

    The connection db403846194.db.1and1.com doesn't exist
    

    Is that something wrong with the portfowarding from my host machine to my Vagrant box? And how am I supposed to set the db name, user and password of my MySQL database?

    opened by stephanebruckert 2
  • Helped out with the custom SQL stuff

    Helped out with the custom SQL stuff

    (Copied from docs under "Modifications by twig")

    I've marked this branch as "stable". It's the same code as you had with the custom SQL, but all in ORM.

    • Disabled support for Link.category_id and Post.category_id (so it supports WordPress 3+)
    • Added the ability to specify which database the wordpress content is coming from. Set it using the WP_DATABASE setting. Defaults to "default".
    • Added mapping for TermTaxonomyRelationship so there is no more hand-crafted SQL being run.
    • PostManager.term() now supports multiple terms
    • Added Term.get_absolute_url()
    • Ensured that WordPress tables are not created or deleted by Django by marking them as unmanaged.

    I've got some working code that links TermTaxonomy object to the Post object via object_id but trying to figure out a clean it up. Since it may break existing code, I have not yet pushed it to github.

    opened by twig 2
  • Fix IPAddressField error

    Fix IPAddressField error

    Hey guys,

    Thanks much for these models – huge timesaver for me. When installing on Django 1.10, I got the following error, since IPAddressField was removed in 1.9:

    wordpress.Comment.author_ip: (fields.E900) IPAddressField has been removed except for support in historical migrations.
    	HINT: Use GenericIPAddressField instead.
    

    This PR fixes it...

    opened by walkness 1
  • Couldn't configure the database

    Couldn't configure the database

    Hello @jcarbaugh ,

    My django setting are the following

    For my django app

    DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'name', 'USER': 'dev', 'PASSWORD': 'password', 'HOST': 'host', 'PORT': '3306', } }

    For wordpress

    WP_DATABASE = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'wordpress', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '8889', } }

    I will really appreciate your help. I am constantly getting the error. Here is the trace back.

    Environment:

    Request Method: GET Request URL: http://192.168.33.10:8080/path/to/blog/

    Django Version: 1.7.3 Python Version: 2.7.6 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'admin_app', 'rest_framework', 'rest_framework_swagger', 'djangoapps', 'djangoapps.applicants', 'djangoapps.catalog', 'djangoapps.ezylnx', 'djangoapps.landers') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware')

    Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response

    1.                 response = wrapped_callback(request, _callback_args, *_callback_kwargs)
      
      File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in view
    2.         return self.dispatch(request, _args, *_kwargs)
      
      File "/usr/local/lib/python2.7/dist-packages/django/views/generic/base.py" in dispatch
    3.     return handler(request, _args, *_kwargs)
      
      File "/usr/local/lib/python2.7/dist-packages/wordpress/views.py" in get
    4.     return super(Archive, self).get(request, _args, *_kwargs)
      
      File "/usr/local/lib/python2.7/dist-packages/django/views/generic/dates.py" in get
    5.     self.date_list, self.object_list, extra_context = self.get_dated_items()
      
      File "/usr/local/lib/python2.7/dist-packages/django/views/generic/dates.py" in get_dated_items
    6.     date_list = self.get_date_list(qs, ordering='DESC')
      
      File "/usr/local/lib/python2.7/dist-packages/django/views/generic/dates.py" in get_date_list
    7.     if date_list is not None and not date_list and not allow_empty:
      
      File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in nonzero
    8.     self._fetch_all()
      
      File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in _fetch_all
    9.         self._result_cache = list(self.iterator())
      
      File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in iterator
    10.     return self.query.get_compiler(self.db).results_iter()
      
      File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py" in get_compiler
    11.         connection = connections[using]
      
      File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py" in getitem
    12.     if hasattr(self._connections, alias):
      

    Exception Type: TypeError at /path/to/blog/ Exception Value: hasattr(): attribute name must be string

    opened by hasnain-naveed 1
  • Remove direct call to model in managers

    Remove direct call to model in managers

    This is simple change that is very important. Models shouldn't be call directly because this blocks possibility of inheriting them by other models without creating custom manager that solves this problem.

    Models should never be call in this way in managers. The best solution is to use or self.get_queryset() method or self.model object representing current model. Also we can use that we have Manager object, so we can call any method.

    opened by AdamStrojek 1
  • Multiple database support does not work in admin interface

    Multiple database support does not work in admin interface

    Page /admin/wordpress/post/1/ triggers error:

    no such table: wp_users
    

    This does not work because ForeignKeyField does not use custom manager.

    Default database for application can be changed by database router.

    opened by mireq 1
  • Django 2.x compatibility

    Django 2.x compatibility

    Not sure if this project is still alive (ping @jcarbaugh ?) but it's currently incompatible with Django >= 2.0.

    First problem I've run across is the ForeignKeys lacking explicit on_delete kwargs.

    If this project is still alive and there's a chance of a release being made upon merging a PR, I'd be happy to create a pull request.

    opened by kopf 0
  • remove permalink decorator

    remove permalink decorator

    This PR fixes one incompatibility w/ mainline django.

    https://docs.djangoproject.com/en/1.11/releases/1.11/#models-permalink-decorator

    states to replace deprecated permalink decorator and replace w/ a return reverse(...)

    --timball

    opened by timball 1
Owner
Jeremy Carbaugh
Jeremy Carbaugh
null 4 Oct 28, 2021
An unofficial API for lyricsfreak.com using django and django rest framework.

An unofficial API for lyricsfreak.com using django and django rest framework.

Hesam Norin 1 Feb 9, 2022
Beyonic API Python official client library simplified examples using Flask, Django and Fast API.

Beyonic API Python official client library simplified examples using Flask, Django and Fast API.

Harun Mbaabu Mwenda 46 Sep 1, 2022
Facebook open graph api implementation using the Django web framework in python

Django Facebook by Thierry Schellenbach (mellowmorning.com) Status Django and Facebook are both rapidly changing at the moment. Meanwhile, I'm caught

Thierry Schellenbach 1.4k Dec 29, 2022
Estudo de como criar uma api para o gerenciamento de livros usando a django restframework

Boa parte do projeto foi beaseado nesse vídeo e nesse artigo. Se assim como eu, você entrou agora no mundo BackEnd, recomendo fortemente tais materiai

Michel Ledig 14 Jun 28, 2022
A Django-style ORM idea for manipulating Google Datastore entities

No SeiQueLa ORM EM DESENVOLVIMENTO Uma ideia de ORM no estilo do Django para manipular entidades do Google Datastore. Montando seu modelo: from noseiq

Geraldo Castro 16 Nov 1, 2022
Twitter-redesign - Twitter Redesign With Django

Twitter Redesign A project that tests Django and React knowledge through a twitt

Mark Jumba 1 Jun 1, 2022
Official Python client for the MonkeyLearn API. Build and consume machine learning models for language processing from your Python apps.

MonkeyLearn API for Python Official Python client for the MonkeyLearn API. Build and run machine learning models for language processing from your Pyt

MonkeyLearn 157 Nov 22, 2022
go-cqhttp API typing annoations, return data models and utils for nonebot

go-cqhttp API typing annoations, return data models and utils for nonebot

风屿 6 Jan 4, 2023
Python API for working with RESQML models

resqpy: Python API for working with RESQML models Introduction resqpy is a pure python package which provides a programming interface (API) for readin

BP 44 Dec 14, 2022
The python SDK for Eto, the AI focused data platform for teams bringing AI models to production

Eto Labs Python SDK This is the python SDK for Eto, the AI focused data platform for teams bringing AI models to production. The python SDK makes it e

null 5 Apr 21, 2022
Tools for use in DeFi. Impermanent Loss calculations, staking and farming strategies, coingecko and pancakeswap API queries, liquidity pools and more

DeFi open source tools Get Started Instalation General Tools Impermanent Loss, simple calculation Compare Buy & Hold with Staking and Farming Complete

Juan Pablo Pisano 467 Jan 8, 2023
A Pancakeswap and Uniswap trading client (and bot) with limit orders, marker orders, stop-loss, custom gas strategies, a GUI and much more.

Pancakeswap and Uniswap trading client Adam A A Pancakeswap and Uniswap trading client (and bot) with market orders, limit orders, stop-loss, custom g

null 570 Mar 9, 2022
Andrei 1.4k Dec 24, 2022
A Twitter Bot that retweets and likes tweets with the hashtag #girlscriptwoc and #girlscript, and also follows the user.

GirlScript Winter of Contributing Twitter Bot A Twitter Bot that retweets and likes tweets with the hashtag #girlscriptwoc and #girlscript, and also f

Pranay Gupta 9 Dec 15, 2022