I got decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>] - django

views.py
#api_view(["POST", "GET"])
#permission_classes([IsAuthenticated])
def add_order(request, pk):
print(request.user)
customer = md.Customer.objects.get(pk=pk)
if request.method == "POST":
description = request.data['description']
price = request.data['price']
order = md.Order.objects.create(customer=customer,
date_created=zt.now(),
description=description,
price=float(price),
customer_total_when_created=customer.total_owe[0]
)
try:
is_paid = request.data['is_paid']
if is_paid == "on":
who_paid = request.data['who_paid']
payment_method = request.data['payment_method']
who_took_money = request.user
if who_paid == customer.name:
order.who_paid = customer
elif who_paid == customer.parent:
order.who_paid = customer.parent
order.payment_method = payment_method
order.who_took_money = who_took_money
order.date_paid = zt.now()
customer.total = customer.total_owe
customer.save()
order.save()
except:
print("no payment succeed")
order_api = OrderSerializer(order)
return Response(order_api.data)
customer_api = CustomerSerializer(customer)
parent_api = CustomerSerializer(customer.parent)
context = {
"customer": customer_api.data,
"parent":parent_api.data,
"sample": [
{"description": "secreal", "price": "12.21", "is_paid": "on", "who_paid": "azra", "payment_method": "CARD"}
]
}
return Response(context)
models.py
class Order(models.Model):
payment_method_list = [("CASH","CASH"),("CARD","CARD")]
customer = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True,blank=True,)
who_paid = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True,blank=True, related_name='%(class)s_requests_created')
who_took_money = models.ForeignKey(User,on_delete=models.CASCADE,null=True,blank=True, related_name='who_took_money')
payment_method = models.CharField(choices=payment_method_list,max_length=4,default="CASH",blank=True,null=True)
date_paid = models.DateTimeField(blank=True,null=True)
date_created = models.DateTimeField(blank=True, null=True)
date_modified = models.DateTimeField(blank=True, null=True, auto_now=True)
is_paid = models.BooleanField(default=False, blank=True,null=True)
customer_total_when_paid = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)
customer_total_when_created = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)
description = models.TextField(blank=True,null=True)
price = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)
def __str__(self):
return self.description[0:12]
from django.db.models.signals import post_save
def update_total_owe_created_order(sender,instance,created,**kwargs):
if created:
order = instance
customer = order.customer
customer.total = customer.total_owe[0]
customer.save()
post_save.connect(update_total_owe_created_order,sender=Order)
def update_total_owe_updated_order(sender,instance,created,**kwargs):
if created==False:
order = instance
customer = order.customer
customer.total = customer.total_owe[0]
customer.save()
post_save.connect(update_total_owe_updated_order,sender=Order)
I have an app that you send your order to and it adds to database.
It only allows authenticated user to add order; so it shows who added that order. I can get the request.user with JWT authentication but can't save the model. When I send an API post request, I get that error. I could get the user with token but it gives me that error. I don't know why. I am using postman. I didn't get it normally but when I use postman it doesn't work.
ret = super().data
File "C:\Users\homet\Desktop\pharmacy\venv\lib\site-packages\rest_framework\serializers.py", line 253, in data
self._data = self.to_representation(self.instance)
File "C:\Users\homet\Desktop\pharmacy\venv\lib\site-packages\rest_framework\serializers.py", line 522, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Users\homet\Desktop\pharmacy\venv\lib\site-packages\rest_framework\serializers.py", line 522, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Users\homet\Desktop\pharmacy\venv\lib\site-packages\rest_framework\fields.py", line 1127, in to_representation
value = decimal.Decimal(str(value).strip())
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

The price in your Order model is a decimal field but you are casting the price from post request to float while creating the Order object.
price = models.DecimalField(max_digits=5,decimal_places=2,null=True,blank=True)
The price should be a Decimal object instead of float.
order = md.Order.objects.create(customer=customer,
date_created=zt.now(),
description=description,
price=Decimal(price),
customer_total_when_created=customer.total_owe[0]
)
customer_total_when_created should also be a Decimal instance but you haven't posted the Customer model which has total_owe.

Related

Django How to format JSON response from drf API?

