Django shell get models object function does not work any ideas? - django

i have tried to look at the django documentation but cant find what i am looking for. I have a django models, and in this model i have defined som logic, the problem is that i cant get the value when i try fetching the recepie through django shell. I want to se if the def recepie_status is working.
My model:
class Recepie(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=60, null=False, blank=True, verbose_name='Recepie name')
description = models.TextField(max_length=500, null=True, blank=True, verbose_name='Description')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
# slug = models.SlugField(max_length=255, verbose_name=_('Recepie Slug'), default=name)
share = models.BooleanField(null=True, blank=True)
def recepie_status(self):
import datetime
import date, timedelta, datetime
status=(date.today()-timedelta(days=15))
if self.created_at > status:
return "New"
else:
return "Old"
i have done this in the django shell:
>>> one = Recepie.objects.get(pk=1)
>>> print (one.name) #this works
>>> from datetime import timedelta, date, datetime
>>> print (one.recepie_status())
throws this error in the django shell
E:\Projekt\Fooders\fooders\recepies\models.py in recepie_status(self)
18
19 def recepie_status(self):
20 status=(date.today()-timedelta(days=15))
21 if self.created_at > status:
22 return "New"
ModuleNotFoundError: No module named 'date'

The issue in the following line
import date
import date is cause of the error,
to import date do the following
from datetime import date

Related

Django unit testing FileField and ImageField using ContentFile

