Using Boolean in Django Custom Query Set - python

Lately I had came to one strange thing when I was working with Django custom querysets. So, I am using request.GET for passing boolean value to my django view. Then I pass this value to my custom queryset function. It seems weird because it works in case of basic query but not with '__isnull'. Are there any differencies?
views.py
if request.GET.get('available'):
items = Item.objects.is_available(request.GET.get('available')) # this works
...
if request.GET.get('order'):
transfers = Transfer.objects.not_working_is_order(request.GET.get('order')) # not working
managers.py
class ItemQuerySet(QuerySet):
def is_available(self, is_available):
return self.filter(is_available=is_available) # this works
class TransferQuerySet(QuerySet):
def is_order(self, bool):
if bool == 'False':
return self.filter(order__isnull=False)
elif bool == 'True':
return self.filter(order__isnull=True) # this works
def not_working_is_order(self, bool):
return self.filter(order__isnull=bool) # not working
mytemplate.html
Not available
myothertemplate.html
Not order

That's because bool is not a boolean, it's a string, you can do something like self.filter(order__isnull=bool == 'True')

Related

overredieg jinja2 for customized view on django templates

hi I wanna overriding html.py in venv/Lib/coreschema/encodings/html.py.
this is a method to need overriding:
def determine_html_template(schema):
if isinstance(schema, Array):
if schema.unique_items and isinstance(schema.items, Enum):
# Actually only for *unordered* input
return '/bootstrap3/inputs/select_multiple.html'
# TODO: Comma seperated inputs
return 'bootstrap3/inputs/textarea.html'
elif isinstance(schema, Object):
# TODO: Fieldsets
return 'bootstrap3/inputs/textarea.html'
elif isinstance(schema, Number):
return 'bootstrap3/inputs/input.html'
elif isinstance(schema, Boolean):
# TODO: nullable boolean
return 'bootstrap3/inputs/checkbox.html'
elif isinstance(schema, Enum):
# TODO: display values
return 'bootstrap3/inputs/select.html'
# String:
if schema.format == 'textarea':
return 'bootstrap3/inputs/textarea.html'
return 'bootstrap3/inputs/input.html'
and this lines :
if isinstance(schema, Array):
if schema.unique_items and isinstance(schema.items, Enum):
# Actually only for *unordered* input
return '/bootstrap3/inputs/select_multiple.html'
I want to modify select_multiple.html to custom_select_multiple.html in templates folder in my project directory.
also this solution need to overriding some files and I do that.
now its cant understand my custom file because in this method:
env = jinja2.Environment(loader=jinja2.PackageLoader('coreschema', 'templates'))
def render_to_form(schema):
template = env.get_template('form.html')
return template.render({
'parent': schema,
'determine_html_template': determine_html_template,
'get_textarea_value': get_textarea_value,
'get_attrs': get_attrs
})
used PackageLoader and jinja2 cant understand where is my file.
and now how can I resolve this problem.
actually I trying to resolve this with set custom urls but this not working. actually I dont know
what I do.

Look up items in list of dataclasses by value

I'm using python to filter data in elasticsearch based on request params provided. I've got a working example, but know it can be improved and am trying to think of a better way. The current code is like this:
#dataclass(frozen=True)
class Filter:
param: str
custom_es_field: Optional[str] = None
is_bool_query: bool = False
is_date_query: bool = False
is_range_query: bool = False
def es_field(self) -> str:
if self.custom_es_field:
field = self.custom_es_field
elif "." in self.param:
field = self.param.replace(".", "__")
else:
field = self.param
return field
filters = [
Filter(param="publication_year", is_range_query=True),
Filter(param="publication_date", is_date_query=True),
Filter(param="venue.issn").
...
]
def filter_records(filter_params, s):
for filter in filters:
# range query
if filter.param in filter_params and filter.is_range_query:
param = filter_params[filter.param]
if "<" in param:
param = param[1:]
validate_range_param(filter, param)
kwargs = {filter.es_field(): {"lte": int(param)}}
s = s.filter("range", **kwargs)
elif filter.param in filter_params and filter.is_bool_query:
....
The thing I think is slow is I am looping through all of the filters in order to use the one that came in as a request variable. I'm tempted to convert this to a dictionary so I can do filter["publication_year"], but I like having the extra methods available via the dataclass. Would love to hear any thoughts.