I would like to know how to modify the way I represent the JSON Response of my requests to the API created with DRF, tabs, spaces, etc..., in order to respond exactly to my frontend app.
I have the following code:
My models.py extract:
class Email(models.Model):
user_email = models.CharField(primary_key=True, max_length=200)
user_phone_number = models.IntegerField()
user_device_id = models.CharField(max_length=200)#request.META.get('HTTP_DEVICE', '')
lat = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
lng = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True)
user_address = models.CharField(max_length=200)
creation_date = models.DateTimeField(default=None)
email_status = models.BooleanField(default=False)
email_score = models.IntegerField()
valid_email = models.BooleanField(default=False)
fraud = models.BooleanField(default=False)
My views.py extract:
class UserListView(APIView):
serializer_class = EmailSerializer
queryset = Email.objects.all()
pagination_class = StandardResultsSetPagination
def get_serializer_class(self):
if self.action == 'list':
return EmailListSerializer
return EmailSerializer
def post(self, request, *args, **kwargs):
parametros = request.POST
email='email=' + request._full_data['user_email']
response = UserConnector(email).get_user_data()
obgs = response[1]['results']
if len(obgs) == 0:
user_email = self.request.POST.get('user_email')
email_stat = ''
email_scor = ''
email_valid = ''
frau = ''
else:
obg = response[1]['results'][0]
user_email = self.request.POST.get('user_email')
email_stat = obg.get('email_status')
email_scor = obg.get('email_score')
email_valid = obg.get('valid_email')
frau = obg.get('fraud')
NewEmail = Email(
user_email = user_email,
user_phone_number = self.request.POST.get('user_phone_number'),
user_device_id = request.META.get('HTTP_DEVICE', ''),
lat = self.request.POST.get('lat'),
lng = self.request.POST.get('lng'),
user_address = self.request.POST.get('user_address'),
creation_date = timezone.now,
email_status = email_stat,
email_score = email_scor,
valid_email = email_valid,
fraud = frau
)
NewEmail.save()
serializer = EmailSerializer(NewEmail)
return Response(serializer.data)
I have receive the folowing JSON response:
{
"user_email": "meloadik#gmail.com",
"user_phone_number": 8117904544,
"user_device_id": "",
"lat": "20.9750000000000000",
"lng": "89.6141400000000000",
"user_address": "rfm mz5 lt4",
"creation_date": "2022-08-23T22:47:13.687178Z",
"email_status": null,
"email_score": 0,
"valid_email": 0,
"fraud": 0
}
I want to know how to format the JSON response differently, like this:
{
"email_response": {
"user_email": "carl#trully.ai",
"creation_date": "2020/06/01",
"email_status": "active",
"email_score": 910,
"valid_email": 1,
"fraud": 0
},
"phone_response": {
"user_phone_number": 8117904544,
}
}
Or modify my JSON Response with different types of styles, tabs, spaces, etc...
A quick fix would be to override EmailSerializer's to_representation method to something like this (pseudocode):
def to_representation(self, instance):
representation = super(EmailSerializer, self).to_representation(instance)
new_representation = {}
new_representation['email_response'] = {field: representation.get(field) for field in email_fields}
new_representation['phone_response'] = {field: representation.get(field) for field in phone_fields}
return new_representation

Django error: The Items could not be created because the data didn't validate

