Value not getting saved in django model - python

I have made two models which are as follows:
class itemsSearched(models.Model):
searched_items = models.CharField(max_length=120)
def __str__(self):
return self.searched_items
class VisitorInfo(models.Model):
user_id = models.CharField(max_length=120)
items_searched = models.ManyToManyField(itemsSearched,blank=True)
I want to save value tshirt in visitorInfo model. Here is the view for this
def get_req(request):
event = request.GET['e']
if event == 'pv':
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[-1].strip()
else:
ip = request.META.get('REMOTE_ADDR')
check_user(request,ip)
elif event == 'pp':
visitor = VisitorInfo.objects.get(user_id=request.GET['duid'])
visitor.active = True
print(visitor.active)
visitor.save()
elif event == 'ue':
u_id = request.GET['duid']
tz = request.GET['tz']
url = request.GET['url']
link = request.GET['ue_pr'] #ue_pr is the property of unstructured event of the type json.
o = json.loads(link)
print(o)
if(o['data']['data']['elementId']=='nf-field-1'):
name = o['data']['data']['value']
print("Name: "+ name)
visitor= VisitorInfo.objects.get(user_id=u_id)
visitor.name = name
visitor.save()
elif(o['data']['data']['elementId']=='s'):
searched_item = int(o['data']['data']['value'])
print("Searched: "+ searched_item) #6
print("Type of searched_item " + type(searched_item)) #7
visitor= VisitorInfo.objects.get(user_id=u_id)
visitor.items_searched.add(searched_item)
visitor.save()
For the sake of clarity I printed 'o' which is a python dictionary parsed from json.Here is the what i have got
{'schema': 'iglu:com.snowplowanalytics.snowplow/unstruct_event/jsonschema/1-0-0', 'data': {'schema': 'iglu:com.snowplowanalytics.snowplow/change_form/jsonschema/1-0-0', 'data': {'formId': 'FORM', 'elementId': 's', 'nodeName': 'INPUT', 'type': 'search', 'elementClasses': ['search-field'], 'value': 'tshirt'}}}
I want to save the value 'tshirt' in visitor info but i am getting the following error.
Traceback (most recent call last):
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site- packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/channels/handler.py", line 243, in process_exception_by_middleware
return super(AsgiHandler, self).process_exception_by_middleware(exception, request)
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ubuntu/awsupload/dashboard/views.py", line 411, in get_req
visitor.items_searched.add(searched)
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 934, in add
self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1083, in _add_items
'%s__in' % target_field_name: new_ids,
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/query.py", line 784, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/query.py", line 802, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1261, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1287, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1217, in build_filter
condition = lookup_class(lhs, value)
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/lookups.py", line 24, in __init__
self.rhs = self.get_prep_lookup()
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 56, in get_prep_lookup
self.rhs = [target_field.get_prep_value(v) for v in self.rhs]
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 56, in <listcomp>
self.rhs = [target_field.get_prep_value(v) for v in self.rhs]
File "/home/ubuntu/awsupload/myvenv/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 966, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'tshirt'
Output of print statement at #6 is as below
Searched: tshirt
Output of print statement at #7 is as below
<class 'str'>

Like the error says, you can't add a string to a many-to-many field. You need to an object of the related model.
I haven't quite understood what you're trying to do, but I suspect you want to get or create an ItemSearched model for "t-shirt", and then add that.
item, _ = itemsSearched.objects.get_or_create(searched_items=searched_item)
visitor = VisitorInfo.objects.get(user_id=u_id)
visitor.items_searched.add(item)
Note, you don't need to save visitor after only modifying its m2m field.

Related

How to iterate through queryset and get value Django