it always gives false ,i used this hasGroup function in other apps in all the apps this function returns false

from django.contrib.auth.models import Group
def hasGroup(user,groupName):
group = Group.objects.filter(name=groupName)
return True if group in user.groups.all() else False
Do it this way:
def hasGroup(user, groupName):
return user.groups.filter(name=groupName).exists()
will save you a query, and will work as you expected.

Django queryset interpolation for a previous / next instance function

Writing a dry function that returns either previous or next instances of a given instance.
This function return previous instances:
def previous(instance):
try:
return Picture.objects.filter(id__lt=instance.id).first()
except Picture.DoesNotExist:
return instance
I want to create an abstracted function which returns either the previous or the next instance using an additional gt_or_lt argument. The problem lies in interpolating that argument into the filter(id__gt_or_lt).
def seek_instance(gt_or_lt, instance):
try:
return Picture.objects.filter(id__gt_or_lt=instance.id).first()
except Picture.DoesNotExist:
return instance
I've tried:
return Picture.objects.filter(id__gt_or_lt = instance.id).first()
seek_instance("gt", instance)
return Picture.objects.filter(id__f"{gt_or_lt}" = instance.id).first()
seek_instance("gt", instance)
return Picture.objects.filter(f"{gt_or_lt}" = instance.id).first()
return Picture.objects.filter(gt_or_lt = instance.id).first()
seek("id__gt", instance)
All fail with their respective errors.
Use a dictionary with kwargs expansion.
return Picture.objects.filter(**{f"id__{gt_or_lt}": instance.id})
You can use dictionary expansion, like #DanielRoseman suggests. But that will still not per se render the previous, or next item. If for example the model has an ordering option [Django-doc], then it is possible that the order is different than on the id. Furthermore, for the previous one, you will need to reverse the ordering.
Furthermore depending on the situation, you might want to prevent that seek_instance can be given a different lookup, like 'in' for example.
We can thus use an if … elif … else here to branch on the item we wish to retrieve, and raise a ValueError in case you use some other lookup:
def seek_instance(lt_or_gt, instance):
try:
if lt_or_gt == 'lt':
return Picture.objects.filter(pk__lt=instance.pk).order_by('-pk').first()
elif lt_or_gt == 'gt':
return Picture.objects.filter(pk__gt=instance.pk).order_by('pk').first()
else:
raise ValueError("Should be 'lt' or 'gt'")
except Picture.DoesNotExist:
return instance

Python return function error

While running this function to validate captcha key and value i am not able to return
it show error like this
"AttributeError: 'bool' object has no attribute 'status_code'"
def validate(request):
id=request.GET.get('id','')
key=request.GET.get('key','')
captchavalue = mc.get(str(id))
if captchavalue == key:
return True
else:
return False
By reading the code and the error, I assume that validate is a view. A view must always return a HttpResponse. So if you want to return a response indicating a boolean value, indicating if captchavalue == key, do:
from django.http import HttpResponse
def validate(request):
id=request.GET.get('id','')
key=request.GET.get('key','')
captchavalue = mc.get(str(id))
return HttpResponse(captchavalue == key)
I'm not 100% sure about the import line, but it's something very similar.
I don't know much Django, but it seems it expects you to return a response object instead of a bool value (True / False).
Maybe your code should like more like this:
if captchvalue == key:
return HttpResponse('HTML Page saying OK')
else:
return HttpResponse('HTML Page saying Error')

Categories