Unittesting Django CreateView with mock library - django

I'm trying to test my CreateView by posting some data and mocking models' save() method.
class BaseViewTest(TestCase):
def setUp(self):
self.user = UserFactory()
self.factory = RequestFactory()
class MuayeneCreateViewTest(BaseViewTest):
def test_get(self):
request = self.factory.get(reverse('muayene:create'))
request.user = self.user
response = MuayeneCreateView.as_view()(request)
self.assertEqual(response.status_code, 200)
self.assertTrue('form' in response.context_data)
self.assertTrue('muayene/muayene_form.html' in response.template_name)
#patch('muayene.models.Muayene.save', MagicMock(name="save"))
def test_post(self):
hasta = HastaFactory()
ilac1 = IlacFactory()
ilac2 = IlacFactory()
data = {
'hasta': hasta.id,
'tarih': str(datetime.date.today()),
'yakinma': 'Kusma',
'kullandigi_ilaclar': [ilac1.id, ilac2.id],
'öntani_tani': 'Öntanı ve tanı',
'öneri_görüsler': 'Öneri ve Görüşler',
'özel_notlar': 'Özel notlar'
}
request = self.factory.post(reverse('muayene:create'), data)
request.user = self.user
response = MuayeneCreateView.as_view()(request)
self.assertEqual(response.status_code, 302)
self.assertTrue(Muayene.save.called)
self.assertEqual(Muayene.save.call_count, 1)
Here is MuayeneCreateView:
class MuayeneCreateView(LoginRequiredMixin, CreateView):
login_url = '/login/'
model = Muayene
form_class = MuayeneCreateForm
and traceback:
ERROR: test_post (tests.test_muayene.MuayeneCreateViewTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib64/python3.5/unittest/mock.py", line 1157, in patched
return func(*args, **keywargs)
File "/home/egegunes/Dropbox/Programs/hastatakip/tests/test_muayene.py", line 153, in test_post
response = MuayeneCreateView.as_view()(request)
File "/usr/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/usr/lib/python3.5/site-packages/django/contrib/auth/mixins.py", line 56, in dispatch
return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)
File "/usr/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "/usr/lib/python3.5/site-packages/django/views/generic/edit.py", line 256, in post
return super(BaseCreateView, self).post(request, *args, **kwargs)
File "/usr/lib/python3.5/site-packages/django/views/generic/edit.py", line 222, in post
return self.form_valid(form)
File "/usr/lib/python3.5/site-packages/django/views/generic/edit.py", line 201, in form_valid
self.object = form.save()
File "/usr/lib/python3.5/site-packages/django/forms/models.py", line 452, in save
self._save_m2m()
File "/usr/lib/python3.5/site-packages/django/forms/models.py", line 434, in _save_m2m
f.save_form_data(self.instance, cleaned_data[f.name])
File "/usr/lib/python3.5/site-packages/django/db/models/fields/related.py", line 1618, in save_form_data
setattr(instance, self.attname, data)
File "/usr/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 480, in __set__
manager = self.__get__(instance)
File "/usr/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 468, in __get__
return self.related_manager_cls(instance)
File "/usr/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 751, in __init__
(instance, self.source_field_name))
ValueError: "<Muayene: ID: None - 2016-07-31 - Bob Baz>" needs to have a value for field "muayene" before this many-to-many relationship can be used.
I couldn't figure out what causes this error. Muayene instance is used by some other models but IMO this error must not show up unless I try to create one of those models with this instance.
Edit
Muayene model:
class Muayene(models.Model):
hasta = models.ForeignKey(
'hasta.Hasta',
on_delete=models.CASCADE
)
tarih = models.DateField(
default = timezone.now
)
yakinma = models.TextField(
max_length = 255,
blank = True,
null = True
)
kullandigi_ilaclar = models.ManyToManyField(
Ilac,
blank = True
)
baki = models.TextField(
max_length = 255,
blank = True,
null = True
)
öntani_tani = models.TextField(
max_length = 255,
blank = True,
null = True
)
öneri_görüsler = models.TextField(
max_length = 255,
blank = True,
null = True
)
özel_notlar = models.TextField(
max_length = 255,
blank = True,
null = True
)
def __str__(self):
tarih = str(self.tarih)
hasta = str(self.hasta.ad + " " + self.hasta.soyad)
pk = str(self.pk)
return "ID: " + pk + " - " + tarih + " - " + hasta
def get_absolute_url(self):
return reverse('muayene:detail', kwargs={'pk':self.pk})
def was_today(self):
today = datetime.date.today()
if today - datetime.timedelta(days=1) <= self.tarih <= today:
return True
else:
return False
Models in relation with Muayene:
class Recete(models.Model):
hasta = models.ForeignKey(
'hasta.Hasta',
on_delete=models.CASCADE
)
muayene = models.ForeignKey(
'muayene.Muayene',
on_delete=models.CASCADE,
)
tarih = models.DateField(
default = timezone.now
)
ilaclar = models.ManyToManyField(Ilac)
def __str__(self):
return str(self.tarih)
def get_absolute_url(self):
return reverse('muayene:recete-detail', kwargs={'pk':self.pk})
class Rapor(models.Model):
hasta = models.ForeignKey(
'hasta.Hasta',
on_delete=models.CASCADE
)
muayene = models.ForeignKey(
'muayene.Muayene',
on_delete=models.CASCADE
)
tarih = models.DateField(
default = timezone.now
)
tani = models.CharField(
blank = True,
null = True,
max_length = 255
)
gun = models.PositiveSmallIntegerField(
default = 1
)
def __str__(self):
return str(self.hasta)
def get_absolute_url(self):
return reverse('muayene:rapor-detail', kwargs={'pk':self.pk})
class LaboratuvarIstek(models.Model):
hasta = models.ForeignKey(
'hasta.Hasta',
on_delete=models.CASCADE
)
muayene = models.ForeignKey(
'muayene.Muayene',
on_delete=models.CASCADE,
)
tarih = models.DateField(
default = timezone.now
)
istekler = models.ManyToManyField(Laboratuvar)
def __str__(self):
return str(self.hasta)
def get_absolute_url(self):
return reverse('muayene:lab-detail', kwargs={'pk':self.pk})

