I am new on Python3 and DJango.
I am writing an app where the user can register a Company using Company Name and AWS Access Key and Secret Key.
I will use the Access and Secret key to make a inventory "Discovery" of the AWS Account.
Well, I want what every time an user register a company (click to create) django executes a management command called infra_discovery.py inside my app_folder/management/commands (that is working fine when I call via python manage.py infra_discovery).
I have the following model:
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
from empresa.models import Empresa
class InfraDiscovery(models.Model):
# user will fill this three fiels:
infra_empresa = models.ForeignKey('empresa.Empresa', on_delete=models.CASCADE, blank=True, null=True )
infra_aws_key = models.CharField(max_length=100, null=True, blank=True)
infra_aws_secret = models.CharField(max_length=255, null=True, blank=True)
# my script called infra_discovery have to fill this fields:
infra_vpc = models.TextField(blank=True, null=True )
infra_ec2 = models.TextField(blank=True, null=True )
infra_ebs = models.TextField(blank=True, null=True )
infra_rds = models.TextField(blank=True, null=True )
infra_vpn = models.TextField(blank=True, null=True )
infra_bill = models.TextField(blank=True, null=True )
def __str__(self):
return self.id
def get_absolute_url(self):
return reverse('infrastructure_discovery_edit', kwargs={'pk': self.pk})
I really don't know how to make django fulfill this fields using my script at every time user clicks in "create" button;
What are your suggestion to me?
Related
In My Django Project, there are two apps: Login and Company
The error that am receiving in this is
AttributeError: module 'login.models' has no attribute 'Country'
Company App > models.py
from django.db import models
from login import models as LM
class CompanyProfile(models.Model):
full_name = models.CharField(max_length=255,
unique = True)
country = models.ForeignKey(LM.Country,
on_delete=models.SET_NULL,
null=True,
blank=False)
state = models.ForeignKey(LM.State,
on_delete=models.SET_NULL,
null=True,
blank=False)
def __str__(self):
return self.full_name
Login App > models.py
class Country(models.Model):
"""List of Country"""
name = models.CharField(max_length=50, unique= True, default='None')
code = models.CharField(max_length=2, unique= True, primary_key=True, default ='NA')
def __str__(self):
return str(self.code)
class State(models.Model):
"""List fo State"""
region = models.CharField(max_length = 255, unique = True, primary_key=True, default='None')
country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=False, default ='NA')
def __str__(self):
return self.region
Here is test to check that weather is login is getting imported or not
def test_import():
try:
# import pdb; pdb.set_trace()
importlib.find_loader('LM.Country')
found = True
except ImportError:
found = False
print(found)
Answer is received stands to be True
python3 manage.py shell
>>> test_import()
True
Now on other stackoverflow blogs i checked i thought it could be of Circlular Import
But i have already fixed that still am getting this error?
Thanks in Advance
Regards
I am not able to see any issue here technically. Maybe Django doesn't support this alias way of mentioning model as Foreign Key which I have never tried this way.
But I would suggest to use string format for adding Foreign Key of other model as below.
class CompanyProfile(models.Model):
full_name = models.CharField(max_length=255, unique = True)
# In following line, as I mention model name in string which django understands
country = models.ForeignKey('login.Country', on_delete=models.SET_NULL,
null=True,blank=False)
Another way is simple import but it might be a problem in case of circular depedencies. So I don't recommend to use that.
I hope you get the answer out of it.
I have an IntegerField in my model and I try to update it in the admin page. No matter what value I input (e.g. 100, 200), the value is restored to 0 after saving it.
models.py
class inputform(models.Model):
name = models.CharField('Name', max_length=40)
gender_choices = (
(0,'Female'), (1,'Male'),
)
gender = models.SmallIntegerField('Gender', choices=gender_choices, blank=True)
age = models.IntegerField('Age', blank=True, null=True)
email = models.CharField('email', max_length=64, blank=True)
live_choices = (
(0,'Other'), (1,'Live alone'), (2,'Live with family'),
)
live = models.SmallIntegerField('Living Status', choices=live_choices, blank=True)
admin.py
from django.contrib import admin
from myApp.models import inputForm
class inputForm(admin.ModelAdmin):
list_display = ('id','name', 'age', 'gender')
I have tried change the value via SQL in the database directly and it updated successfully. However, when I read it in the admin page and saved it without any change, the value restore to 0.
Is there any wrong with my code? Thanks!
I want to customize Django admin select box and show thumbnail in the select box next to the image title
I have a class called Image and another class called News, that has a foreign key to the Image.
Note: I use Django jet as admin template.
class Image(models.Model):
alternate = models.CharField(
verbose_name=_('Alternate'),
max_length=255,
null=True,
blank=True
)
title = models.CharField(
verbose_name=_('Title'),
max_length=255,
null=True,
blank=True
)
artist = models.ManyToManyField(
'Artist',
verbose_name=_('Artist'),
blank=True
)
image = models.ImageField()
def __str__(self):
return "({}) {}".format(self.pk, self.title)
class Meta:
verbose_name = _('Image Attachment')
verbose_name_plural = _('Image Attachments')
#staticmethod
def autocomplete_search_fields():
return 'title',
class News(BaseModel):
title = models.CharField(
verbose_name=_('Title'),
max_length=255,
null=True,
blank=True
)
summery = RichTextField(
verbose_name=_('Summery'),
null=True,
blank=True,
)
main_image = models.ForeignKey(
Image,
verbose_name=_('Main Image'),
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name='images'
)
Now I want to show the thumbnail of the image in choices in Django admin when I want to add news.
Now my select box look like this
You will need to create a custom widget that inherits from Select, the most important part it seems will be setting the option_template_name to be a template that you create to show the image. Since you are using something other than the base Django Admin, you may want to look into extending the widgets in that Library.
Something along the lines of:
class SelectWithImage(Select):
...
option_template_name = 'myapp/forms/widgets/select_option_with_image.html'
...
Then adjust the admin formfield_overrides for the News model in your admin.py as described here and you should be good to go!
This step will look something like this:
from django.contrib import admin
from django.db import models
# Import our custom widget and our model from where they're defined
from myapp.models import News
from myapp.widgets import SelectWithImage
class NewsAdmin(admin.ModelAdmin):
formfield_overrides = {
models.ForeignKey: {'widget': SelectWithImage},
}
I am trying to upload some testing data to an app, using the option of the migrations.All the data is storaged in a .Yaml file in the app ans I have some other migrations that runs perfectly uploading all the data.
But this one has a problem. In this model (Transactions) I created 3 self-writen, fields that are calculated when calling to the save() method. This process run perfectly when I sent the data through the View. But when I send it through the migration, fails as if the save method is not overwritten. I don't know what to do to accomplish the upload as a migration.
The migration
from django.db import migrations
from django.core import serializers
def transactions(apps, schema_editor):
with open('fixtures/transactions.yaml') as trans:
for obj in serializers.deserialize("yaml", trans):
t=apps.get_model("acounts", "Transactions")()
cat=apps.get_model("acounts","Category")
.objects.get(pk=obj.object.category.pk)
cuen=apps.get_model("acounts", "Acount").objects.get(pk=obj.object.acount.pk)
print(obj)
t.tipo=obj.object.tipo
t.description=obj.object.description
t.monto=obj.object.monto
t.date=obj.object.date
# t.category=obj.object.category
t.category=cat
# t.acount=obj.object.acount
t.acount=cuen
t.save()
class Migration(migrations.Migration):
dependencies = [
('acounts', '0002_populate_acounts'),
]
operations = [
(migrations.RunPython(transactions))
]
The Model
class Transactions(models.Model):
TYPE_CHOICES = (
('GASTO', 'Gasto'),
('INGRESO', 'Ingreso'),
)
tipo = models.CharField(
choices=TYPE_CHOICES,
max_length=20
)
description=models.CharField(max_length=100)
monto=models.DecimalField(max_digits=25,
decimal_places=2,
null=False)
category=models.ForeignKey('Category',
on_delete=models.CASCADE,
null=False)
acount=models.ForeignKey('Acount',
on_delete=models.CASCADE,
null=False)
date=models.DateField()
total_USD=models.DecimalField(
max_digits=25,
decimal_places=2,
editable=False);
total_BTC=models.DecimalField(
max_digits=25,
decimal_places=9,
editable=False);
total_BSS=models.DecimalField(
max_digits=25,
decimal_places=2,
editable=False);
total_EUR=models.DecimalField(
max_digits=25,
decimal_places=2,
editable=False);
created_at=models.DateTimeField(
auto_now_add=True,
editable=False)
updated_at=models.DateTimeField(
auto_now=True,
editable=False)
def save(self):
cotizations=Currency.objects.all()
currency=self.acount.currency.name
in_usd=self.monto/Currency.objects.get(name=currency).price_USD_now
query_btc=in_usd*Currency.objects.get(name='BTC').price_USD_now
query_bss=in_usd*Currency.objects.get(name='YEN').price_USD_now
query_eur=in_usd*Currency.objects.get(name='EUR').price_USD_now
self.total_USD=in_usd
self.total_BTC=query_btc
self.total_YEN=query_bss
self.total_EUR=query_eur
super(Transactions, self).save()
return query_btc;
The Error
raise utils.IntegrityError(*tuple(e.args))
django.db.utils.IntegrityError: (1048, "Column 'total_USD' cannot be null
The same method runs perfect when done trough the view, How could I create a data migration for this model using the overwritten .save() method?
I have a Django app that works perfectly on google app engine, using the datastore via djangae. However, the admin site throws an error:
NotSupportedError at /admin/auth/user/5629499534213120/change/
Cross-join where filters are not supported on the Datastore
This error only occurs when trying to edit the default Django user model. Not sure why this is happening.
I have used the default Django user model. (this is an app dealing with donations for a nonprofit)
models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class FoodSplashUser(models.Model):
base_user = models.OneToOneField(User, on_delete=models.CASCADE)
address = models.TextField(null=True)
city = models.TextField(null=True)
state = models.CharField(max_length=4, null=True)
zip = models.CharField(max_length=10, null=True)
def __str__(self):
return str(self.base_user.username)
class Organization(models.Model):
base_user = models.OneToOneField(User, on_delete=models.CASCADE)
address = models.TextField(null=True)
city = models.TextField(null=True)
state = models.CharField(max_length=4, null=True)
zip = models.CharField(max_length=10, null=True)
description = models.TextField(null=True)
image_url = models.URLField(null=True)
def __str__(self):
return str(self.base_user.username)
class DonationRequest(models.Model):
organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now=True)
request_type = models.TextField(null=True)
description = models.TextField(null=True)
def __str__(self):
return str(self.organization.base_user.username) + " " + self.request_type
class DonationPromise(models.Model):
user = models.ForeignKey(FoodSplashUser, on_delete=models.CASCADE)
donation_request = models.ForeignKey(DonationRequest, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now=True)
verified = models.BooleanField(default=False)
def __str__(self):
return str(self.user.base_user.username) + " " + str(self.donation_request)
This app goes with the default Django admin interface, but I decided to make the classes below for easy editing later.
admin.py:
from django.contrib import admin
from . import models
# Register your models here.
class FoodSplashUserAdmin(admin.ModelAdmin):
pass
class OrganizationAdmin(admin.ModelAdmin):
pass
class DonationRequestAdmin(admin.ModelAdmin):
pass
class DonationPromiseAdmin(admin.ModelAdmin):
pass
admin.site.register(models.FoodSplashUser, FoodSplashUserAdmin)
admin.site.register(models.Organization, OrganizationAdmin)
admin.site.register(models.DonationRequest, DonationPromiseAdmin)
admin.site.register(models.DonationPromise, DonationPromiseAdmin)
This may be a separate error, but :
admin.site.register(models.DonationRequest, DonationPromiseAdmin)
admin.site.register(models.DonationPromise, DonationPromiseAdmin)
Shouldn't that first one be: DonationRequestAdmin?
NotSupportedError indicates that your code performs an action that is not possible with App Engine Datastore. Not all the Django ORM features can be used in a non-relational database which Datastore is. You are trying to create an entity that has some relations, which causes the error. Probably it is a good idea to use Gauth for authentication and user management, as described in the Djangae docs.