Django ImageField is unable to hande tif images - django

I am creating a django Project where I had Stored a Picture(Image) in database using ImageField as...
original_pic = models.ImageField()
Also, I want to Store an Image which will Contain the Same Picture(Image) as original_pic with Watermark in another ImageField as..
display_pic = models.ImageField(null=True, blank=True)
In short, I just want to Apply Algorithm on original_pic and save the result in watermark_pic using django models
Algorithm(Logic) for Applying Watermark to image is as follows...
def watermark_image_with_text(filename):
text = 'PicMesh'
color = 'blue'
fontfamily = 'arial.ttf'
image = Image.open(filename).convert('RGBA')
imageWatermark = Image.new('RGBA', image.size, (255, 255, 255, 0))
draw = ImageDraw.Draw(imageWatermark)
width, height = image.size
font = ImageFont.truetype(fontfamily, int(height / 20))
textWidth, textHeight = draw.textsize(text, font)
x = width / 5
y = height / 6
draw.text((x, y), text, color, font)
my_image = Image.alpha_composite(image, imageWatermark)
my_image.convert('RGB').save('D:\Github\PicMesh\media\water_'+
filename.name + '.png')
return 'D:\Github\PicMesh\media\water_'+filename.name + '.png'
My Models.py contains following Photo model that overwrites save method to store value in display_pic.
class Photo(models.Model):
format_of_tags = (
('PNG', 'PNG'),
('JPG', 'JPG'),
('JPEG', 'JPEG'),
('Exif', 'Exif'),
('TIF', 'TIF'),
('GIF', 'GIF'),
('WEBP', 'WEBP'),
('SVG', 'SVG'),
)
title = models.CharField(max_length=150)
format = models.CharField(max_length=20, choices=format_of_tags, blank=False)
tags = models.CharField(max_length=250)
original_pic = models.ImageField()
display_pic = models.ImageField(null=True, blank=True)
description = models.CharField(max_length=1000)
photographer = models.ForeignKey('Photographer', on_delete=models.CASCADE)
category = models.ForeignKey('Categories', on_delete=models.CASCADE, default=0)
# Overwrites save method and set value of display_pic by default
def save(self, *args, **kwargs):
if not self.pk:
rotate_img_name = watermark_image_with_text(self.original_pic)
self.display_pic = rotate_img_name
super().save(*args, **kwargs)
the Problem with the code is that it handles all formats of image perfectly for e.g- png,jpg,jpeg,etc but it is unable to handle image of format tif.
I got OSError when save() method is invoked
error trackback is as follows...
`Internal Server Error: /admin/home/photo/add/
Traceback (most recent call last):
File "C:\Users\abx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1b1-py3.6.egg\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\abx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1b1-py3.6.egg\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\abx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1b1-py3.6.egg\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\abx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1b1-py3.6.egg\django\contrib\admin\options.py", line 607, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\abx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1b1-py3.6.egg\django\utils\decorators.py", line 140, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\abx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1b1-py3.6.egg\django\views\decorators\cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "C:\Users\abx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1b1-py3.6.egg\django\contrib\admin\sites.py", line 223, in inner
return view(request, *args, **kwargs)
File "C:\Users\abx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1b1-py3.6.egg\django\contrib\admin\options.py", line 1647, in add_view
return self.changeform_view(request, None, form_url, extra_context)
File "C:\Users\abx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1b1-py3.6.egg\django\utils\decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "C:\Users\abx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1b1-py3.6.egg\django\utils\decorators.py", line 140, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "C:\Users\abx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1b1-py3.6.egg\django\contrib\admin\options.py", line 1536, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\abx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1b1-py3.6.egg\django\contrib\admin\options.py", line 1575, in _changeform_view
self.save_model(request, new_object, form, not add)
File "C:\Users\abx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django-2.1b1-py3.6.egg\django\contrib\admin\options.py", line 1094, in save_model
obj.save()
File "D:\Github\PicMesh\home\models.py", line 53, in save
rotate_img_name = watermark_image_with_text(self.original_pic)
File "D:\Github\PicMesh\home\models.py", line 16, in watermark_image_with_text
image = Image.open(filename).convert('RGBA')
File "C:\Users\abx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\Image.py", line 892, in convert
self.load()
File "C:\Users\abx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\TiffImagePlugin.py", line 1061, in load
return self._load_libtiff()
File "C:\Users\abx\AppData\Local\Programs\Python\Python36-32\lib\site-packages\PIL\TiffImagePlugin.py", line 1153, in _load_libtiff
raise IOError(err)
OSError: -2
[29/Aug/2018 10:15:37] "POST /admin/home/photo/add/ HTTP/1.1" 500 132413`