You can actually see failing reason in your traceback:
File "/usr/lib/python3.5/site-packages/django/forms/models.py", line 452, in save
self._save_m2m()
That is because your view doesn't call model's save method directly. Instead it gets form that is used for model (or creates one with factory) and calls form's save method. You can check this method at django.forms.models.BaseModelForm.save. So if you really want to count calls on model instance and don't wanna fail test, you shoud mock django.forms.models.BaseModelForm._save_m2m too, because it gets called in form's save method.

Related

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

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.

Django-filter - filter an annotated field

I'm using Django-filter on my django-tables2 table, I have a custom filter that uses one search box to search all fields. SiteFilterEx, it gets all the field names and creates or queries to search each field name.
my model has the following:
class Site(models.Model):
location = models.CharField(max_length=50)
ref = models.CharField(max_length=255, blank=True, null=True)
bgp_as = models.CharField(max_length=6, verbose_name="BGP AS Number")
opening_date = models.DateField(verbose_name="Site opening date", blank=True, null=True)
tel = models.CharField(max_length=20, blank=True, null=True)
address = models.CharField(max_length=255, blank=True, null=True)
town = models.CharField(max_length=255, blank=True, null=True)
postcode = models.CharField(max_length=10, blank=True, null=True)
class DeviceCircuitSubnets(models.Model):
device = models.ForeignKey(Device, on_delete=models.CASCADE)
circuit = models.ForeignKey(Circuit, on_delete=models.CASCADE, blank=True, null=True)
subnet = models.ForeignKey(Subnet, on_delete=models.CASCADE)
active_link = models.BooleanField(default=False, verbose_name="Active Link?")
active_link_timestamp = models.DateTimeField(auto_now=True, blank=True, null=True)
However id like to also search against the annotated field "active_circuit" (which can be seen in the QuerySet)
but when I add this to the list of fields, I get errors stating it doesn't exist.
I need to somehow pass the annotated field through to the filter as a valid field to search for or something else?
filter:
class SiteFilterEx(django_filters.FilterSet):
ex = django_filters.CharFilter(label='Ex filter', method='filter_ex')
search_fields = ['location', 'sitesupernet__subnet', 'bgp_as', 'opening_date','town','postcode','active_circuit']
def filter_ex(self, qs, name, value):
if value:
q_parts = value.split()
# Use a global q_totals
q_totals = Q()
# This part will get us all possible segmantiation of the query parts and put it in the possibilities list
combinatorics = itertools.product([True, False], repeat=len(q_parts) - 1)
possibilities = []
for combination in combinatorics:
i = 0
one_such_combination = [q_parts[i]]
for slab in combination:
i += 1
if not slab: # there is a join
one_such_combination[-1] += ' ' + q_parts[i]
else:
one_such_combination += [q_parts[i]]
possibilities.append(one_such_combination)
# Now, for all possiblities we'll append all the Q objects using OR
for p in possibilities:
list1=self.search_fields
list2=p
perms = [zip(x,list2) for x in itertools.permutations(list1,len(list2))]
for perm in perms:
q_part = Q()
for p in perm:
q_part = q_part & Q(**{p[0]+'__icontains': p[1]})
q_totals = q_totals | q_part
qs = qs.filter(q_totals)
return qs
class Meta:
model = Site
fields = ['ex']
form = SiteFilterForm
view:
class Sites(LoginRequiredMixin, ExportMixin, PagedFilteredTableView):
model = Site
table_class = SiteTable
template_name = "app_settings/table_view.html"
login_url = '/login/'
redirect_field_name = 'redirect_to'
filter_class = SiteFilterEx
exclude_columns = ("buttons", )
table_pagination = {'per_page': 12}
def dispatch(self, *args, **kwargs):
site_type = get_object_or_404(SiteType, pk=self.kwargs['site_type'])
site_state = 'Open' if self.kwargs['state'] else 'Closed'
self.site_type_name = '{} {}s'.format(site_state, site_type.site_type)
self.site_type_icon = 'fa {}'.format(site_type.icon)
return super(Sites, self).dispatch(*args, **kwargs)
def get_queryset(self):
site_type = self.kwargs['site_type']
subnet = Subquery(
DeviceCircuitSubnets.objects.filter(device__site_id=OuterRef('id'), \
active_link=True, \
circuit__decommissioned=False
).values('circuit__name')[:1])
active_circuit = Subquery(
DeviceCircuitSubnets.objects.filter(device__site_id=OuterRef('id'), \
active_link=True, \
circuit__decommissioned=False
).values('circuit__name')[:1])
return super(Sites, self).get_queryset().filter(
is_live=self.kwargs['state'], site_type_id=site_type
).annotate(
active_circuit=active_circuit
).prefetch_related('sitesupernet_set')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['page_icon']=self.site_type_icon
context['page_title']=self.site_type_name
return context
Traceback error:
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
34. response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "/itapp/itapp/sites/views.py" in dispatch
127. return super(Sites, self).dispatch(*args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/mixins.py" in dispatch
52. return super().dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch
97. return handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/views/generic/list.py" in get
142. self.object_list = self.get_queryset()
File "/itapp/itapp/sites/views.py" in get_queryset
142. return super(Sites, self).get_queryset().filter(
File "/itapp/itapp/itapp/functions.py" in get_queryset
560. return self.filter.qs
File "/usr/local/lib/python3.6/site-packages/django_filters/filterset.py" in qs
237. qs = self.filter_queryset(qs)
File "/usr/local/lib/python3.6/site-packages/django_filters/filterset.py" in filter_queryset
224. queryset = self.filters[name].filter(queryset, value)
File "/usr/local/lib/python3.6/site-packages/django_filters/filters.py" in __call__
765. return self.method(qs, self.f.field_name, value)
File "/itapp/itapp/sites/filters.py" in filter_ex
53. qs = qs.filter(q_totals)
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py" in filter
892. return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py" in _filter_or_exclude
910. clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py" in add_q
1290. clause, _ = self._add_q(q_object, self.used_aliases)
File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py" in _add_q
1312. current_negated, allow_joins, split_subq, simple_col)
File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py" in _add_q
1318. split_subq=split_subq, simple_col=simple_col,
File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py" in build_filter
1190. lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py" in solve_lookup_type
1049. _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py" in names_to_path
1420. "Choices are: %s" % (name, ", ".join(available)))
Exception Type: FieldError at /sites/sites/1/2/
Exception Value: Cannot resolve keyword 'active_circuit' into field. Choices are: acc_short, address, device, downtimeschedule, id, is_live, last_hw_refresh_date, location, no_wallboard, opening_date, postcode, ref, site_type, site_type_id, sitecircuits, sitecontacts, sitefile, sitenotes, sitesupernet, snmpdata, tel, town, watchlist
Try to Mention a type for the Subquery , the models can be imported from django.db import models
active_circuit = Subquery(
DeviceCircuitSubnets.objects.filter(device__site_id=OuterRef('id'), \
active_link=True, \
circuit__decommissioned=False
).values('circuit__name')[:1],output_field=models.CharField())

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")
...