I get the following error:
ValueError at /create-items/
The Items could not be created because the data didn't validate., and can't find out what the issue is...
Views.py
def createMulitpleItemsPage(request):
currency = '€'
ItemFormSet = modelformset_factory(Items, form=CreateItemFormset, extra=1)
qs = Items.objects.none()
user = request.user.profile
formset = ItemFormSet(request.POST or None, queryset=qs, form_kwargs={'user': user})
# Create multiple items
if request.method == 'GET':
user = request.user.profile
ItemFormSet = modelformset_factory(Items, form=CreateItemFormset, extra=1)
qs = Items.objects.none()
formset = ItemFormSet(request.POST or None, queryset=qs, form_kwargs={'user': user})
context = {'formset': formset}
if request.method == 'POST':
print('printing POST: ', request.POST)
print('printing Errors: ', formset.errors)
if formset.is_valid():
formset = CreateItemFormset(user=request.user.profile, data=request.POST)
parent = formset.save(commit=False)
parent = formset.save()
for form in formset:
newitems = form.save(commit=False)
newitems.user = request.user.profile
newitems.save()
return redirect('items')
return render(request, 'base/mass_create_items.html', context)
Forms.py
class CreateItemFormset(ModelForm):
def __init__(self, user, *args, **kwargs):
super(CreateItemFormset, self).__init__(*args, **kwargs)
qs = Categories.objects.filter(user=user)
self.fields['item_category'] = ModelChoiceField(queryset=qs)
class Meta:
model = Items
fields = ['item_name', 'item_category', 'item_start_date', 'item_end_date', 'item_purchase_price', 'item_rest_value']
Models.py
class Items(models.Model):
user = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True)
item_name = models.CharField(max_length=200, null=False, blank=False)
item_category = models.ForeignKey(Categories, null=True, blank=True, on_delete=models.SET_NULL)
item_created_at = models.DateTimeField(auto_now_add=True, null=True, blank=False)
item_updated_at = models.DateTimeField(auto_now=True, null=True, blank=False)
item_start_date = models.DateField(null=True, blank=False)
item_end_date = models.DateField(null=True, blank=False)
item_purchase_price = models.FloatField(null=True, blank=False)
item_rest_value = models.FloatField(default=0, null=True, blank=False)
item_saving_goal = models.FloatField(default=0, null=True, blank=False)
item_date_delta = models.FloatField(default=0, null=True, blank=False)
item_days_passed = models.FloatField(default=0, null=True, blank=False)
item_currently_saved = models.FloatField(default=0, null=True, blank=False)
item_percentage_saved = models.FloatField(default=0.01, null=True, blank=False)
item_monthly_saving = models.FloatField(default=0, null=True, blank=False)
def save(self, *args, **kwargs):
self.item_saving_goal = self.item_purchase_price - self.item_rest_value
self.item_date_delta = (self.item_end_date.year - self.item_start_date.year) * 12 + ( self.item_end_date.month - self.item_start_date.month )
self.item_days_passed = (date.today().year - self.item_start_date.year) * 12 + ( date.today().month - self.item_start_date.month )
self.item_currently_saved = self.item_saving_goal * (self.item_days_passed / self.item_date_delta )
self.item_percentage_saved = self.item_currently_saved / self.item_saving_goal * 100
self.item_monthly_saving = self.item_saving_goal / self.item_date_delta
super().save(*args, **kwargs)
Error looks like this:
Internal Server Error: /create-items/
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/handlers/exception.py",
line 47, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/handlers/base.py",
line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/contrib/auth/decorators.py",
line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/Users/jelledekker/Library/Mobile Documents/com~apple~CloudDocs/Django/Aurelian web/base/views.py", line
304, in createMulitpleItemsPage
parent = formset.save(commit=False)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/forms/models.py",
line 458, in save
raise ValueError(
ValueError: The Items could not be created because the data didn't validate.
You are testing the formset for validity before binding it to POST!
if formset.is_valid():
formset = CreateItemFormset(user=request.user.profile, data=request.POST)
Think those two lines need to be reversed.

Django rest framework test does not create instances in test database

I'm having an issue in DRF tests when creating instance of a model, the status code in response is 'HTTP_201_CREATED' but the instance it self does not exist in the testing db.
here is my model :
class Item(SafeDeleteModel):
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_("Owner"))
name = models.CharField(_("Name"), max_length=150)
category = TreeForeignKey('merssis.ItemCategory', on_delete=models.SET_NULL, null=True, verbose_name=_("Category"))
fixed_price = models.FloatField(_("Fixed price"), default=0)
main_pic = ProcessedImageField(verbose_name=_("Main picture"), upload_to='item_pics', processors=[ItemWatermarker()],format='JPEG')
main_pic_thumbnail = ImageSpecField(source='main_pic',
processors=[ResizeToFill(384, 256)],
format='JPEG',
options={'quality': 100})
geo_location = models.PointField(srid=4326, null=True, blank=True, verbose_name=_("Geolocation"))
_safedelete_policy = SOFT_DELETE_CASCADE
def __str__(self):
return self.name
Serializer :
class ItemCreateSerializer(GeoFeatureModelSerializer):
PRICE_TYPE_CHOICES = (
('fixed', _('Fixed') ),
('open', _('Open') ),
)
owner = serializers.HiddenField(default=serializers.CurrentUserDefault())
price_type = serializers.ChoiceField(choices=PRICE_TYPE_CHOICES)
category = serializers.PrimaryKeyRelatedField(queryset=ItemCategory.objects.all(), many=False)#ItemCategorySerializer(many=False)
main_pic = serializers.ImageField(use_url='item_pics')
def validate(self, data):
user = self.context['request'].user
geo_data = data.get('geo_location')
#Validate fixed price value
if data['price_type'] == 'fixed':
if data.get('fixed_price') == None or int(data.get('fixed_price')) <= 0:
raise serializers.ValidationError({"fixed_price" :INVALIDE_PRICE_ERROR})
#Price type is open should explicitly set fixed price to 0
if data['price_type'] == 'open':
data['fixed_price'] = 0
#Validate geo_location
#geo_location post data form ====> {"type":"Point", "coordinates":[37.0625,-95.677068]}
if geo_data:
if not validate_in_country_location(user, geo_data):
raise serializers.ValidationError({"geo_location":OUTSIDE_COUNTRY_MSG})
return data
def create(self, validated_data):
#Remove price_type value since it is not a field in the model
#We used to determine th price type on the serializer only
validated_data.pop('price_type')
return Item(**validated_data)
class Meta:
model = Item
geo_field = 'geo_location'
fields = ( 'owner',
'name',
'price_type',
'category',
'fixed_price',
'main_pic',
'geo_location',
)
The view :
class ItemCreateAPIView(CreateAPIView):
queryset = Item.objects.all()
serializer_class = ItemCreateSerializer
permission_classes = [permissions.IsAuthenticated]
def perform_create(self, serializer, *args, **kwargs):
self.check_object_permissions(self.request, self.request.user)
serializer.save()
The test case :
class ItemTestCase(APITestCase):
def test_create_new_item(self):
"""
Testing Add new item functionality
"""
self.client_1 = APIClient()
self.user_1 = create_new_user(email='tester1#gmail.com', username='tester_1', password='qsdf654654', gender='male')
self.client_1.login(username='tester_1',password='qsdf654654')
image_file = create_test_image()
category = ItemCategory.objects.create(name='SomeCat')
new_item_data = {
'name': 'New Item',
'price_type' : 'open',
'category': str(category.pk),
'main_pic': image_file,
}
response = self.client_1.post(url, new_item_data, format='multipart')
items = Item.objects.filter(name='New Item')
print(response.status_code)
self.assertEqual( response.status_code, status.HTTP_201_CREATED)
self.assertEqual( items.count(), 1)
and when i run the test i get '201' printed in console AND AssertionError: 0 != 1
i'm fvkin confused
In the serializer create() the object was never saved so change:
return Item(**validated_data)
to:
return Item.objects.create(**validated_data) # create the object