Related

'Context' object has no attribute 'render_context'

I am running Django==3.2.12 and trying to generate a rendered tewmplate string. The following is the nuts and bolts of it....
I am recieving the error "'Context' object has no attribute 'render_context'" and can not make any sence of it.
It used to work fine, I am using django-mjml for this.
Code...
import uuid
from django.db import models
from django.template import Template, Context
from django.urls import reverse
class EmailTemplate(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
uuid = models.UUIDField(default = uuid.uuid4)
mjml_template = models.TextField(blank=True)
html_template = models.TextField(blank=True)
class Meta:
ordering = ['name', ]
verbose_name = 'Template'
verbose_name_plural = 'Templates'
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('pages:emailing', kwargs={'slug': self.slug, 'uuid': self.uuid})
def save(self, *args, **kwargs):
mjml_open = '{% load mjml %}{% mjml %}'
mjml_close = '{% endmjml %}'
verbatum_open = '{% verbatim %}{{'
verbatum_close = '}}{% endverbatim %}'
verbatum = self.mjml_template.replace('{{', verbatum_open)
verbatum = verbatum.replace('}}', verbatum_close)
verbatum = mjml_open + verbatum + mjml_close
template = Template(verbatum)
context = Context({})
passed = False
try:
self.html_template = template.render(context)
passed = True
except Exception as err:
self.html_template = str(err)
if passed:
image_categories = ImageCategory.objects.filter(templates=self)
for image_category in image_categories:
for image in image_category.get_images():
tag = '[~ ' + image.slug + ' ~]'
swap = self.html_template
swap = swap.replace(tag, image.image.url)
self.html_template = swap
resource_categories = ResourceCategory.objects.filter(templates=self)
for resource_category in resource_categories:
for resource in resource_category.get_resources():
tag = '[~ ' + resource.slug + ' ~]'
swap = self.html_template
swap = swap.replace(tag, resource.resource)
self.html_template = swap
super(EmailTemplate, self).save(*args, **kwargs)
Traceback....
Internal Server Error: /admin/emailing/emailtemplate/1/change/
Traceback (most recent call last):
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/contrib/admin/options.py", line 616, in wrapper
return self.admin_site.admin_view(view)(*args, **kwargs)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 232, in inner
return view(request, *args, **kwargs)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1660, in change_view
return self.changeform_view(request, object_id, form_url, extra_context)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper
return bound_method(*args, **kwargs)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1540, in changeform_view
return self._changeform_view(request, object_id, form_url, extra_context)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1586, in _changeform_view
self.save_model(request, new_object, form, not add)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/contrib/admin/options.py", line 1099, in save_model
obj.save()
File "/Applications/MAMP/htdocs/mjml/emailing/models.py", line 42, in save
self.html_template = template.render(context)
File "/Users/sbrown/.local/share/virtualenvs/mjml-NNm5TF3H/lib/python3.9/site-packages/django/template/base.py", line 166, in render
with context.render_context.push_state(self):
AttributeError: 'Context' object has no attribute 'render_context'

Django invalid literal for int() with save_m2m

I try to integrate vue tags input http://www.vue-tags-input.com/#/ with my project.
Autocomplete works fine, form also. When I save the form, everything except the category(tags) is saved.
I know that with many to many relationship I have to use save_m2m in view, but when I do this, error appear:
invalid literal for int() with base 10: 'e'
My view:
#login_required
def save_embed(request):
interests = RecipeCategory.objects.all()
if request.method == "POST":
form = AddEmbed(request.POST)
if form.is_valid():
new_embed = form.save(commit=False)
new_embed.added_by = request.user
new_embed.save()
form.save_m2m()
else:
form = AddEmbed()
return render(request, 'embed/embedadd.html', {'form': form,
'interests': interests})
Model:
class Embed(models.Model, Activity):
url = models.URLField(max_length=255, verbose_name='Adres przepisu')
title = models.CharField(max_length=255, verbose_name='Tytuł')
description = models.TextField(verbose_name='Opis', blank=True, null=True)
type = models.CharField(blank=True, max_length=200)
thumbnail_url = models.URLField(max_length=255, blank=True, null=True)
image = models.ImageField(upload_to='recipes', blank=True)
html = models.TextField()
votes = GenericRelation(LikeDislike, related_query_name='embedlikes')
added_by = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
category = TreeManyToManyField(RecipeCategory, blank=True, null=True, related_name='embeds', verbose_name='Kategoria')
slug = AutoSlugField(populate_from='title', unique=True)
Edit - Form
class AddEmbed(ModelForm):
url = forms.URLField(label='Adres przepisu', widget=forms.URLInput(attrs={'v-model': 'embed.url', '#paste':'paste', '#input':'input'}))
title = forms.CharField(widget=forms.HiddenInput(attrs={':value':'embedsinfo.title'}))
description = forms.CharField(widget=forms.HiddenInput(attrs={':value':'embedsinfo.description'}))
thumbnail_url = forms.CharField(widget=forms.HiddenInput(attrs={':value':'embedsinfo.thumbnail_url'}))
html = forms.CharField(widget=forms.HiddenInput(attrs={':value':'embedsinfo.html'}))
category = forms.CharField(widget=forms.HiddenInput(attrs={':value': 'tags'}))
class Meta:
model = Embed
fields = ['url','title', 'description', 'thumbnail_url', 'html', 'category']
Traceback:
Traceback (most recent call last):
File "/data/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/data/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/data/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/data/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/app/recipes/views.py", line 39, in save_embed
form.save_m2m()
File "/data/lib/python3.6/site-packages/django/forms/models.py", line 441, in _save_m2m
f.save_form_data(self.instance, cleaned_data[f.name])
File "/data/lib/python3.6/site-packages/django/db/models/fields/related.py", line 1621, in save_form_data
getattr(instance, self.attname).set(data)
File "/data/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 997, in set
self.add(*new_objs, through_defaults=through_defaults)
File "/data/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 938, in add
through_defaults=through_defaults,
File "/data/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1065, in _add_items
'%s__in' % target_field_name: new_ids,
File "/data/lib/python3.6/site-packages/django/db/models/query.py", line 892, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/data/lib/python3.6/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/data/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1290, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/data/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1318, in _add_q
split_subq=split_subq, simple_col=simple_col,
File "/data/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1251, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/data/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1116, in build_lookup
lookup = lookup_class(lhs, rhs)
File "/data/lib/python3.6/site-packages/django/db/models/lookups.py", line 20, in __init__
self.rhs = self.get_prep_lookup()
File "/data/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 59, in get_prep_lookup
self.rhs = [target_field.get_prep_value(v) for v in self.rhs]
File "/data/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 59, in <listcomp>
self.rhs = [target_field.get_prep_value(v) for v in self.rhs]
File "/data/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 972, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'e'
[21/Jun/2020 13:20:22] "POST /recipes/recipe/embed/add/ HTTP/1.1" 500 151931

ValueError: invalid literal for int() with base 10: 'A' while updating M2M

I am trying to update a ManyToMany field in django while doing this I am getting the following error :
Traceback (most recent call last):
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/rest_framework/decorators.py", line 55, in handler
return func(*args, **kwargs)
File "/home/bhupesh/Desktop/tutorialdb-test/tutorialdb/api/views.py", line 94, in tutorials
updateDB.tags.add(t)
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 938, in add
through_defaults=through_defaults,
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1065, in _add_items
'%s__in' % target_field_name: new_ids,
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/query.py", line 892, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1290, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1318, in _add_q
split_subq=split_subq, simple_col=simple_col,
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1251, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1116, in build_lookup
lookup = lookup_class(lhs, rhs)
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/lookups.py", line 20, in __init__
self.rhs = self.get_prep_lookup()
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 59, in get_prep_lookup
self.rhs = [target_field.get_prep_value(v) for v in self.rhs]
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 59, in <listcomp>
self.rhs = [target_field.get_prep_value(v) for v in self.rhs]
File "/home/bhupesh/Desktop/tutorialdb-test/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 966, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'A'
Here is my models.py
class tag(models.Model):
name = models.CharField(max_length=100)
created_date = models.DateTimeField(default=timezone.now)
description = models.TextField(blank=True)
def __str__(self):
return self.name
class tutorial(models.Model):
title = models.CharField(max_length=200)
link = models.URLField()
tags = models.ManyToManyField(tag)
category = models.CharField(max_length=200, choices = TUTORIAL_CATEGORIES)
created_date = models.DateTimeField(default=timezone.now)
#cached_property
def __str__(self):
return self.title
I am actually generating title & tags from a custom script that's why the serialzer is incomplete.
I am trying to send the following JSON data :
{
"link":"https://youtu.be/DHvMXvCVQVA",
"category":"video"
}
views.py
#api_view(['GET', 'POST'])
def tutorials(request):
"""
get: Returns all tutorials
post: POST a tutorial
"""
if request.method == 'GET':
tutorials = tutorial.objects.all()
serializer = tutorialSerializer(tutorials, many=True)
return JSONResponse(serializer.data)
elif request.method == 'POST':
postserializer = tutorialPOST(data = request.data)
if postserializer.is_valid():
title, tags = generateTags(request.data['link'])
print(title)
print(tags)
updateDB = tutorial.objects.create(
title = title,
link = request.data['link'],
category = request.data['category'],
created_date = timezone.now
)
for t in tags:
updateDB.tags.set(t)
return JSONResponse({"message " : "submitted" }, status=status.HTTP_202_ACCEPTED)
return JSONResponse({"message":"not_valid"})
Here is serializer.py
class tutorialPOST(serializers.Serializer):
class Meta:
model = tutorial
fields = ('link', 'category')
From what I know it's happening because of the following line in views.py
updateDB.tags.add(t)
You should call timezone.now method, instead of passing the method itself:
updateDB = tutorial.objects.create(
title = title,
link = request.data['link'],
category = request.data['category'],
created_date = timezone.now()
)
You have default value of created_date set correctly:
created_date = models.DateTimeField(default=timezone.now)
so it will be autofilled automatically for you:
updateDB = tutorial.objects.create(
title = title,
link = request.data['link'],
category = request.data['category']
)
Your date fields are giving errors. Just remove all their attributes and add "auto_now=True,auto_now_add=True" to date fields.

Serializer results in KeyError after correct data input and save

I'm creating an API endpoint that works and saves data through its API. It works, but my concern is that it throws a KeyError as shown below. I'm not sure if this is an issue with my code. Your help is very much appreciated.
Data:
data = {'title': u'abc', 'career_level': 1}
Serializer:
class JobPostSerializer(serializers.ModelSerializer):
career_level = PrimaryKeyRelatedField(allow_null=True, queryset=CareerLevel.objects.all(), required=False)
title = CharField(allow_blank=True, allow_null=True, max_length=240, required=False)
Model:
class JobPost(models.Model):
career_level = models.ForeignKey(CareerLevel, related_name='jobpost_career', blank=True, null=True)
title = models.CharField(max_length=240, blank=True, null=True)
created_at = models.DateTimeField(db_index=True, auto_now_add=True)
def __str__(self):
return self.title
def __unicode__(self):
return self.title
class Meta:
ordering = ['-created_at']
Error Message:
Internal Server Error: /api/v1/posts/
Traceback (most recent call last):
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/viewsets.py", line 87, in view
return self.dispatch(request, *args, **kwargs)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch
response = self.handle_exception(exc)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/views.py", line 463, in dispatch
response = handler(request, *args, **kwargs)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/mixins.py", line 22, in create
headers = self.get_success_headers(serializer.data)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 503, in data
ret = super(Serializer, self).data
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 241, in data
self._data = self.to_representation(self.validated_data)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/serializers.py", line 463, in to_representation
attribute = field.get_attribute(instance)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/relations.py", line 157, in get_attribute
return get_attribute(instance, self.source_attrs)
File "/home/ubuntu/panbecopy/src/penv/local/lib/python2.7/site-packages/rest_framework/fields.py", line 78, in get_attribute
instance = instance[attr]
KeyError: u'career_level'
Your serializer definition makes no sense.
JobPostSerializer(data={'title': u'abc', 'career_level': 1}):
It should instead be:
class JobPostSerializer(serializers.ModelSerializer):
That line of yours is more similar to when you want to instantiate the serializer. Something like when you want to check if the input was valid, for example.
job_serializer = JobPostSerializer(data={'title': u'abc', 'career_level': 1})
job_serializer.is_valid()

How to update some data when post object in Django Rest?

I have this Serializer:
class LikeSerializer(serializers.ModelSerializer):
user = serializers.PrimaryKeyRelatedField(queryset=ExtUser.objects.all(), required=False, allow_null=True, default=None)
class Meta:
model = Like
field = ('user', 'post')
def create(self, validated_data):
post = Post(id=validated_data['post'], author=validated_data['user'])
#post=Post.objects.get(pk=validated_data['post'])
post.rating += 1
print(post)
post.save()
return Like.objects.create(**validated_data)
And I get error, when i trying to save Like object TypeError: int() argument must be a string or a number, not 'Post'
Trying to add int(), but it not helps, I think I not correct update Post object
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 466, in dispatch
response = self.handle_exception(exc)
File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 463, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Python/2.7/site-packages/rest_framework/decorators.py", line 53, in handler
return func(*args, **kwargs)
File "/Users/olegklimakov/Documents/6rp/likes/views.py", line 19, in send_like
serializer.save(user=request.user, isLiked=True)
File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 191, in save
self.instance = self.create(validated_data)
File "/Users/olegklimakov/Documents/6rp/likes/serializers.py", line 39, in create
post.save()
File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 700, in save
force_update=force_update, update_fields=update_fields)
File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 728, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 793, in _save_table
forced_update)
File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 823, in _do_update
filtered = base_qs.filter(pk=pk_val)
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 790, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 808, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 1243, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 1269, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 1203, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 1099, in build_lookup
return final_lookup(lhs, rhs)
File "/Library/Python/2.7/site-packages/django/db/models/lookups.py", line 19, in __init__
self.rhs = self.get_prep_lookup()
File "/Library/Python/2.7/site-packages/django/db/models/lookups.py", line 57, in get_prep_lookup
return self.lhs.output_field.get_prep_lookup(self.lookup_name, self.rhs)
File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 744, in get_prep_lookup
return self.get_prep_value(value)
File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 976, in get_prep_value
return int(value)
TypeError: int() argument must be a string or a number, not 'Post'
Post model:
class Post(models.Model):
id = models.AutoField(primary_key=True)
date_create = models.DateField(auto_now_add=True)
date_change = models.DateField(auto_now=True)
title = models.CharField(max_length=250) # Max Length of title = 250
description = models.CharField(max_length=1000) # Max Length = 1000 chars
rating = models.IntegerField(default=1)
author = models.ForeignKey('extuser.ExtUser', blank=True, null=True)
def __unicode__(self):
return u"%s" % self.id
It seems like inside the statement
"Post(id=validated_data['post'], author=validated_data['user'])",
validated_data['post'] gives you a Post object, not a int object,
but the 'id' inside the Post model expect a int object.
That probably is the reason you get the error.
#transactional
def create(self, validated_data):
post = Post(id=validated_data['post'], author=validated_data['user'])
post.rating += 1
post.save()
return super(self, LikeSerializer).create(validated_data)
Its good to let ModelSerializer create do its job, also note you definitely want to use transaction to keep data consistent
Also, code below creates new Post entity:
post = Post(...)
post.save()
You definitely need to get existent Post entity instead
Post.objects.filter(...).first()