Django Error: __init__() takes exactly 2 arguments (3 given)

Anyone can find what is causing the error in my code? I already searched, but didn't find an answer. I think the problem is with the function objects.get(param), but I'm not sure.
What I wanted to do with my code was to retrieve the objects Genre, Country, Language and Directors if they were already added to the database.
Here's the code:
Models.py
from django.db import models
from numpy import unique
class Director(models.Model):
director = models.CharField(max_length=500, unique=True)
def __unicode__(self):
return self.director
def __init__(self, director):
super(Director, self).__init__()
self.director = director
class Language(models.Model):
language = models.CharField(max_length=500, unique=True)
def __unicode__(self):
return self.language
def __init__(self, language):
super(Language, self).__init__()
self.language = language
class Genre(models.Model):
genre = models.CharField(max_length=500, unique=True)
def __unicode__(self):
return self.genre
def __init__(self, genre):
super(Genre, self).__init__()
self.genre = genre
class Country(models.Model):
country = models.CharField(max_length=500, unique=True)
def __unicode__(self):
return self.country
def __init__(self, country):
super(Country, self).__init__()
self.country = country
class Movie(models.Model):
id_movie = models.CharField(max_length=200, unique=True)
rating = models.CharField(max_length=200)
votes = models.CharField(max_length=200)
year = models.CharField(max_length=10)
genre = models.ManyToManyField(Genre)
country = models.ManyToManyField(Country)
language = models.ManyToManyField(Language)
directors = models.ManyToManyField(Director)
def __init__(self, id_movie, rating, votes, year):
super(Movie, self).__init__()
self.id_movie = id_movie
self.rating = rating
self.votes = votes
self.year = year
def __unicode__(self):
return self.id_movie
crawler.py
from movie_info.models import Movie, Genre, Director, Language, Country
def get_movie_info(codigo_do_filme):
import imdb
ia = imdb.IMDb()
movie = ia.get_movie(codigo_do_filme)
return {'titulo': movie['title'], 'rating': movie['rating'], 'votes': movie['votes'], 'ano': movie['year'], 'genero': movie['genre'][0], 'pais': movie['countries'][0], 'idioma': movie['lang'][0], 'directors': movie['director']}
def read_sheet(file_name, fieldnames=None, delimiter=",", quotechar="\n"):
from csv import DictReader
reader = DictReader(open(file_name,'rb'), fieldnames = fieldnames, delimiter = delimiter, quotechar=quotechar)
return reader
def fill_db_movie_info(the_sheet_file):
file_csv = read_sheet(the_sheet_file)
for movie in file_csv:
id_filme = movie['id_move']
if not Movie.objects.filter(id_movie=id_filme).exists():
info = get_movie_info(id_filme)
rating_imdb = info['rating']
movie_votes = info['votes']
movie_year = info['ano']
movie_genre = info['genero']
movie_country = info['pais']
movie_lang = info['idioma']
movie_directors = info['directors']
addToDB = Movie(id_filme, rating_imdb, movie_votes, movie_year)
addToDB.save()
if not Genre.objects.filter(genre=movie_genre).exists():
genreToDB = Genre(movie_genre)
genreToDB.save()
addToDB.genre.add(genreToDB)
else:
addToDB.genre.add(Genre.objects.get(genre=movie_genre))
if not Country.objects.filter(country=movie_country).exists():
countryToDB = Country(movie_country)
countryToDB.save()
addToDB.country.add(countryToDB)
else:
addToDB.country.add(Country.objects.get(country=movie_country))
if not Language.objects.filter(language=movie_lang).exists():
langToDB = Language(movie_lang)
langToDB.save()
addToDB.language.add(langToDB)
else:
addToDB.language.add(Language.objects.get(language=movie_lang))
for m_director in movie_directors:
if not Director.objects.filter(director=m_director['name']).exists():
directorsToDB = Director(m_director['name'])
directorsToDB.save()
addToDB.directors.add(directorsToDB)
else:
addToDB.directors.add(Director.objects.get(director=m_director['name']))
print "salvou: " + id_filme, rating_imdb, movie_votes, movie_year, movie_genre, movie_country, movie_lang, movie_directors[0]
The Traceback:
pydev debugger: starting (pid: 1424)
Traceback (most recent call last):
File "/Applications/eclipse/plugins/org.python.pydev_3.5.0.201405201709/pysrc/pydevd.py", line 1845, in <module>
debugger.run(setup['file'], None, None)
File "/Applications/eclipse/plugins/org.python.pydev_3.5.0.201405201709/pysrc/pydevd.py", line 1373, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Users/rubenspessoa/Documents/Workspace/LearningDjango/main.py", line 7, in <module>
fill_db_movie_info('/Users/rubenspessoa/Documents/Workspace/DATASET/test_subdataset.csv')
File "/Users/rubenspessoa/Documents/Workspace/LearningDjango/crawler.py", line 49, in fill_db_movie_info
addToDB.country.add(Country.objects.get(country=movie_country))
File "/Library/Python/2.7/site-packages/django/db/models/manager.py", line 151, in get
return self.get_queryset().get(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 304, in get
num = len(clone)
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 77, in __len__
self._fetch_all()
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 857, in _fetch_all
self._result_cache = list(self.iterator())
File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 230, in iterator
obj = model(*row_data)
TypeError: __init__() takes exactly 2 arguments (3 given)
You have defined __init__ methods for all your models. You should not do that.