Image with a chinese filename returns UnicodeEncodeError

I have an api backend made of Django Rest Framework and I can not return my Image File with chinese characters like code/温州银行.png. It always return the error below:
File "/usr/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 "/usr/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 "/usr/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/rest_framework/viewsets.py", line 83, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python2.7/site-packages/rest_framework/views.py", line 477, in dispatch
response = self.handle_exception(exc)
File "/usr/local/lib/python2.7/site-packages/rest_framework/views.py", line 437, in handle_exception
self.raise_uncaught_exception(exc)
File "/usr/local/lib/python2.7/site-packages/rest_framework/views.py", line 448, in raise_uncaught_exception
raise exc
UnicodeEncodeError: 'ascii' codec can't encode characters in position 9-12: ordinal not in range(128)
Is there any way to solve this?
My libraries:
Django==1.9.2
djangorestframework==3.5.1
My serializers.py:
class RemitPayeeSerializer(serializers.ModelSerializer):
class Meta:
model = RemitPayee
fields = '__all__'
depth = 2
def to_internal_value(self, data):
print 'To Internal Value'
ret = super(RemitPayeeSerializer, self).to_internal_value(data)
if data.get('level'):
ret['level'] = \
[int(level) for level in data.get('level').split(',')]
if data.get('bank'):
ret['bank'] = data.get('bank')
return ret
def validate(self, data):
'''
'''
ret = super(RemitPayeeSerializer, self).validate(data)
request = self.context['request']
if request.method == 'POST' or request.method == 'PUT':
if ret.get('remit_type') != 1 and \
ret.get('qr_code') is not None:
form = QRCodeUploadForm(request.data, request.FILES)
if form.is_valid():
ret['qr_code'] = form.cleaned_data['qr_code']
else:
raise serializers.ValidationError({
'error': [{'QR_code': _('Invalid QR Code')}]})
return ret
#is_advpermitted('change_remitpayee')
def update(self, instance, validated_data):
'''
'''
member_levels = validated_data.pop('level', None)
bank = validated_data.get('bank')
if bank:
validated_data['bank'] = Bank.objects.get(pk=bank)
for key, val in validated_data.items():
setattr(instance, key, validated_data[key])
instance.save()
if member_levels is not None:
instance.level.clear()
for level_id in member_levels:
level = Level.objects.get(pk=level_id)
instance.level.add(level)
instance.save()
return instance
#is_advpermitted('change_remitpayee')
def create(self, data):
'''
'''
member_levels = data.pop('level', None)
bank = data.get('bank')
data['bank'] = Bank.objects.get(pk=bank) if bank else None
remit_payee = RemitPayee.objects.create(**data)
if member_levels:
for level_id in member_levels:
level = Level.objects.get(pk=level_id)
remit_payee.level.add(level)
remit_payee.save()
return remit_payee
def to_representation(self, obj):
logger.info('----start-----')
ret = super(RemitPayeeSerializer, self).to_representation(obj)
request = self.context['request']
expand = request.GET.get('opt_expand')
# user, _ = parse_request_for_token(request)
# member = Member.objects.filter(user=user).first()
# if member:
# ret['remit_limit'] = member.level.remit_limit
logger.info('----Remit ret-----')
logger.info(ret)
bank = ret.get('bank')
if bank:
if expand:
ret['bank'] = {'id': bank['id'], 'name': bank['name']}
else:
ret['bank'] = bank['id']
level = ret.get('level')
if level:
member_levels = []
for x in level:
if expand:
member_levels.append({'id': x['id'], 'name': x['name'],
'remit_limit': x['remit_limit']})
else:
member_levels.append(str(x['id']))
ret['level'] = member_levels
return ret
My RemitPayee model:
class RemitPayee(models.Model):
remit_type = models.IntegerField(
default=1, null=True, blank=True, choices=REMIT_TYPE_OPTIONS)
payee_name = models.CharField(max_length=255, null=True, blank=True)
address = models.CharField(max_length=255, null=True, blank=True)
account = models.CharField(max_length=255, null=True, blank=True)
memo = models.TextField(null=True, blank=True)
nickname = models.CharField(max_length=255, null=True, blank=True)
qr_code = models.ImageField(upload_to='codes/',
null=True, blank=True)
sum_fund = models.FloatField(null=True, blank=True)
status = models.IntegerField(
default=1, null=True, blank=True, choices=STATUS_OPTIONS)
bank = models.ForeignKey(
Bank, null=True, blank=True, related_name='remit_payee_bank')
level = models.ManyToManyField(
Level, related_name='remit_payee_member_level')