I am using Django 3.2
I have a model like this:
Foo class
class Foo(models.Model):
name = models.CharField(max_length=124)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
description = models.TextField()
bio = models.TextField()
attachment = models.FileField()
photo = models.ImageField()
recorded_date = models.DateField()
time_of_day = models.TimeField()
timestamp = models.DateTimeField()
duration = models.DurationField()
website = models.URLField()
pseudo_array = models.CharField(max_length=256)
pseudo_tags = models.CharField(max_length=128)
Snippet of Unit test
import glob
import os
import json
from datetime import datetime, timedelta
from django.utils.timezone import make_aware
from model_bakery import baker
from django.test import TestCase
from django.core.exceptions import ValidationError
from django.core.files.base import ContentFile
image_mock =ContentFile(b"R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==", name='photo.png')
file_mock = ContentFile("Some random text", name='archive.txt')
class TestModels(TestCase):
def setUp(self):
current_timestamp = datetime.now(timezone.utc)
self.foo = Foo.objects.create( name='Accepted Object',bio='For accepted testing',
owner=self.pattysmith,
description='Object for accepted testing',
attachment = file_mock,
photo = image_mock,
recorded_date = datetime.strptime('20200101','%Y%m%d'),
time_of_day = datetime.strptime('10:00','%H:%M'),
timestamp = make_aware(timezone.now().strptime('20200101 10:00','%Y%m%d %H:%M')),
duration = timedelta(days=20, hours=10),
website = 'https://www.accepted.com',
moderation_status=1,
pseudo_tags='approved,nice, accepted'
)
def tearDown(self):
Foo.objects.all().delete()
User.objects.all().delete()
for f in glob.glob("*.png"):
os.remove(f)
for f in glob.glob("*.txt"):
os.remove(f)
def test_change_moderated_char_field(self):
self.foo.name='My new name'
self.foo.save(update_fields=['name'])
# test for number of changed fields ...
When I run the test test_change_moderated_char_field I see that the file and image field names have changed - looks like Django is auto-generating the file names.
Here is what my console printout looks like:
moderated_field_current_field_value: 'My new name' != 'Accepted Object' for moderated field: name
moderated_field_current_field_value: /path/to/archive_Fo8NWLI.txt != /path/to/archive.txt for moderated field: attachment
moderated_field_current_field_value: /path/to/photo_mVEyGtI.png != /path/to/photo.png for moderated field: photo
######### changed_fields: ["name", "attachment", "photo"] #####
I am currently accessing the name of the file/image by accessing the path attribute on the field. How do I get the name of the file when it is actually uploaded (since some name mangling seems to be taking place?

Overwriting Datetime is not working in Postgresql in Django

So what I need to do is to change few rows in a model DateTime field to 40 days in the past, with Django using a PostgreSQL database. Where I choose all products with an even ID and change the date_uploaded value.
This is what I am currently doing...
from django.core.management.base import BaseCommand
from store.models import Product
import datetime
class Command(BaseCommand):
def handle(self, *args, **options):
all_products = Product.objects.all()
for product in all_products:
if product.pk % 2 == 0:
product.date_uploaded = product.date_uploaded - datetime.timedelta(40,2,0,0)
product.save()
print(product.date_uploaded)
And for some reason when I try to save the product it works with no errors but the DateTime value is not changed. Is there anything wrong with what I am doing?
this is my models.py
class Product(models.Model):
image1 = models.ImageField(upload_to="product_images", default="https://eblossomsl.s3-us-west-2.amazonaws.com/logo.png")
image2 = models.ImageField(upload_to="product_images", blank=True)
image3 = models.ImageField(upload_to="product_images", blank=True)
image4 = models.ImageField(upload_to="product_images", blank=True)
name = models.CharField(max_length=100, unique=True)
category = models.CharField(choices=CATEGORY, max_length=20, default="HRT", db_index=True)
price = models.PositiveIntegerField()
search_query = models.TextField(blank=True, null=True)
date_uploaded = models.DateTimeField(auto_now=timezone.now())
quantity_bought = models.PositiveIntegerField(default=0)
Any help would be greatly appreciated since I am not sure what I am doing wrong.
The problem is in auto_now argument passed into DateTimeField, this argument is responsible for changing the value of the field to the current datetime each time .save() is called on the object, i.e. every time you are running your script it sets it to current datetime and your changes are ignored. What you really need is auto_now_add which sets the value only once at the object creation.
date_uploaded = models.DateTimeField(auto_now_add=timezone.now())
Run makemigrations, apply them and run your script again.

Delete an user object automatically after some time in django models

I want automatically delete the user object or make default="" in my model after 2 min.
Here is my model. What am I doing wrong!!
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime, timedelta
from django.utils import timezone
from datetime import date
class Action(models.TextChoices):
REQUESTED = 'Requested'
ACCEPTED = 'Accepted'
REJECTED = 'Rejected'
class UserMembership(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=255, default='')
student_id = models.CharField(max_length=10, default='')
membership_type = models.CharField(max_length=50)
membership_action = models.CharField(max_length=50, choices=Action.choices, default=Action.REQUESTED)
start_date = models.DateTimeField(default=timezone.now,blank=True,)
#property
def delete_after_thirty_days(self):
time = self.start_date + datetime.timedelta(minutes=2)
if time < datetime.datetime.now():
e = UserMembership.objects.get(user=self.user)
e.delete()
return True
else:
return False
def __str__(self):
return self.name
Basically, after 2 minutes the values of the UserMembership model related to the specific user should be deleted or change back to default values. currently, nothing happens and I don't get any errors as well. Thank you for your time.

Attribute Error in Django model Foreign Key

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.

Django: How to create a record in different app/model post saving the data in current model

Following are my apps and respective models:
Project name: django03
app: home
home/model.py
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
# Create your models here.
User = settings.AUTH_USER_MODEL
HOME_TYPE = (
('1','1'),
('2','2'),
('3','3'),
)
class Home(models.Model):
home_owner = models.ForeignKey(User,null=False, verbose_name='Owner')
hometype= models.CharField(max_length=100, null=False, default=1,
choices=HOME_TYPE, verbose_name='Home Type')
licenseid= models.CharField(max_length=200, null=False, unique=True,
verbose_name='License ID')
archive = models.BooleanField(default=False)
def __str__(self):
return self.licenseid
app: furniture
furniture/model.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import models
# Create your models here.
User = settings.AUTH_USER_MODEL
FURNITURE_DATA_IMPORT_SOURCE= (
('0', '0'),
('1', '1'),
('2', '2'),
)
class Furniture(models.Model):
furniture_owner = models.ForeignKey(User, verbose_name='User')
furniture_imported_via = models.CharField(max_length=200, default="0", null=False, choices=FURNITURE_DATA_IMPORT_SOURCE, verbose_name='Source of import')
furniture_title = models.CharField(max_length=100, null=False, verbose_name='Furniture title')
furniture_description = models.TextField(max_length=250, verbose_name='Furniture description')
archive = models.BooleanField(default=False)
def __str__(self):
return self.furniture_title
app:mappings
mappings/model.py
from __future__ import unicode_literals
from django.db import models
from home.models import Home
from furniture.models import Furniture
class HomeFurnitureMapping(models.Model):
home = models.OneToOneField(
Home,
on_delete=models.CASCADE,
null=False,
unique=True,
verbose_name='Home'
)
furniture = models.OneToOneField(
Furniture,
on_delete=models.CASCADE,
null=False,
unique=True,
verbose_name='Furniture'
)
app: furnitureupdates
furnitureupdates/model.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from mappings.models import HomeFurnitureMapping
# Create your models here.
class FurnitureUpdate(models.Model):
mapping_id = models.OneToOneField(
HomeFurnitureMapping,
on_delete=models.CASCADE,
null=False,
unique=True,
verbose_name='Mapping ID'
)
update_status = models.IntegerField(null=False, default=1)
update_date = models.DateField(auto_now_add=True, null=False, verbose_name='Update date')
update_time = models.TimeField(auto_now_add=True, null=False, verbose_name='Update time')
def __str__(self):
return self.mapping_id
My questions are:
How to create/update a record in "FurnitureUpdate" table after I save/update "Furniture" form from admin panel?
How to create/update a record in "FurnitureUpdate" table after I save/update "HomeFurnitureMapping" form from admin panel
And can this functionality to update "FurnitureUpdate" table be retained if I use django-excel like bulk data upload packages?
Update:
I tried django signals, by adding method in "HomeFurnitureMapping" class:
# method for updating
def update_on_home_furniture_mapping(sender, instance, **kwargs):
print ('ENTERED')
print(instance.id)
m_id = instance.id
from updates.models import FurnitureUpdate
FurnitureUpdate.objects.create(mapping_id = m_id)
print ('Furniture Update created!')
# register the signal
post_save.connect(update_on_tag_product_mapping, sender= HomeFurnitureMapping)
But I get the following error on form submission in admin panel.
Error: "FurnitureUpdate.mapping_id" must be a "HomeFurnitureMapping" instance.
your last error fix by remove id:
replace
FurnitureUpdate.objects.create(mapping_id = m_id)
to
FurnitureUpdate.objects.create(mapping_id = instance)
by default in the db django added _id to the name of columns, and in your case columns inside database looks like COLUMN_NAME_id_id double id at the end, so if you want send foreign key as integer you need use double _id_id, but for single _id you need send an instance.