I wanna do a simple recommendation system based on users' Animals that they added. I want to show only products of a category, that's been mapped in "zwierzeta" dictionary. So basically if user has chosen that he has a horse (which is id 1, i want to show only products that have category 4) Also if user has more than 1 animals, i want to show them randomly from list of categories id. The logic seems to be fine, im just new at django and i have no idea how to actually iterate through the querysets and how to get a value(animal) from a particular queryset. The get method doesnt work. Do you have any idea how to get a particular value from a queryset?
class MyAnimal(models.Model):
name = models.CharField(max_length=256)
animal = models.ForeignKey(Animal, on_delete=models.CASCADE, null=False)
class ProductInStore(models.Model):
product = models.ForeignKey('Product', on_delete=models.CASCADE)
class Product(models.Model):
product_category = models.ManyToManyField(EcommerceProductCategory)
def list(self, request):
ProductCategoryAnimal.objects
qs = MyAnimal.objects.filter(user=self.request.user)
if qs:
for q in qs:
categories = []
get_category = ProductCategoryAnimal.objects.values_list('category_id', flat=True).get(animal_id=q.animal_id)
categories.append(get_category)
print(categories)
result = ProductInStore.objects.filter(
product__product_category__id=random.choice(categories)
)
else:
result = ProductInStore.objects.all()[:1]
return result.order_by('?')[:1]
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/rest_framework/generics.py", line 199, in get
return self.list(request, *args, **kwargs)
File "/Users/jakubstrawa/programming/DeorPythonek/api/ecommerce/views.py", line 180, in list
product__category_id=random.choice(categories)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 962, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 969, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1358, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1380, in _add_q
split_subq=split_subq, check_filterable=check_filterable,
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1319, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1156, in build_lookup
raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name))
django.core.exceptions.FieldError: Related Field got invalid lookup: category_id
You can simplify this to:
def list(self, request):
zwierzeta = {1 : 4, 6: 5, 8: 6, 9: 6, 4: 3}
qs = MyAnimal.objects.filter(user=self.request.user)
if qs:
category=random.choice([zwierzeta[q.animal_id] for q in qs])
result = ProductInStore.objects.filter(
product__product_category__id=category
)
else:
result = ProductInStore.objects.all()
return result.order_by('?')[:1]
But using a dictionary with hardcoded items looks odd: it means you need to know the primary keys in advance and it is hard to later add new categories since it requires deploying a new software version. It might be better to model the relation between a category and an animal as a ManyToManyField or equivalent.

Django Q Filter - Too many Values to unpack

I want to dynamicly create some filter criteria depending on the url query params.
For this I created a nested Django Q-Object which looks like:
query = <Q: (AND: (OR: region=30, region=39), name__endswith=Hannover, zip_code=30165)>
Now I want to pass this Q object to Model-Filter
Eort.objects.filter(query)
Thereby I get a ValueError : too many values to unpack (expected 2)
Traceback (most recent call last):
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\views\generic\base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\felix\Documents\WZO\WZO\WZO_App\views.py", line 47, in get
log.debug(Eort.objects.filter(eq))
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\sql\query.py", line 1380, in _add_q
split_subq=split_subq, check_filterable=check_filterable,
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\sql\query.py", line 1244, in build_filter
check_filterable=check_filterable,
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\sql\query.py", line 1380, in _add_q
split_subq=split_subq, check_filterable=check_filterable,
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\sql\query.py", line 1244, in build_filter
check_filterable=check_filterable,
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\sql\query.py", line 1380, in _add_q
split_subq=split_subq, check_filterable=check_filterable,
File "C:\Users\felix\Documents\WZO\myenv\lib\site-packages\django\db\models\sql\query.py", line 1255, in build_filter
arg, value = filter_expr
Does anybody know how to solve this problem?
This is how I created the Q-Object:
def or_operator(self, key, qlist):
if qlist:
result = Q()
result.connector = Q.OR
for i in qlist:
if i == '':
continue
if i[0] == '%' and i[-1] == '%':
result.add(Q('{0}__{1}={2}'.format(key, 'contains', i[1:-1])), Q.OR)
elif i[0] == '%' and not i[-1] == '%':
result.add(Q('{0}__{1}={2}'.format(key, 'startswith', i[1:])), Q.OR)
elif not i[0] == '%' and i[-1] == '%':
result.add(Q('{0}__{1}={2}'.format(key, 'endswith', i[:-1])), Q.OR)
else:
result.add(Q('{0}={1}'.format(key, i)), Q.OR)
return result
query = Q()
query.connector = Q.AND
for key in params:
if key in ['lat', 'lng', 'name', 'street', 'zip_code', 'city', 'region']:
val = params.get(key, None).split(',')
query.add(self.or_operator(key, val),Q.AND)
You should not work with ={2}. A Q object is not a string of the form foo=bar, it is in essence a 2-tuple with as first element a string that is the "key" which is the field and optionally some lookups, and as second element a value, but that value can be a string, datetime object, etc. You thus construct the Q object with:
if i[0] == '%' and i[-1] == '%':
result.add(Q((f'{key}__contains', i[1:-1])), Q.OR)
elif i[0] == '%' and not i[-1] == '%':
result.add(Q((f'{key}__startswith', i[1:])), Q.OR)
elif not i[0] == '%' and i[-1] == '%':
result.add(Q((f'{key}__endswith', i[:-1])), Q.OR)
else:
result.add(Q((key, i)), Q.OR)