contenttypes.models.DoesNotExist: ContentType matchingquery does not exist how to improve

by another project this comment system is worked! but there nothing, how to fix this issue?
full traceback
> Traceback (most recent call last): File
> "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\core\handlers\exception.py",
> line 41, in inner
> response = get_response(request) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\core\handlers\base.py",
> line 187, in _get_response
> response = self.process_exception_by_middleware(e, request) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\core\handlers\base.py",
> line 185, in _get_response
> response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\newstudio\serials\views.py",
> line 78, in post_of_serie
> content_type = ContentType.objects.get(model=c_type) File
> "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\db\models\manager.py",
> line 85, in manager_method
> return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\db\models\query.py",
> line 380, in get
> self.model._meta.object_name django.contrib.contenttypes.models.DoesNotExist: ContentType matching
> query does not exist.
this is views.py
initial_data = {
"content_type": serie.get_content_type,
"object_id": serie.id
}
if request.method == 'POST':
form = CommentForm(request.POST or None, initial=initial_data)
if form.is_valid():
c_type = form.cleaned_data.get("content_type")
content_type = ContentType.objects.get(model=c_type)
obj_id = form.cleaned_data.get('object_id')
content_data = form.cleaned_data.get("content")
parent_obj = None
try:
parent_id = int(request.POST.get("parent_id"))
except:
parent_id = None
if parent_id:
parent_qs = Comment.objects.filter(id=parent_id)
if parent_qs.exists() and parent_qs.count() == 1 :
parent_obj = parent_qs.first()
new_comment, created = Comment.objects.get_or_create(
user = request.user,
content_type = content_type,
object_id = obj_id,
content = content_data,
parent = parent_obj
)
return HttpResponseRedirect(new_comment.content_object.get_absolute_url())
form = CommentForm(initial=initial_data)
comments = Comment.objects.filter_by_instance(serie)
context = { "serie":serie,
"full_path":full_path,
"title":title,
"poster":poster,
"comments": comments,
"comment_form": form,
}
return render(request, 'series.html', context)
in html template contenttype is displayed the model which i use in my views
but it doesn't work. but averything displayed correctly
the second img
models
class Series(models.Model):
id = models.AutoField(primary_key=True)
rus_name = models.CharField(max_length=60)
eng_name = models.CharField(max_length=60)
slug = models.SlugField(unique=False)
serial_of_this_series = models.ForeignKey(Serial, on_delete=models.CASCADE, default=True)
season_of_this_series = models.ForeignKey(Season, on_delete=models.CASCADE, default=True)
number_of_series = models.IntegerField(default=0)
description = models.TextField(max_length=700, blank=True, default=None)
size_of_torent_file = models.CharField(max_length=60, default=None)
link_for_dowloand_serie_in_quality_360p = models.CharField(max_length=60, default=None)
link_for_dowloand_serie_in_quality_720p = models.CharField(max_length=60, default=None)
link_for_dowloand_serie_in_quality_1080p = models.CharField(max_length=60, default=None)
rating = models.FloatField(default=0, blank=True)
is_active = models.BooleanField(default=True)
timestamp_rus = models.DateField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
timestamp_eng = models.CharField(max_length=60)
time_of_series = models.DecimalField(max_digits=10, decimal_places=2, default=42)
new_or_old = models.BooleanField(default=True)
def save(self, *args, **kwargs):
name_of_serial = self.serial_of_this_series.rus_name_of_seriall
number_of_season = self.season_of_this_series.number_of_season
number_of_series = self.number_of_series
if self.new_or_old:
#notification_for_new_series_task.delay(name_of_serial, number_of_season, number_of_series)
season_module = Season.objects.get(slug=self.season_of_this_series.slug, serial_for_this_season=self.serial_of_this_series)
season_module.number_of_series_released += 1
season_module.save()
self.new_or_old = False
return super(Series, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('series:post_of_serie', kwargs=
{'serial_slug': self.serial_of_this_series.slug,
'season_slug': self.season_of_this_series.slug,
'series_slug': self.slug})
def __str__(self):
return "%s | %s" % (self.rus_name, self.number_of_series)
#property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
#property
def get_content_type(self):
instance = self
content_type = ContentType.objects.get_for_model(instance.__class__)
return content_type
class Meta:
ordering = ["-timestamp_rus"]
verbose_name = 'Series'
verbose_name_plural = 'Series'
I would expect the content_type value to be lowercase i.e. series instead of Series.
Your Serie.get_content_type property returns the content type instance. You should use the model field.
initial_data = {
"content_type": serie.get_content_type.model,
"object_id": serie.id,
}
It's not clear why you need to include the content_type and object_id in the form at all. You already have serie in the view, so you should be able to remove those fields from the form then update the view as follows:
if form.is_valid():
content_type = serie.get_content_type
obj_id = serie.id
content_data = form.cleaned_data.get("content")
...