I have an application which is made of several apps. The thing is that by default, only 1 app is installed. I called it 'base'. This base app enables the user to manage users, groups (but that isn't the point here) AND should enable users to install other apps on runtime (that is the point).
I created an Application model.
In my UI, I list all the applications with a button install aside of it.
The idea is, when I click on this button, to :
Mark the application as installed
Add it to the App registry on runtime (that's the blocking point)
Apply the migration for this app
So here are some samples of code :
My Application model :
from django.apps import apps
from django.conf import settings
from django.core import management
from django.db import models
class Application(models.Model):
class Meta:
db_table = 'base_application'
name = models.CharField(max_length=255, unique=True)
verbose_name = models.CharField(max_length=255)
version = models.CharField(max_length=255, null=True, blank=True)
summary = models.CharField(max_length=255)
description = models.TextField(null=True, blank=True)
is_installed = models.BooleanField(default=False)
is_uninstallable = models.BooleanField()
My install() method would look like :
I know there are mistakes in it and that is the point of this question. I don't understand how the App Registry actually works.
Note that I must provide the reverse of it too (uninstall)
def install(self):
self.is_installed = True
self.save()
settings.INSTALLED_APPS.append(self.name)
apps.populate(settings.INSTALLED_APPS)
self.migrate()
My migrate() method :
def migrate(self):
management.call_command('makemigrations', self.name, interactive=False)
management.call_command('migrate', self.name, interactive=False)
The usual error I get is No installed app with label ....
Thanks in advance for your help. I can precise if needed.
Related
I have been building a web app using the Django framework to allow me to ping certain IPs periodically to see if they are online. The setup of the app requires different IPs in different groups. When I have added the python ping function into my model it says that the IPs are not reachable.
Below is my models.py for the project. As you can see I have included the pythonping ping function to try and ping the IPs in question, but it does not seem to work.
from cgitb import text
from ipaddress import ip_address
from django.db import models
from pythonping import ping
#import macaddress
# Create your models here.
class WS_Building_location(models.Model):
Building = models.CharField(max_length=200)
#date_added = models.DateTimeField(auto_now_add =True)
class Meta:
verbose_name_plural = 'Buildings'
def __str__(self):
return self.Building
class WS_address(models.Model):
"""Wyrestorm address"""
building = models.ForeignKey(WS_Building_location, on_delete=models.CASCADE)
ws_ip = models.GenericIPAddressField()
#mac_address = models.macaddress()
date_added = models.DateTimeField(auto_now_add=True)
ipstr = str(ws_ip)
ip_ping = models.TextField(ping('ipstr', verbose = False))
class Meta:
verbose_name_plural = 'addresses'
def __str__(self):
return self.ws_ip
I have read that the pythonping module needs to have root access in order to create the raw packets it uses as a ping and it is not recommended that django be root for security concerns. Any help would be greatly appreciated as I am a novice at this sort of thing but willing to learn!
Now I had a problem
RuntimeError: Can't resolve dependencies while running tests and after long debugging We found that a forigen key relationship is the problem
Yet we need this relation in our app
I have to get an owner relation to Django Groups
The models like that:
class UserAccount(AbstractUser):
arabic_name = models.CharField(max_length=128, default='', blank=True)
parent = models.ForigenKey('self', null=True)
django.contrib.auth.models import Group
Group.add_to_class('owner', models.ForeignKey('users.UserAccount',
blank=True,
null=True,
related_name='groups_created'
))
As I need to define an owner to the groups as I have my specific hierarchy system for users so no one can see others groups
So what Can I do?
Update - Solution
class UserAccount(AbstractUser):
arabic_name = models.CharField(max_length=128, default='', blank=True)
hierarchy_id = models.PositiveIntegerField()
django.contrib.auth.models import Group
Group.add_to_class('hierarchy_id', models.PositiveIntegerField(null=True))
#script populate hierarchy
h_id=0
for user in users:
if user.is_parent:
then user.hierar...... = h_id
and so on.. I populated hierarchy ID instead of relation
Thanks
Actually I found you can do a circular dependency without your knowledge, in case you do a relation and migrate it then do the reverse relation after a while then migrate it , it will not clash but when both migrated instantly in tests for example it will clash. so I tried this solution and tested, after a year from asking the question, it is working well.
class UserAccount(AbstractUser):
arabic_name = models.CharField(max_length=128, default='', blank=True)
hierarchy_id = models.PositiveIntegerField()
django.contrib.auth.models import Group
Group.add_to_class('hierarchy_id', models.PositiveIntegerField(null=True))
#script populate hierarchy
h_id=0
for user in users:
if user.is_parent:
then user.hierar...... = h_id
I have below model:
class Property(models.Model):
job = models.ForeignKey(Job, on_delete=models.CASCADE)
app = models.ForeignKey(App, on_delete=models.CASCADE)
name = models.CharField(max_length=120)
value = models.CharField(max_length=350, blank=True)
description = models.TextField(blank=True)
pub_date = models.DateTimeField('date_published', default=timezone.now)
class Meta:
verbose_name_plural = "properties"
unique_together = (('value', 'name'),)
def __str__(self):
return self.name
When I try to create a Property object in admin page (I'm using Django Suit) with name/value which are already exist I get the exception: "Property with this Value and Name already exists." So it works perfect.
But in manage.py shell:
>>>from myapp.models import App, Property, Job
>>>from django.shortcuts import get_object_or_404
>>>app = get_object_or_404(App, app_name='BLABLA')
>>>job = get_object_or_404(Job, job_name='BLABLA2')
>>> Property.objects.create(job=job, app=app, name='1', value='1')
<Property: 1>
>>> Property.objects.create(job=job, app=app, name='1', value='1')
<Property: 1>
In this case I do not get any exceptions and objects are added in database.
I tried makemigrations, migrate and migrate --run-syncdb.
Django 1.9.12, sqlite3
The unique constraints are enforced at database level. You're not getting any error probably because SQLite doesn't support this type of constraint. You cannot add constraint to existing table in SQLite. If you're in early development stage, drop the table and recreate it with updated constraints. Then it should work fine in shell.
Check SQLite alter table docs for allowed updates on an existing table.
The admin form throws error because it checks uniqueness by itself without relying on database constraints.
I have models like this:
class Subscription(models.Model):
visable_name = models.CharField(max_length=50, unique=True)
recipe_name = models.CharField(max_length=50)
website_url = models.URLField()
class User(models.Model):
username = models.CharField(max_length=50)
class UserSubs(models.Model):
subscription = models.ForeignKey(Subscription, to_field='visable_name')
user = models.ForeignKey(User, to_field='username')
And I want to prepare simple ranking, so I came up with something like this: Subscription.objects.annotate(total=models.Count('usersubs')).order_by('-total')
The true problem is that I just discovered that my "simple ranking" should be in another App, where I can't even do from FirstApp import models.Subscription, becouse I get ImportError: cannot import name Subscription.
I actually have no idea how it has to be done.. Maybe should I give up from separate these two Apps?
I still don't really understand why you are trying to split these up, but it seems likely you have a circular dependency: your model files are both trying to import each other. You probably need to remove the import from one side: note that if you're importing simply to use as a reference in defining a ForeignKey, you can use a string: models.ForeignKey('FirstApp.Subscription') instead of the actual class.
I have a model:
class Server(models.Model):
serverId = models.IntegerField(verbose_name=_("serverId"))
name = models.CharField(max_length=200, verbose_name=_("server_name"))
ip = models.CharField(max_length=200, verbose_name=_("ip"))
cport = models.IntegerField(default=5000, verbose_name=_("cport"))
aport = models.IntegerField(default=1000, verbose_name=_("aport"))
hport = models.IntegerField(default=2000, verbose_name=_("hport"))
version = models.CharField(max_length=100, verbose_name=_("version"))
serverGroup = models.ForeignKey(Group, null=True, blank=True,
verbose_name=_('server_group'))
class Meta:
db_table = u'server'
def __unicode__(self):
return self.name
and the modelform:
class ServerForm(ModelForm):
class Meta:
model = Server
from within this app directory I did
$ mkdir locale
$ django-admin.py makemessages -l zh_CN
then I provided the translation in locale/zh_CN/LC_MESSAGES/django.po
then I did
$ django-admin.py compilemessages
then I ran the development server:
$ python manage.py runserver
and went to look at the url http://127.0.0.1:8000 in firefox and the translation displayed. So I thought I did right and I deployed the project on the same machine using nginx + fastcgi with nothing changed in the whole project. Then I go to the url http://127.0.0.1, and then the the modelform shows English there. It didn't localize to Chinese.
I've googled much and read many docs from docs.djangoproject.com and still don't know how to solve the problem. So I ask here.
I only set LANGUAGE_CODE = 'zh_CN' in my settings.py and leave everything on deafult. My django version is 1.2.4
Any of your comments are appreciated.
Make sure you are using lazy_translation. Are you importing ugettext_lazy or ugettext?
from django.utils.translation import ugettext_lazy as _
http://docs.djangoproject.com/en/dev/topics/i18n/internationalization/#lazy-translation
For information, django takes the first argument as the verbose name of a field.
So you can also write your models in a shorter way, like this :
version = models.CharField(_("version"), max_length=100)
serverGroup = models.ForeignKey(_('server_group'), Group, null=True, blank=True)
On version 1.4 it works only (for me) with ugettext not with ugettext_lazy