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())
Related
I am trying to call a get api but it gives me this error everytime.
The error:
AttributeError: Got AttributeError when attempting to get a value for field name on serializer NestedSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the int instance.
Original exception text was: 'int' object has no attribute 'name'.
My models:
class Destination(models.Model):
Continent_Name = (
('Europe', 'Europe',),
('Asia', 'Asia',),
('North America', 'North America',),
('South America', 'South America',),
('Africa', 'Africa',),
('Oceania', 'Oceania',),
('Polar', 'Polar',),
('Regions', 'Regions',),
)
name = models.CharField(max_length=255, unique=True)
continent = models.CharField(max_length=255, choices=Continent_Name, default='Europe')
top = models.BooleanField(default=False)
dest_image = models.ImageField(blank=True)
def __str__(self):
return self.name
class Package(models.Model):
TOUR_TYPE = (
('Custom-made trip with guide and/or driver', 'Custom-made trip with guide and/or driver',),
('Custom-made trip without guide and driver', 'Custom-made trip without guide and driver',),
('Group Tour', 'Group Tour',),
('Cruise Tour', 'Cruise Tour',),
)
operator = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
destination = models.ForeignKey(Destination, on_delete=models.CASCADE)
package_name = models.CharField(max_length=255)
city = models.CharField(max_length=255)
featured = models.BooleanField(default=False)
price = models.IntegerField(verbose_name="Price in Nrs")
price_2 = models.IntegerField(verbose_name="Price in $")
duration = models.IntegerField(default=5)
duration_hours = models.PositiveIntegerField(blank=True,null=True,verbose_name="Hours If One day Tour")
discount = models.IntegerField(verbose_name="Discount %", default=15)
#discounted_price = models.IntegerField(default=230)
#savings = models.IntegerField(default=230)
tour_type = models.CharField(max_length=100, choices=TOUR_TYPE, default='Group Tour')
new_activity = models.ManyToManyField(NewActivity)
accommodation = models.CharField(max_length=255, default='Guest House & Hotel')
transport = models.CharField(max_length=150, default='Flight')
age_range = models.CharField(max_length=100, default='6 to 79 years old')
fix_departure = models.BooleanField(default=False)
rating = models.IntegerField(choices=((1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 5))
)
image = models.ImageField(blank=True, verbose_name="Thumbnail Image-Vertical")
content =RichTextField()
highlights = RichTextField()
inclusions = RichTextField()
exclusions = RichTextField()
# itinerary = models.ManyToManyField(Itinerary)
itinerary_text = RichTextField()
faqs = RichTextField(blank=True)
image_1= models.ImageField(blank=True,null = True,verbose_name="Image-Horizontal")
image_2= models.ImageField(blank=True,null = True,verbose_name="Image-Square")
image_3= models.ImageField(blank=True,null = True,verbose_name="Image-Sqaure")
date_created = models.DateField()
def __str__(self):
return self.package_name
My views:
class PackageSearchAPi(ListAPIView):
queryset = Package.objects.all().order_by('package_name')
serializer_class = PackageSerializer
def get(self, request, *args, **kwargs):
search = self.request.query_params.get('search',None)
if search is not None:
qs = Package.objects.filter(Q(destination__name__icontains=search)|
Q(destination__continent__icontains=search)|
Q(package_name__icontains=search)|
Q(city__icontains=search)).disctinct()
else:
qs = Package.objects.values('id','destination','package_name','city')
serializer = PackageSerializer(qs,many=True)
return Response(serializer.data,status=200)
My serializers:
class PackageSerializer(serializers.ModelSerializer):
class Meta:
model = Package
fields = ['id', 'operator','destination', 'package_name', 'duration', 'featured', 'price','price_2', 'discount',
'city', 'tour_type','new_activity', 'accommodation', 'transport', 'age_range',
'fix_departure', 'rating', 'image', 'date_created', ]
depth = 1
Here I checked the code and nothing seems to be wrong in any part but keeps getting the same above error.
Traceback:
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\Saroj\Desktop\TravelCRM\apps\packages\views.py", line 251, in get
return Response(serializer.data,status=200)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 760, in data
ret = super().data
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 260, in data
self._data = self.to_representation(self.instance)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 677, in to_representation
return [
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 678, in <listcomp>
self.child.to_representation(item) for item in iterable
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 529, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 516, in to_representation
attribute = field.get_attribute(instance)
File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\fields.py", line 487, in get_attribute
raise type(exc)(msg)
AttributeError: Got AttributeError when attempting to get a value for field `name` on serializer `NestedSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `int` instance.
Original exception text was: 'int' object has no attribute 'name'.
For nested relations you have to define nested serializer
class DestinationSerializer(serializers.Serializer):
name = serializers.CharField()
top = serializers.BooleanField()
continent = serializers.CharField()
class PackageSerializer(serializers.ModelSerializer):
destination = DestinationSerializer()
class Meta:
model = Package
fields = ['id', 'operator','destination', 'package_name', 'duration', 'featured', 'price','price_2', 'discount',
'city', 'tour_type','new_activity', 'accommodation', 'transport', 'age_range',
'fix_departure', 'rating', 'image', 'date_created', ]
I'm trying to use elastic search in my django model.
Currently, if I search with title only it works and returns correct records but when I tried to add a carparts filter it asked me to add index.FilterField('cartpart_id') which I did but now it throws an error that
'NoneType' object has no attribute '_meta'
This is my code
class IndexPage:
def get_context(self, request):
recipes = CarPage.objects.child_of(self).live().public() \
.select_related('listing_image')
extra_url_params = ''
s = get_search_backend()
filter_name = request.GET.get("title")
filter_carparts = request.GET.get('carparts')
if filter_carparts:
filter_carparts = filter_carparts.split(",")
filter_carparts = [ int(x) for x in filter_carparts ] #Output = [1,2,3]
if filter_name and filter_carparts:
cars = cars.filter(carparts__carpart__in=filter_carparts).distinct()
cars = s.search(filter_name, recipes)
elif filter_carparts and not filter_name:
cars = cars.filter(carparts__carpart__in=filter_carparts).distinct()
extra_url_params = 'carparts={}'.format()
elif filter_name and not filter_carparts:
cars = s.search(filter_name, recipes)
else:
cars = cars
return context
#register_snippet
class CarPart(models.Model):
title = models.CharField(max_length=50)
class Meta:
verbose_name_plural = 'Car Parts'
def __str__(self):
return self.title
class CarParts(model.sModel):
source_page = ParentalKey(
'home.CarPage', related_name='carparts'
)
carpart = models.ForeignKey(
CarPart,
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
panels = [
SnippetChooserPanel('catpart'),
]
class CarPage(BasePage):
enter code here
content_panels = BasePage.content_panels + [
InlinePanel('carparts', label="Car Part"),
]
def get_context(self, request):
context = super().get_context(request)
return context
class CarPage(BasePage):
title= models.CharField(max_length=20)
search_fields = BasePage.search_fields + [
index.SearchField('title'),
index.FilterField('cartpart_id') <--- issue
]
content_panels = BasePage.content_panels + [
FieldPanel('title'),
]
def get_context(self, request):
context = super().get_context(request)
return context
Full Traceback:
Traceback:
File "/home/mycars/code/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/home/mycars/code/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/home/mycars/code/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/mycars/code/env/lib/python3.6/site-packages/wagtail/core/views.py" in serve
24. return page.serve(request, *args, **kwargs)
File "/home/mycars/code/env/lib/python3.6/site-packages/wagtail/core/models.py" in serve
721. self.get_context(request, *args, **kwargs)
File "/home/mycars/code/models.py" in get_context
171. cars = s.search(filter_name, cars)
File "/home/mycars/code/env/lib/python3.6/site-packages/wagtail/search/backends/base.py" in search
370. partial_match=partial_match,
File "/home/mycars/code/env/lib/python3.6/site-packages/wagtail/search/backends/base.py" in _search
358. search_query.check()
File "/home/mycars/code/env/lib/python3.6/site-packages/wagtail/search/backends/base.py" in check
157. self._get_filters_from_where_node(self.queryset.query.where, check_only=True)
File "/home/mycars/code/env/lib/python3.6/site-packages/wagtail/search/backends/base.py" in _get_filters_from_where_node
108. child_filters = [self._get_filters_from_where_node(child) for child in where_node.children]
File "/home/mycars/code/env/lib/python3.6/site-packages/wagtail/search/backends/base.py" in <listcomp>
108. child_filters = [self._get_filters_from_where_node(child) for child in where_node.children]
File "/home/mycars/code/env/lib/python3.6/site-packages/wagtail/search/backends/base.py" in _get_filters_from_where_node
100. return self._process_filter(field_attname, lookup, value, check_only=check_only)
File "/home/mycars/code/env/lib/python3.6/site-packages/wagtail/search/backends/base.py" in _process_filter
78. result = self._process_lookup(field, lookup, value)
File "/home/mycars/code/env/lib/python3.6/site-packages/wagtail/search/backends/elasticsearch5.py" in _process_lookup
20. column_name = self.mapping.get_field_column_name(field)
File "/home/mycars/code/env/lib/python3.6/site-packages/wagtail/search/backends/elasticsearch2.py" in get_field_column_name
105. prefix = definition_model._meta.app_label.lower() + '_' + definition_model.__name__.lower() + '__'
Exception Type: AttributeError at /cars/
Exception Value: 'NoneType' object has no attribute '_meta'
I have the following problem, I implemented an ajax function to be able to have a dependent dropdown, at the time of creating a question all right but the problem arrives when saving it and sending me to the page to add questions, could someone tell me that I am wrong?.
error:
Traceback (most recent call last):
File "C:\Users\Oficina\AppData\Local\Programs\Python\Python37-32\lib\site
packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Oficina\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Oficina\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Oficina\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\Oficina\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Proyectos\proyecto-educa-quiz\classroom\views\teachers.py", line 733, in question_change
form = QuestionForm(instance=question, quiz=quiz)
File "C:\Proyectos\proyecto-educa-quiz\classroom\forms.py", line 450, in __init__
self.fields['indicador'].queryset = self.instance.objetivo.indicador_set.order_by('id')
AttributeError: 'NoneType' object has no attribute 'indicador_set'
this is my code:
forms.py:
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
context_object_name = 'questions'
fields = ('number','objetivo','indicador','text','description', 'texto' ,'puntaje' ,'image','document','video')
label = 'Pregunta'
def __init__(self ,quiz ,*args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['objetivo'].queryset = Planificacion.objects.filter(asignatura_id = quiz.subject.id, curso_id = quiz.curso.id)
self.fields['indicador'].queryset = PlanificacionIndicador.objects.none()
self.fields['texto'].queryset = TextoQuestion.objects.filter(owner__id=quiz.owner.id)
if 'objetivo' in self.data:
try:
objetivo_id = int(self.data.get('objetivo'))
self.fields['indicador'].queryset = PlanificacionIndicador.objects.filter(objetivo_id=objetivo_id).order_by('indicador_evaluacion')
except (ValueError, TypeError):
pass
elif self.instance.pk:
self.fields['indicador'].queryset = self.instance.objetivo.indicador_set.order_by('id')
view.py:
#login_required
#teacher_required
def question_change(request, quiz_pk, question_pk):
AnswerFormSet = inlineformset_factory(
Question, # modelo padre
Answer, # modelo base
formset=BaseAnswerInlineFormSet,
fields=('text' ,'is_correct'),
min_num=2,
validate_min=True,
max_num=4,
validate_max=True,
)
if request.method == 'POST':
form = QuestionForm(quiz ,request.POST, request.FILES ,instance=question)
formset = AnswerFormSet(request.POST, request.FILES, instance=question)
if form.is_valid() and formset.is_valid():
with transaction.atomic():
form.save()
formset.save()
messages.success(request, 'Pregunta y respuestas guardadas exitosamente!')
return redirect('teachers:quiz_change', quiz.pk)
else:
form = QuestionForm(instance=question, quiz=quiz)
formset = AnswerFormSet(instance=question_pk)
return render(request, 'classroom/teachers/question_change_form.html', {
'quiz': quiz,
'question': question,
'form': form,
'formset': formset
})
models.py:
class Question(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions')
number = models.IntegerField(verbose_name=("Número de la pregunta"))
objetivo = models.ForeignKey(Planificacion, on_delete=models.SET_NULL, related_name='questions', verbose_name=('Objetivo aprendizaje'), blank=True, null=True)
indicador = models.ForeignKey(PlanificacionIndicador, on_delete=models.SET_NULL, related_name='questions', verbose_name=('Indicador Evaluación'), blank=True, null=True)
text = models.CharField('Pregunta', max_length=255)
texto= models.ForeignKey(TextoQuestion, on_delete=models.CASCADE, blank=True, null=True, verbose_name=('Texto'),help_text='Si tienes algún texto creado para esta prueba seleccionalo si no dejalo en blanco.')
image = models.ImageField( null = True, upload_to='quiz_images',default=False, blank=True,verbose_name=('Imagen'))
document = models.FileField(null=True, upload_to='quiz_images',default= False, blank=True,verbose_name=('Audio'))
video = models.FileField(null=True, upload_to='quiz_images',default= False, blank=True,verbose_name=('Video'))
description = models.CharField(max_length=255, null= True, blank=True, verbose_name=("Descripción") )
puntaje = models.IntegerField(verbose_name=("Puntos"), help_text=("Puntaje que tendra cada pregunta que dara un total para la nota final del alumno."))
objects = InheritanceManager()
def __str__(self):
return self.text
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')
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")
...