Does django-constance admin supports database backend? - django

I'm trying to setup the admin to show settings meant to be stored in database backend (Postgres 9.5.0). I manually created values in shell_plus as follows:
In [1]: from constance.backends.database.models import Constance
In [2]: first_record = Constance.objects.get(id=1)
In [3]: first_record
Out[3]:
pg-admin properly shows the entry although django admin doesn't show it at all. I ran migrate command for both databases (I have default and product databases) but the record still is not showing up. Certainly I can make it work with forcing to register with admin as follows:
admin.site.register(Constance)
but my question is if it's necessary?

Yes, they do.
You need to manage dependencies, but you can just use next command to install:
pip install "django-constance[database]"
Also you need to add some additionl settings to your settings.py :
CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend'
INSTALLED_APPS = (
# other apps
'constance.backends.database',
)
#optional - in case you want specify table prefix
CONSTANCE_DATABASE_PREFIX = 'constance:myproject:'
Then you need to apply migrations by running command python manage.py migrate database
For displaying settings inputs in admin you should specify them in your settings.py. There are various types of fields and you even can add your own types of fields using CONSTANCE_ADDITIONAL_FIELDS parameter.
CONSTANCE_CONFIG = {
'THE_ANSWER': (42, 'Answer to the Ultimate Question of Life, '
'The Universe, and Everything'),
}
You can read more at documentation page.

Related

Best way to update my django model coming from an external api source?

I am getting my data through requesting an api source, then I put it in my django model. However, data update daily.. so how can I update these data without rendering it everytime?
def index (request):
session = requests.Session()
df = session.get('https://api.coincap.io/v2/assets')
response= df.json()
coin = response['data']
final_result = coin.to_dict('records')
for coin in final_result:
obj, created = Coincap.objects.update_or_create(
symbol = coin['symbol'],
name = coin['name'],
defaults = {
'price': coin['priceUsd']
})
return render(request, '/home.html/')
Right now, I have to go to /home.html , if I want my data update. However, my goal is to later serialize it and make it REST api data, so I wouldn't touch django template anymore. Anyway for it to update internally once a day after i do manage.py runserver?
For those that are looking for an example:
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self,*args,**kwargs):
//Your request api here
for coin in final_result:
obj, created = Coincap.objects.update_or_create(
symbol = coin['symbol'],
name = coin['name'],
defaults = {
'price': coin['priceUsd']})
Then you run in with cron just as Nikita suggested.
One simple and common solution is to create a custom Django admin command and use Cron to run it at specified intervals. You can write a command's code to your liking and it can have access to all of the models, settings and other parts of your Django project.
You would put your code making a request and writing data to the DB, using your Django models, in your new Command class's handle() method (obviously request parameter is no longer needed). And then, if for example you have named your command update_some_data, you can run it as python manage.py update_some_data.
Assuming Cron exists and is running on the machine. Then you could setup Cron to run this command for you at specified intervals, for example create a file /etc/cron.d/your_app_name and put
0 4 * * * www-data /usr/local/bin/python /path/to/your/manage.py update_some_data >> /var/log/update_some_data.log 2>&1
This would make your update be done everyday at 04:00. If your command would provide any output, it will be written to /var/log/update_some_data.log file.
Of course this is just an example, so your server user running your app (www-data here) and path to the Python executable on the server (/usr/local/bin/python here) should be adjusted for particular use.
See links for further guidance.

Biopython Entrez wanting to access /root/.config in Django app

I have some code in a Django app which does the following, to get a Pubmed article by DOI:
def getPubmedByDOI(request,doi):
Entrez.email = 'me#mydomain.com'
handle = Entrez.esearch(db="pubmed", term=doi)
record = Entrez.read(handle)
return getPubmedArticle(request,record["IdList"][0]) // renders the article
This works nicely but for one thing - the Entrez.esearch call insists upon access to /root/.config on the server, specifically to write to the following empty directory:
/root/.config/biopython/Bio/Entrez/DTDs/
It's Apache on Gentoo, running as follows:
User django
Group apache
All the code for the application is in ~django/, so I'd expect any writing to be in ~django/.config rather than /root/.config. I can work around this by changing permissions on /root but a better solution would be to configure Biopython or Apache so as not to write to /root. Does anyone have any suggestions as to how this might be done?
Logged upstream as https://github.com/biopython/biopython/issues/918 which suggests setting:
>>> from Bio.Entrez.Parser import DataHandler
>>> DataHandler.global_dtd_dir
'/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Bio/Entrez/DTDs'
>>> DataHandler.local_dtd_dir = '...'

Getting django-facebook to work

