How to print foreign key of this model in django? - django

Model File
class Report_item(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
title = models.CharField(max_length=255, help_text='*Title for the post e.g. item identity')
item_type = models.CharField(default="", max_length=100,
help_text='*Enter the item name you found e.g. Marksheet,key,wallet')
location = models.CharField(max_length=60, help_text='*Enter the address/street where you find this item')
city = models.CharField(max_length=60, help_text='*Enter the city name')
date = models.DateTimeField(default=timezone.now)
Description = models.TextField(help_text='*Enter full description about item')
publish = models.BooleanField(default=False)
image = models.FileField(default="add Item image",
help_text='*Please uplocad a item image to identify by the owner')
def __str__(self):
return self.title + " " + str(self.publish)
def get_absolute_url(self):
return reverse('feed:detail', kwargs={'pk': self.pk})
class Meta:
ordering = ["-date"]
I print my title in the shell.
>>> qs=Report_item.objects.filter(id=3)
>>> print(qs[0].title)
bunch of key with home keyring
But I got an error when I tried to print(qs[0].owner)
My foreign key is the Django auth user.
>>> print(qs[0].owner)
Traceback (most recent call last):
File "/home/imsaiful/Desktop/local_repo/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 178, in __get__
rel_obj = getattr(instance, self.cache_name)
AttributeError: 'Report_item' object has no attribute '_owner_cache'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/imsaiful/Desktop/local_repo/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 184, in __get__
rel_obj = self.get_object(instance)
File "/home/imsaiful/Desktop/local_repo/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 159, in get_object
return qs.get(self.field.get_reverse_related_filter(instance))
File "/home/imsaiful/Desktop/local_repo/myvenv/lib/python3.6/site-packages/django/db/models/query.py", line 379, in get
self.model._meta.object_name
django.contrib.auth.models.DoesNotExist: User matching query does not exist.
admin section image:
https://drive.google.com/file/d/1lQ-TcdaTCxj-cmnzfhlGZXql-KbWpIjW/view?usp=sharing

Related

Django Unitest, can't recognize the error

I am wondering if could anyone help out here, I am trying to send a post request to the URL, but I am not sure about the best way of doing it?
The idea here is to test the creation of the card object, but I am getting an error which I am not managing to figure out, if anyone could help me out here it would be fantastic.
here the code and the error below it
def test_create_card(self):
payload = {
'title': "Sample card title",
'description': 'Get a free coffee for every 10 coffee you buy',
'points_needed': 10,
}
res = self.client.post(CARDS_URL, self.company, **payload)
print(res)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
card = Card.objects.get(id=res.data['id'])
for k, v in payload.items():
self.assertEqual(getattr(card, k), v)
self.assertEqual(card.company, self.company)
ERROR
ERROR: test_create_card (card.tests.test_card_api.PrivateCardAPITests)
Test creating a card
Traceback (most recent call last):
File "/app/card/tests/test_card_api.py", line 141, in test_create_card
res = self.client.post(CARDS_URL, self.company, **payload)
File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 295, in post
response = super().post(
File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 208, in post
data, content_type = self._encode_data(data, format, content_type)
File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 179, in _encode_data
ret = renderer.render(data)
File "/py/lib/python3.9/site-packages/rest_framework/renderers.py", line 914, in render
return encode_multipart(self.BOUNDARY, data)
File "/py/lib/python3.9/site-packages/django/test/client.py", line 245, in encode_multipart
for (key, value) in data.items():
AttributeError: 'Company' object has no attribute 'items
'
and here is the model:
'
class Card(models.Model):
company = models.ForeignKey(Company, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, blank=True)
description = models.TextField(blank=True)
points_needed = models.IntegerField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True, blank=True)
active = models.BooleanField(default=True)
def __str__(self):
return self.title
'

Problem in Deleting Model Entries having ForeignKey Constraint

class Client(models.Model):
client_id = models.CharField(primary_key=True, max_length=255)
name = models.CharField(max_length=255, blank=False)
class Cont(models.Model):
contid = models.CharField(max_length=255, primary_key=True)
Client = models.ForeignKey(Client, on_delete=models.PROTECT)
class ContractDailyIndent(models.Model):
id = models.CharField(max_length=255, primary_key=True)
cont = models.ForeignKey(Cont, on_delete=models.PROTECT)
class VDLContract(models.Model):
id = models.CharField(max_length=255, primary_key=True)
contractindent = models.ForeignKey(ContractDailyIndent,
on_delete=models.PROTECT)
Getting error in this line
VDLContract.objects.filter(contractindent__cont__Client__in=clients).delete()
It's giving error:
Traceback (most recent call last):
File "/home/puranjay/Documents/FeasOpt/new/fo_ftl_puranjay/mysite/empanelment/views.py", line 10432, in update_client_type
delete_client_type(user, client_type_id)
File "/home/puranjay/Documents/FeasOpt/new/fo_ftl_puranjay/mysite/empanelment/views.py", line 105, in delete_client_type
delete_indent_models(user, clients)
File "/home/puranjay/Documents/FeasOpt/new/fo_ftl_puranjay/mysite/empanelment/utility.py", line 962, in delete_indent_models
raise e
File "/home/puranjay/Documents/FeasOpt/new/fo_ftl_puranjay/mysite/empanelment/utility.py", line 941, in delete_indent_models
VDLContract.objects.filter(contractindent__cont__Client__in=clients).delete()
File "/home/puranjay/Documents/FeasOpt/env/venv/lib/python3.6/site-packages/django/db/models/query.py", line 661, in delete
collector.collect(del_query)
File "/home/puranjay/Documents/FeasOpt/env/venv/lib/python3.6/site-packages/django/db/models/deletion.py", line 222, in collect
field.remote_field.on_delete(self, field, sub_objs, self.using)
TypeError: 'NoneType' object is not callable
I tried implementing your problem on my localmachine.
Django causes this error because of foreign key constraint.This happens when your foreign key is dependent on other models, in your case VDLContract may have dependency on other model which need to be deleted first.

django modelsTypeError: decoding str is not supported

I'm a beginner trying to view a basic queryset with two records. I'm not able to process the request. Looking for some help.
class TestVenue(models.Model):
venue_name = models.CharField(max_length=40)
venue_city = models.CharField(max_length=20, null=True, blank=True)
venue_province = models.CharField(max_length=20, null=True, blank=True)
venue_shortcode = models.CharField(max_length=20, null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
update = models.DateTimeField(auto_now=True)
my_date_field = models.DateField(auto_now=False, auto_now_add=False)
def __str__(self):
return self.venue_name
my views.py is pretty simple
def venues_listview(request):
template_name = 'venues_list.html'
queryset = TestVenue.objects.all()
context = {
"object_list": queryset
}
return render(request, template_name, context)
from the shell i want to see my queryset but i get the following error:
>>> from venues.models import TestVenue
>>> TestVenue.object.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: type object 'TestVenue' has no attribute 'object'
>>> TestVenue.objects.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\users\frank\desktop\test_env\lib\site-packages\django\db\models\query.py", line 229, in __repr__
return '<%s %r>' % (self.__class__.__name__, data)
File "C:\users\frank\desktop\test_env\lib\site-packages\django\db\models\base.py", line 589, in __repr__
u = six.text_type(self)
File "C:\users\frank\desktop\test_env\src\venues\models.py", line 14, in __str__
# return self.venue_name
TypeError: decoding str is not supported
Your error is in this line,
TestVenue.object.all()
It should be,
TestVenue.objects.all()
objects is the attribute which calls the default manager, not object.
I rebooted my computer and it's now working. I had tried starting and stopping the server but that had not fixed the issue. Thanks for the help.

Django giving Cannot force an update in save() with no primary key

I'm getting ValueError: Cannot force an update in save() with no primary key. while code hitting to exception and run get_or_create code. Model has it's table in database with auto incremental id field. And also this is not an update process. I can't get why Django behaving like this.
ERROR:
Traceback (most recent call last):
File "x.py", line 1980, in <module>
getattr(a, islem)()
File "x.py", line 718, in method
Slug='undefined', Status=False)
File "~/env/local/lib/python2.7/site-packages/django/db/models/manager.py", line 135, in get_or_create
return self.get_query_set().get_or_create(**kwargs)
File "~/env/local/lib/python2.7/site-packages/django/db/models/query.py", line 385, in get_or_create
obj.save(force_insert=True, using=self.db)
File ~/core/modules/xx/models.py", line 78, in save
super(Categories, self).save(args, kwargs)
File "~/env/local/lib/python2.7/site-packages/django/db/models/base.py", line 460, in save
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "x/env/local/lib/python2.7/site-packages/django/db/models/base.py", line 541, in save_base
raise ValueError("Cannot force an update in save() with no primary key.")
ValueError: Cannot force an update in save() with no primary key.
CODE:
try:
category = Categories.objects.get(Code=category_code)
except ObjectDoesNotExist:
category, created = Categories.objects.get_or_create(
Name='Undefined', Code='undefined',ParentCategoryID=None, OrderID=0,
Slug='undefined', Status=False)
MODEL:
class Categories(models.Model):
Name = models.CharField(max_length=155)
Code = models.CharField(max_length=255)
ParentCategoryID = models.ForeignKey('self', related_name='SubCategory', null=True, blank=True)
Level = models.IntegerField(default=0, max_length=10, editable=False)
OrderID = models.IntegerField(blank=True, max_length=10)
Slug = models.SlugField(max_length=250)
CreateDate = models.DateTimeField(auto_now_add=True)
LastUpdateDate = models.DateTimeField(auto_now=True)
Status = models.BooleanField(default=True)
def save(self, *args, **kwargs):
if self.ParentCategoryID is not None:
parent = Categories.objects.get(id=self.ParentCategoryID.id)
self.Level = parent.Level + 1
if self.OrderID <= 0:
try:
top = Categories.objects.order_by('-OrderID')[0]
self.OrderID = top.OrderID + 1
except:
self.OrderID = 1
super(Categories, self).save(args, kwargs)
You need to use the * and ** when you call super as well:
super(Categories, self).save(*args, **kwargs)
Note there are some other strange things in this code too. Primarily this line:
parent = Categories.objects.get(id=self.ParentCategoryID.id)
is doing two identical queries for no reason; self.ParentCategoryID is already the parent object. You should just do:
parent = self.ParentCategoryID
which should lead you to the conclusion that the ParentCategoryID is badly named; it contains the actual object, not the ID.
Note also that there are quite a few style violation; Python prefers lower_case_with_underscore for attribute names, and Django prefers singular model names. The related name for the foreign key should be plural, though, as it will refer to multiple category objects. So:
class Category(models.Model):
name = models.CharField(max_length=155)
code = models.CharField(max_length=255)
parent_category = models.ForeignKey('self', related_name='sub_categories', null=True, blank=True)
...

south error with django

my old models.py :
from django.db import models
from taggit.managers import TaggableManager
from django.utils.encoding import smart_unicode
import markdown
class PublishedManager(models.Manager):
def get_query_set(self):
return super(PublishedManager, self).get_query_set().filter\
(is_published=True)
class Category(models.Model):
name = models.CharField(max_length=55)
def __unicode__(self):
return u"%s" %(self.name)
class BookMarks(models.Model):
name = models.CharField(max_length=255)
url = models.URLField()
date_time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return u"%s %s %s" %(self.name, self.url, self.date_time)
class Post(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
excerpt = models.TextField(blank=True, help_text="A small teaser of\
your content")
content = models.TextField(blank=True, null=True)
contentmarkdown = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
is_published = models.BooleanField(default=True)
objects = models.Manager()
published_objects = PublishedManager()
tags = TaggableManager()
category = models.ForeignKey(Category)
def save(self):
self.content = markdown.markdown(self.contentmarkdown)
super(Post, self).save() # Call the "real" save() method.
class Meta:
ordering = ("date_created",)
def __unicode__(self):
return smart_unicode("%s %s %s %s %s" %(self.title, self.content, self.is_published, self.category, self.tags))
def get_absolute_url(self):
return "/posts/%s/" % self.id
class Book(models.Model):
name = models.CharField(max_length=55)
author = models.CharField(max_length=55)
image = models.ImageField(upload_to="static/img/books/")
body = models.TextField(blank=True, null=True)
bodymarkdown = models.TextField()
def __unicode__(self):
return u"%s %s" %(self.name, self.author)
def get_absolute_url(self):
return "/books/%s/" % self
.id
and after add "category = models.ForeignKey(Category)" this field to Book and BookMarks table, my new models.py like this:
from django.db import models
from taggit.managers import TaggableManager
from django.utils.encoding import smart_unicode
import markdown
class PublishedManager(models.Manager):
def get_query_set(self):
return super(PublishedManager, self).get_query_set().filter\
(is_published=True)
class Category(models.Model):
name = models.CharField(max_length=55)
def __unicode__(self):
return u"%s" %(self.name)
class BookMarks(models.Model):
name = models.CharField(max_length=255)
url = models.URLField()
date_time = models.DateTimeField(auto_now_add=True)
category = models.ForeignKey(Category)
def __unicode__(self):
return u"%s %s %s" %(self.name, self.url, self.date_time)
class Post(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
excerpt = models.TextField(blank=True, help_text="A small teaser of\
your content")
content = models.TextField(blank=True, null=True)
contentmarkdown = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
is_published = models.BooleanField(default=True)
objects = models.Manager()
published_objects = PublishedManager()
tags = TaggableManager()
category = models.ForeignKey(Category)
def save(self):
self.content = markdown.markdown(self.contentmarkdown)
super(Post, self).save() # Call the "real" save() method.
class Meta:
ordering = ("date_created",)
def __unicode__(self):
return smart_unicode("%s %s %s %s %s" %(self.title, self.content, self.is_published, self.category, self.tags))
def get_absolute_url(self):
return "/posts/%s/" % self.id
class Book(models.Model):
name = models.CharField(max_length=55)
author = models.CharField(max_length=55)
image = models.ImageField(upload_to="static/img/books/")
body = models.TextField(blank=True, null=True)
bodymarkdown = models.TextField()
category = models.ForeignKey(Category)
def __unicode__(self):
return u"%s %s" %(self.name, self.author)
def get_absolute_url(self):
return "/books/%s/" % self.id
class Errors(models.Model):
name = models.CharField(max_length=255)
created = models.DateTimeField(auto_now_add=True)
body = models.TextField(blank=True, null=True)
bodymarkdown = models.TextField()
def __unicode__(self):
return self.name
def get_absolute_url(self):
return "/errors/%s/" % self.id
I used south. Everything was going OK but after this line:
? 1. Quit now, and add a default to the field in models.py
? 2. Specify a one-off value to use for existing columns now
? 3. Disable the backwards migration by raising an exception.
? Please select a choice: 2
? Please enter Python code for your one-off default value.
? The datetime module is available, so you can do e.g. datetime.date.today()
>>> datetime.datetime.now()
I get an error like this:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/management/commands/migrate.py", line 108, in handle
ignore_ghosts = ignore_ghosts,
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/__init__.py", line 213, in migrate_app
success = migrator.migrate_many(target, workplan, database)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 235, in migrate_many
result = migrator.__class__.migrate_many(migrator, target, migrations, database)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 310, in migrate_many
result = self.migrate(migration, database)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 133, in migrate
result = self.run(migration)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 106, in run
dry_run.run_migration(migration)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 191, in run_migration
self._run_migration(migration)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 178, in _run_migration
raise exceptions.FailedDryRun(migration, sys.exc_info())
south.exceptions.FailedDryRun: ! Error found during dry run of '0012_auto__del_field_book_category__add_field_book_category1__del_field_boo'! Aborting.
Traceback (most recent call last):
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 175, in _run_migration
migration_function()
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/migration/migrators.py", line 57, in <lambda>
return (lambda: direction(orm))
File "/home/ada/mainproject/blog/migrations/0012_auto__del_field_book_category__add_field_book_category1__del_field_boo.py", line 17, in forwards
keep_default=False)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/db/generic.py", line 44, in _cache_clear
return func(self, table, *args, **opts)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/db/generic.py", line 402, in add_column
sql = self.column_sql(table_name, name, field)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/south/db/generic.py", line 688, in column_sql
default = field.get_db_prep_save(default, connection=self._get_connection())
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 991, in get_db_prep_save
connection=connection)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 292, in get_db_prep_save
prepared=False)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 284, in get_db_prep_value
value = self.get_prep_value(value)
File "/home/ada/virtualenv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 537, in get_prep_value
return int(value)
TypeError: int() argument must be a string or a number, not 'datetime.datetime'
Please can you tell me Why I get this error? What must I do?
Because your new category field is mandatory (you can't create a book or bookmark without giving it a category), south asked you what to do with the existing books and bookmarks in your database - your latest changes would have made all your current books / bookmarks invalid (since they don't have a category).
Your new category field is represented in your book/bookmark tables using a primary key of the category table. This primary key will likely be an integer (or possibly a string).
South asked you to supply a default primary key. Instead of supplying the primary key of an category object in your database (which would be an integer or a string). You've supplied a datatime object.
It's crapping out when it actually runs the migration because the field doesn't hold datetime objects. It holds integers (or strings). you need to create the migration again and add a valid primary key.