I'm trying to implement custom field in my model following the docs, My model is as follow:
class User(AbstractUser):
uid = models.CharField(
"uid", max_length=255, null=True, blank=True)
phone_number = models.CharField(
"Phone number", max_length=255, null=True, blank=True)
nickname = models.CharField(
"Nickname", max_length=255, null=True, blank=True)
eth_address = models.CharField("Eth address", max_length=255, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
# deleted
class eth_address_decrypted(models.Field):
description = 'eth_address_decrypted'
def __init__(self, *args, **kwargs):
return decrypt_string(self.eth_address)
class Meta:
db_table = "users"
pass
I have a eth_address field that it's value are encrypted, i need to display the decrypted value on the frontend, so i wrote custom field model as the docs and call it on my front end through query:
User.objects.get(eth_address_decrypted=value)
But it returning the following error:
Cannot resolve keyword 'eth_address_decrypted' into field. Choices are: created, date_joined, email, eth_address,
What am i doing wrong ?
Is there a way i can call user.eth_address_decrypted on object as a custom field or function without migrating it ? (because eth_address_decrypted just a convert from existed eth_adress)
Related
I have a model with 2 M2M attributes: Connection is recursive and the ConnectionRequest uses an intermediary class. With Connection attribute, I am able to retrieve the connections of a user without problems (since I am using a native M2M field). But with ConnectionRequest is where I have challenges.
I would like to retrieve the 'connection requests' for this user but struggling with this natively. I have implemented it however programmatically (through a query) - but its not clean.
Basically, I would like to return the list of all connection requests. ie where the recipientAccount is the same as the parent class (Account) object.
class Account(models.Model):
firstName = models.CharField(
'First Name', max_length=100, blank=True, null=True)
lastName = models.CharField(
'Last Name', max_length=100, blank=True, null=True)
emailAddress = models.EmailField(
'Email Address', max_length=255, blank=True, null=True, unique=True)
connections = models.ManyToManyField('self', blank=True)
connection_requests = models.ManyToManyField(
'ConnectionRequest', blank=True, related_name='accounts')
def __str__(self):
return self.firstName + ' ' + self.lastName
class ConnectionRequest(models.Model):
senderAccount = models.ForeignKey(
Account, related_name='sender_Account', on_delete=models.CASCADE)
recipientAccount = models.ForeignKey(
Account, related_name='recipient_Account', on_delete=models.CASCADE)
def __str__(self):
return str(self.senderAccount.id) + ' to ' + str(self.recipientAccount.id)
I have an idea to try the below but suddenly realised that I am unable to access the Account object from the ConnectionRequest class (since its a parent object/class).
class ConnectionRequest(models.Model):
def __str__(self):
return self.__class__.objects.filter(
Q(recipientAccount=recipientaccount))
Should I be looking to implement this in the Account model? Perhaps as a method?
Thanks!
I would like to get the model name from the content type.
I have tried this ....
a=Module.objects.filter(slug="sales")
So it return SoftDeletionQueryset
So after that I just done the following
for x in a: print(x.content_type)
So it return "sales analytics". That is the content_type value in the Module.content_type field
I have the content_type values now ..... The content type model having the 3 fields right ? app_label,model,name So I want to get the model name according to the content_type values –
Here is my code
class Module(BaseModel, SoftDeletionModel):
id = models.AutoField(primary_key=True)
name = models.CharField(
_("Module Name"), max_length=50, default=False, unique=True)
slug = models.SlugField(unique=True)
display_name = models.CharField(
_("Display Name"), max_length=50, default=False)
content_type = models.ForeignKey(ContentType,
blank=True, null=True, on_delete=models.CASCADE)
parent_module_id = models.ForeignKey("Module",
blank=True, null=True, on_delete=models.CASCADE)
order = models.IntegerField(_("Order"), default=0, blank=True, null=True)
class Meta:
db_table = 'modules'
def __str__(self):
return "{0}".format(self.display_name)
I don't really understand the question, but I will try to answer
You use print() and it returns __str__ func result.
If you want to get the model name you have to use this code or content_type
modules = Module.objects.filter(slug="sales")
for m in modules:
print(m.name)
print(m.content_type)
If you mean exactly classname
For that use .__class__.__name__ or Module.__name__
I have the following models:
class Address(models.Model):
address1 = models.CharField(max_length=150, null=True)
address2 = models.CharField(max_length=150, null=True, blank=True)
city = models.CharField(max_length=50, null=True)
state_province = models.CharField(max_length=50, null=True)
zipcode = models.CharField(max_length=10, null=True)
country = models.CharField(max_length=3, default='USA', null=False)
created_at = models.DateTimeField(db_index=True, auto_now_add=True)
updated_at = models.DateTimeField(db_index=True, auto_now=True)
class Meta:
db_table = 'addresses'
and this one.....
class User(models.Model, AbstractBaseUser, PermissionsMixin):
email = models.EmailField(db_index=True, max_length=150, unique=True,
null=False)
first_name = models.CharField(max_length=45, null=False)
last_name = models.CharField(max_length=45, null=False)
mobile_phone = models.CharField(max_length=12, null=True)
profile_image = models.CharField(max_length=150, null=True)
is_staff = models.BooleanField(db_index=True, null=False, default=False)
is_active = models.BooleanField(
_('active'),
default=True,
db_index=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
addresses = models.ManyToManyField(Address),
USERNAME_FIELD = 'email'
objects = MyCustomUserManager()
def __str__(self):
return self.email
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email
class Meta:
db_table = 'users'
My first mystery is that by migrating the models, there is no "addresses" field in the users table, nor a pivot table in the database to keep the multiple relationships. How are ManyToMany payloads kept??
Secondly, my goal is to have multiple addresses for Users. I want Users to have multiple "Addresses" (and not each address having one User) because other models can have addresses too. I don't want the Address model to have 12 different "owner" fields with with ForeignKeys.
So. I try this:
from myApp.models import User
from myApp.models import Address
user = User(email="test#test.com", first_name="john", last_name="doe", mobile_phone="444")
# the model permits partial address fields, don't worry about that.
address = Address(city="New York", zipcode="10014")
Now I try to add the address to the user.addresses and I'm getting an error.
user.addresses.add(address)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-0337af6b1cd4> in <module>()
----> 1 user.addresses.add(address)
AttributeError: 'tuple' object has no attribute 'add'
Help?
You have a superfluous comma after the definition of the many-to-many field, which turns it into a tuple. When you've removed this, you'll find both that the migrations will create your intermediary table, and that user.addresses.add() will work.
Hi i am Setting the value of one field of my Django model equal to value of other field of Other model. This value should change dynamically.
This is my first model
class MainModel(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='Email Address',
max_length=255,
unique=True)
payment_online = models.ForeignKey(OnlinePayments, null=True, blank=True)
register_date = models.DateTimeField(default=datetime.now, blank=True)
purchase_date = models.CharField(max_length=32, default='')
is_csr = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
This is second model
class OnlinePayments(models.Model):
payer_email = models.CharField(max_length=255, default=None, null=True)
payer_name = models.CharField(max_length=255, default=None, null=True)
timestamp = models.DateTimeField(auto_now_add=True, blank=True)
def __str__(self):
return self.payer_email
i want to set the value of purchase_date in MainModel equal to value of timestamp in OnlinePayments.
Any help would be appericiated
You don't actually need to maintain two fields with the same value.
I'd define a method on MainModel and get the timestamp from the related model:
class MainModel(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='Email Address',
max_length=255,
unique=True)
payment_online = models.ForeignKey(OnlinePayments, null=True, blank=True)
...
def get_purchase_date(self):
return self.payment_online.timestamp if self.payment_online else None
I think #alecxe provided a great answer.
However, if you really want to store the information in 2 places you can override the save method on the OnlinePayments model so that whenever a record is saved on that model, you can manually save the timestamp value to purchase_date in MainModel.
Add the following save method to your OnlinePayments model (filling in the purchase_date assignment under the comment)
def save(self, *args, **kwargs):
# save the value of self.timestamp into purchase_date
super(OnlinePayments, self).save(*args, **kwargs)
I'm trying to save an existing instance of a customer record. Its model has a M2M to the vehicle model (since a customer can multiple vehicles). After reading several questions/answer here, I still do not know how to solve this.
Customer model:
class Customer(models.Model):
vehicle_id = models.ManyToManyField(VehicleSale)
name = models.CharField(max_length=40, blank=True, db_index=True, null=True,
verbose_name='name')
lic = models.CharField(max_length=20, blank=True, db_index=True, null=True,
verbose_name='license')
addr = models.CharField(max_length=40, blank=True, null=True, verbose_name='address')
city = models.CharField(max_length=15, blank=True, null=True, verbose_name='city')
state = models.CharField(max_length=2, blank=True, null=True, verbose_name='state')
zip = models.CharField(max_length=10, blank=True, null=True, verbose_name='zipcode')
email = models.EmailField(blank=True, null=True, verbose_name='email')
tel1 = models.CharField(max_length=15, blank=True, verbose_name='Tel. 1', null=True)
tel2 = models.CharField(max_length=15, blank=True, verbose_name='Tel. 2', null=True)
ssn = models.CharField(max_length=12, blank=True, db_index=True, null=True,verbose_name='SSN')
class Meta:
db_table = 'customer'
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
self.name = self.name.upper()
self.addr = self.addr.upper()
self.city = self.city.upper()
self.state = self.state.upper()
return super(Customer, self).save(*args, **kwargs)
In the view, after defining customer as
customer = current_vehicle.customer_set.all()
I tried the following:
if 'customer' in request.POST:
if customer:
customer_form = CustomerForm(request.POST, instance=customer[0])
if customer_form.is_valid():
customer_form.save()
Also tried adding before customer_form is defined:
customer.vehicle_id = current_vehicle.id
And then this after the form:
customer_form.vehicle_id = current_vehicle.id
Form is not valid so it's not saved. Upon checking {{ form.errors}}, it always reports vehicle_id is required.
Finally, after the answer in this, I adjusted it to my scenario by adding:
obj = customer_form.save(commit=False)
and hoping to assign vehicle_id, but it fails immediately.
What am I missing?
Thanks.
1st EDIT:
The section on the view now looks as:
customer_form = CustomerForm(request.POST, instance=customer[0])
customer_form.save()
customer_form.vehicle_id.add(current_vehicle)
You are misunderstanding what a ManyToMany field is here:
customer_form.vehicle_id = current_vehicle.id
vehicle_id is defined as a ManyToMany field on your Customer model, therefore you can't just assign a single id to it. You have to add an instance of VehicleSale model, eg:
customer_form.vehicle_id.add(current_vehicle)
See docs here:
https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/
See also this answer for why you can't save until you populate the vehicle_id relation:
https://stackoverflow.com/a/2529875/202168