I an trying to get django-facebook to work as per instructions given in the readme on
https://github.com/tschellenbach/Django-facebook. I am new to django.
It looks simple but I am facing the following problems. I am not able to get it to work.
In the readme it says AUTH_USER_MODEL = 'member.FacebookUser'. I am guessing the right option is
AUTH_USER_MODEL = 'django_facebook.FacebookUser'
after importing the models - this took me some t even after making that change, syncdb throws an error stating that:
FacebookUser does not have a USERNAME_FIELD.
Not able to solve that I decided to use the default user model - auth.user. That works and I was able to load facebook/example. However after authentication from facebook, I get an error
You need to set AUTH_PROFILE_MODULE in your project settings
So I added AUTH_PROFILE_MODULE = 'django_facebook.FacebookProfile'
Now it returns a new error -
FacebookProfile matching query does not exist. Lookup parameters were {'user_id_exact': 2L}
What should I do now?
Do python manage.py syncdb or whatever it needs to be done to update your database schema with the new table (facebook_profile).
Also, you don't mention it but I have and app that uses django_facebook and I have my settings.py file like this:
TEMPLATE_CONTEXT_PROCESSORS = (
...
'django_facebook.context_processors.facebook',
...
)
AUTHENTICATION_BACKENDS = (
...
'django_facebook.auth_backends.FacebookBackend',
)
I hope it helps

Undetected Django app when installing from git

I'm having trouble installing django-admin_action_mail from git.
I tried to install it via:
pip install
git+https://github.com/mjbrownie/django-admin_action_mail.git
But Django did not pick it up when I added it to settings.INSTALLED_APPS.
Did I miss something?
The admin code for that app is commented out (see here: https://github.com/mjbrownie/django-admin_action_mail/blob/master/admin_action_mail/admin.py ) so nothing is going to show up on the admin page - even if it's working and enabled.
It looks as though you need to create your own models to handle the mailing functions. Take a look at the README where it tells you to add something like the following in your app's admin.py:
from admin_action_mail.actions import mail_action
class MyModelAdmin(admin.ModelAdmin):
#Note all args are optional
actions = [
mail_action(
'description' : "Send Email to Related Users",
'email_dot_path' : 'email', # dot path string to email field (eg 'user.email')
'email_template_html' : 'admin_action_email/email.html'
'reply_to' : 'noreply#example.com' # defaults to request.user.email
)
]
admin.site.register(MyModel, MyModelAdmin)
Have you added a model like that to your own app's admin.py?
EDIT: As the problem appears to be with installation, the following should help:
You can add arbitrary paths to your wsgi path spec, that means it will pick up Python app modules in other locations. Assuming your app is installed in /home/user2161049/myapp you can put your external modules under /home/user2161049/myapp/external. In this case copy the contents of that app into /home/user2161049/myapp/external/admin_action_mail/.
To add this to your settings.py:
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(SITE_ROOT, 'external'))
The first line defines SITE_ROOT based on the current running script (setup.py) at startup. The second adds the external folder into the search path. You can put anything you want in there, and even define a specific folder somewhere else if you want to keep your externals out of your app folder. Restart the server and it should find the app just fine.

Django-tinymce in Django Admin - "can't find variable: tinyMCE"

I'm trying to use django-tinymce to edit fields in django admin.
I've the app installed in my virtualenv (django-tinymce==1.5.1b4). It's listed in my installed apps -
INSTALLED_APPS = (
#...
'tinymce',
#...
)
My settings includes the following
TINYMCE_DEFAULT_CONFIG = {
'theme': "advanced",
'theme_advanced_toolbar_location': "top",
'theme_advanced_buttons1': "bold,italic,underline,separator,"
"bullist,separator,outdent,indent,separator,undo,redo",
'theme_advanced_buttons2': "",
'theme_advanced_buttons3': "",
}
TINYMCE_SPELLCHECKER = True
TINYMCE_COMPRESSOR = True
And I've got the files available at /MEDIA_ROOT/js/tiny_mce (the default).
My models look like -
from tinymce import models as tinymce_models
class MyModel(models.Model)
post = tinymce_models.HTMLField()
When I go to the model admin page, the field appears as a normal text field and my browser tells me there's an error on the inline js script for the field. It says it doesn't recognise the variable tinyMCE. It doesn't look like the page is even trying to load the js file (I'm getting no 404's - I can't see any sign of anything being loaded).
I'm not sure what I'm missing..
Have You, Sir, done python manage.py collectstatic ?
What value variable in settings.py is in TINYMCE_JS_ROOT and TINYMCE_JS_URL
If variable TINYMCE_JS_URL is not set check if You, Sir, have file at /MEDIA_ROOT/js/tiny_mce/tiny_mce.js. If not, try to copy manually from django-tinymce's egg.
OK, looks like it might have been a bug in the django_tinymce code. I've reverted to 1.5.1b2 and everything works as expected. Guess I should look into filing a bug report.