Date filters fail in django

I have a function:
def update_coins_table():
# Check if the currency has been updated in the last hour
up_to_date_currency = Currency.objects.filter(
currency_value_in_dollars_date=
[datetime.now(), timedelta(hours=1)]).order_by('-currency_value_in_dollars_date')[:len(coins_ids)]
if up_to_date_currency.exists():
# Return if it is
return
if not do_greeting():
print("Gecko crypto board not reachable. Db setup")
return
crypto_coins_prices = cg.get_price(ids=coins_ids_str, vs_currencies='usd')
datetime_now = datetime.now()
for coin_key in crypto_coins_prices:
coin = Currency(
currency_name=coin_key,
currency_value_in_dollars=crypto_coins_prices[coin_key]['usd'],
currency_value_in_dollars_date=datetime_now)
coin.save()
and get the following error on executing filter(),
up_to_date_currency = Currency.objects.filter(
currency_value_in_dollars_date=
[datetime.now(), timedelta(hours=1)]).order_by('-currency_value_in_dollars_date')[:len(coins_ids)]
Error message:
Internal Server Error: /get_currency/
Traceback (most recent call last):
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\projects\crypto-currency-board\crypto\manage_crypto_currency\views.py", line 21, in get_latest_currency
update_coins_table()
File "C:\projects\crypto-currency-board\crypto\manage_crypto_currency\get_coins_scheduler.py", line 38, in update_coins_table
up_to_date_currency = Currency.objects.filter(
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 942, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, *args, **kwargs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q
child_clause, needed_inner = self.build_filter(
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1319, in build_filter
condition = self.build_lookup(lookups, col, value)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\sql\query.py", line 1165, in build_lookup
lookup = lookup_class(lhs, rhs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\lookups.py", line 24, in __init__
self.rhs = self.get_prep_lookup()
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\lookups.py", line 76, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1357, in get_prep_value
value = super().get_prep_value(value)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1217, in get_prep_value
return self.to_python(value)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1318, in to_python
parsed = parse_datetime(value)
File "C:\projects\crypto-currency-board\venv\lib\site-packages\django\utils\dateparse.py", line 107, in parse_datetime
match = datetime_re.match(value)
TypeError: expected string or bytes-like object
[22/Nov/2020 20:27:44] "GET /get_currency/ HTTP/1.1" 500 142548
The model of 'Currency' is:
class Currency(models.Model):
currency_name = models.CharField(max_length=100)
currency_value_in_dollars = models.FloatField()
currency_value_in_dollars_date = models.DateTimeField()
def __str__(self):
return self.currency_name
Why can't I filter by 'currency_value_in_dollars_date'? check if the currency value has been updated within the last hour.
You can not simply uses a list of two values to filter. If you for example want to retrieve all elements in between you can work with a __range lookup [Django-doc]:
from django.utils.timezone import now
current_time = now()
up_to_date_currency = Currency.objects.filter(
currency_value_in_dollars_date__range=(
current_time-timedelta(hours=1),
current_time
)
).order_by('-currency_value_in_dollars_date')[:len(coins_ids)]
This will thus retrieve all Currency objects between an hour ago and now.
If by
check if the currency value has been updated within the last hour
you mean you want to filter all rows up to 1 hour ago, then replace
currency_value_in_dollars_date=
[datetime.now(), timedelta(hours=1)]
with (notice __gte)
currency_value_in_dollars_date__gte=datetime.now() - timedelta(hours=1)
If you want to filter by array, then you'd have to either use JSONField to match value, or use __in to execute SQL in. Otherwise, you can't filter by array, so what you did is basically invalid.
Depending on your settings, you should probably use timezone.now() from django instead of datetime.

How to fix: 'TypeError: expected string or bytes-like object' when doing unit test on a views.py function

I'm writing a test for a function that returns a JSONResponse. The function works fine on the website but the test always raises a TypeError. It looks like the program fails to get an entry from the database and returns an error instead.
views.py:
def check_availability(request, id):
if request.method == "GET":
response_data = {}
event_date = request.GET.get('event_date', False)
check = None
try:
try:
speaker = Pembicara.objects.get(id = id)
filtered = Booking.objects.filter(speaker = speaker)
check = filtered.get(event_date = event_date)
except ObjectDoesNotExist as e:
pass
except Exception as e:
raise e
if not check:
response_data['available'] = 'ok'
else:
response_data['available'] = 'no'
except Exception as e:
raise e
return JsonResponse(response_data)
tests.py:
def test_date_availability_is_checked(self):
p = self.createPembicara()
c = Client()
date = datetime.date.today()
# request = c.get('/profile/1/check_availability/', event_date=date)
b = self.createBooking()
request = c.get('/profile/1/check_availability/', event_date='1999-12-20')
self.assertEqual(request.status_code, 200)
self.assertJSONEqual(request.content, {'available': 'ok'})
terminal:
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
./Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/whitenoise/base.py:116: UserWarning: No directory at: /Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/BookaSpeakers/static/
warnings.warn(u"No directory at: {}".format(root))
E.......
======================================================================
ERROR: test_date_availability_is_checked (speaker_profile.tests.ProfileTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/speaker_profile/tests.py", line 69, in test_date_availability_is_checked
request = c.get('/profile/1/check_availability/', event_date='2000-12-20')
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", line 535, in get
response = super().get(path, data=data, secure=secure, **extra)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", line 347, in get
**extra,
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", line 422, in generic
return self.request(**r)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/test/client.py", line 503, in request
raise exc_value
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/speaker_profile/views.py", line 53, in check_availability
raise e
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/speaker_profile/views.py", line 47, in check_availability
raise e
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/speaker_profile/views.py", line 43, in check_availability
check = filtered.get(event_date = event_date)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get
clone = self.filter(*args, **kwargs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/query.py", line 892, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1290, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1318, in _add_q
split_subq=split_subq, simple_col=simple_col,
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1251, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1116, in build_lookup
lookup = lookup_class(lhs, rhs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/lookups.py", line 20, in __init__
self.rhs = self.get_prep_lookup()
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/lookups.py", line 70, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1270, in get_prep_value
return self.to_python(value)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1232, in to_python
parsed = parse_date(value)
File "/Users/nethaniasonya/Documents/KULIAH/SEMESTER 3/ppw/bookaspeakers/env/lib/python3.7/site-packages/django/utils/dateparse.py", line 74, in parse_date
match = date_re.match(value)
TypeError: expected string or bytes-like object
----------------------------------------------------------------------
Ran 9 tests in 0.211s
FAILED (errors=1)
Destroying test database for alias 'default'...
Any help would be appreciated, thank you!
The error likely happens because event_date ends up with the value False, which happens because there was no value for 'event_date' in request.GET.
According to the docs of Client.get(), you have to pass a dict with the GET/POST parameters of the request, not using kwargs.
Try by changing this line (which is using kwargs):
request = c.get('/profile/1/check_availability/', event_date='1999-12-20')
to this (now using a dict as the second parameter)
request = c.get('/profile/1/check_availability/', {'event_date': '1999-12-20'})

How to get user object by email filtering in Django

I am trying to get a specific user in Django via email filtering using default user model. I am doing the following in my views.py but it is not working:
def shareCode(request):
if request.method=="POST":
email = request.POST.get("mail")
print(email)
id = int(request.POST.get('id'))
user = User.objects.get(email = email)
obj = Code.objects.get(pk=id,user = user.id)
res = {"shared":"fasle"}
obj2 = Code(name=obj.name,code=obj.code,shared=True)
obj2.save()
res = {
"shared":True
}
return HttpResponse(json.dumps(res))
models.py
class Code(models.Model):
name = models.CharField(max_length=255)
code = models.TextField()
user = models.ForeignKey(User,on_delete=models.CASCADE)
shared = models.BooleanField(default=False)
but its getting be following error
Internal Server Error: /editor/share
Traceback (most recent call last):
File "D:\stocksapp\winenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "D:\stocksapp\winenv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "D:\stocksapp\winenv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\stocksapp\main\views.py", line 138, in shareCode
obj = Code.objects.get(id=id,user = user)
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\query.py", line 390, in get
clone = self.filter(*args, **kwargs)
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\query.py", line 844, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\query.py", line 862, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\sql\query.py", line 1263, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\sql\query.py", line 1287, in _add_q
split_subq=split_subq,
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\sql\query.py", line 1225, in build_filter
condition = self.build_lookup(lookups, col, value)
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\sql\query.py", line 1096, in build_lookup
lookup = lookup_class(lhs, rhs)
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\lookups.py", line 20, in __init__
self.rhs = self.get_prep_lookup()
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\lookups.py", line 70, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "D:\stocksapp\winenv\lib\site-packages\django\db\models\fields\__init__.py", line 965, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'code'
Any help will be appreciated
You can retrieve an object from models using exact match.
e.g:
user = User.objects.get(email__exact='usermail#example.com')
This would generate SQL that looks like this:
SELECT ... WHERE email = 'usermail#example.com';

Categories