NoReverseMatch while trying to match dates with regular expression in url - django

In my URL I expect to get 2 dates as input:
url(r'^export/range/csv/(?P<start_date>\d+)/(?P<end_date>\d+)/$', views.export_payment_range_csv, name="export_payment_range_csv"),
But I am getting error :
NoReverseMatch at /payment/list/range/ Reverse for
'export_payment_range_csv' with arguments '()' and keyword arguments
'{u'start_date': datetime.date(2016, 2, 1), u'end_date':
datetime.date(2016, 12, 31)}' not found. 2 pattern(s) tried:
['condition/export/range/csv/(?P\d+)/(?P\d+)/$',
'payment/export/range/csv/(?P\d+)/(?P\d+)/$']
I assume this has to do with regular expression in my URL file.
what I am doing wrong?
UPDATE:
URL I access
<li>CSV for current range payments
When start date and end date I got during template rendering from the view.
I expect dates on the view side
payment_list = LeasePaymentFilter(request.GET, queryset=LeasePayment.objects.filter(payment_date__range=[start_date, end_date]))

Your url parameters expects digits (\d+), for example:
reverse("export_payment_range_csv", kwargs={
'start_date': '123',
'end_date': '456',
})
but you pass datetime.date instances:
reverse("export_payment_range_csv", kwargs={
'start_date': d1,
'end_date': d2,
})
check the view itself (the function views.export_payment_range_csv()) and see what format is expected for the parameters, and generate the needed string, for example:
def format_my_date(d):
return d.strftime("%Y%m%d")
reverse("export_payment_range_csv", kwargs={
'start_date': format_my_date(d1),
'end_date': format_my_date(d2),
})

Related

regular expression to analyze site link

I tried to create a regex string to analyze link
site- www.example.com/page.php?u=userid&action=add&date=yyyy-MM-dd
I want to create named groups as:
site: includes the full requested link
user: includes value of u parameter
action: includes value of action parameter
by taking example above the result will be:
site: www.example.com/page.php?u=userid&action=add&date=yyyy-MM-dd
user: userid
action: add
This regex gives you named captures of site, user and action,
(?=(?<site>www.*$))(?=.*u=(?<user>(?:[^&]*)))(?=.*action=(?<action>(?:[^&]*)))
Play here,
https://regex101.com/r/1VAgSO/1
Python 3
In[2]: from urllib.parse import parse_qs, urlparse
In[3]: url = 'www.example.com/page.php?u=userid&action=add&date=yyyy-MM-dd'
In[4]: parsed_url = urlparse(url)
In[5]: parsed_url
Out[5]: ParseResult(scheme='', netloc='', path='www.example.com/page.php', params='', query='u=userid&action=add&date=yyyy-MM-dd', fragment='')
In[6]: parsed_query = parse_qs(parsed_url.query)
In[7]: parsed_query
Out[7]: {'u': ['userid'], 'action': ['add'], 'date': ['yyyy-MM-dd']}
In[8]: {'site': url, 'user': parsed_query['u'], 'action': parsed_query['action']}
Out[8]:
{'site': 'www.example.com/page.php?u=userid&action=add&date=yyyy-MM-dd',
'user': ['userid'],
'action': ['add']}
https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlparse
https://docs.python.org/3/library/urllib.parse.html#urllib.parse.parse_qs

Django query annotate and agregate

How can I write a query like this in Django?
select sum(kolvo), reason
from(
select count(reason) kolvo, reason
from contacts group by reason) group by reason
Your query looks semantically equivalent to:
SELECT count(reason) AS kolvo,
reason
FROM contacts
GROUP BY reason
So without the outer query.
You can make such query in Django's ORM with:
Contacts.objects.values('reason').annotate(
kolvo=Count('id')
).order_by('reason')
This will then return a QuerySet that wraps dictionaries, like:
< QuerySet [
{ 'reason': 'some reason', 'kolvo': 13 },
{ 'reason': 'some other reason', 'kolvo': 2 },
] >

Django filter update specific field based on ajax return

I have a ajax post that returns the following data:
{u'related_id': u'9', u'db_name': u'my_field', u'name': u'jsaving_draft', u'value': u'hypothesis sadfasdfadfws asdfasdf'}
In my view I have:
if request.is_ajax():
if "jsaving_draft" in request.body:
results = json.loads(request.body)
print results
save_id = results['related_id']
save_db = results['db_name']
save_value = results['value']
temp = Dbtable.objects.filter(id=save_id).update(save_db=save_value)
How can I specify the specific table element to update based on save_db without hardcoding the database row name. I have a table in my database named.
I tried doing something like like:
Dbtable.objects.filter(id=save_id).update("%s"=save_value) % save_db
but that failed spectacularly. Does anyone have an idea of how I can make this work?
You can use keyword argument unpacking:
Dbtable.objects.filter(id=save_id).update(**{save_db: save_value})
Example:
>>> def test(a,b):
... return a + b
...
>>> test(**{'a': 1, 'b': 2})
3

NoReverseMatch: with arguments '()' and keyword arguments

I am using Django 1.5 and trying to pass args to my URL. When I use the first two args then the below code works fine, with the third args I am getting an error. I have already referred to the new Django 1.5 update for url usage and accordingly used quotes for the URL name.
NoReverseMatch: Reverse for 'add_trip' with arguments '()' and keyword arguments '{u'city': 537, u'score': 537, u'time': 35703, u'distance': 1196.61}' not found
urls.py
url(
r'^add/(?P<city>\w+)/(?P<score>\w+)/(?P<distance>\w+)/(?P<time>\w+)$',
'trips.views.add_trip',
name='add_trip'
),
html file
Add/delete
If I use only two args (i.e city and score, then it works fine) else I get the no reverse match error.
views.py
def SearchTrips(request):
city = request.POST['city'].replace(" ","%20")
location = request.POST['location'].replace(" ","%20")
duration = request.POST['duration']
#url = "http://blankket-mk8te7kbzv.elasticbeanstalk.com/getroutes?city=%s&location=%s&duration=%s" % (city, location, duration)
url= "http://blankket-mk8te7kbzv.elasticbeanstalk.com/getroutes?city=New%20York%20City&location=Park%20Avenue&duration=10"
print url
try:
resp = urllib2.urlopen(url)
except:
resp = None
if resp:
datas = json.load(resp)
else:
datas = None
return render(request, 'searchtrips.html', {'datas': datas})
The distance value 1196.61 does not match the regex because of the decimal point.
You can use
(?P<distance>[\w\.]+)
which matches uppercase A-Z, lowercase a-z, digits 0-9, hyphens and decimal points.
Alternatively, you could use
(?P<distance>[\d\.]+)
Which only matches digits 0-9 and decimal points.

making separate array from existing json django

I have this array of JSON:
[{'pk': 4L, 'model': u'logic.member', 'fields': {'profile': 3L, 'name': u'1', 'title': u'Mr', 'dob': datetime.date(1983, 1, 1), 'lastname': u'jkjk', 'redressno': u'jdsfsfkj', 'gender': u'm'}}, {'pk': 5L, 'model': u'logic.member', 'fields': {'profile': 3L, 'name': u'2', 'title': u'Mr', 'dob': datetime.date(1983, 1, 1), 'lastname': u'jkjk', 'redressno': u'jdsfsfkj', 'gender': u'm'}}]
I want to make separate array of JSON for only fields property.
What I tried is:
memarr=[]
for index,a in data1:
print index
print a
memarr[index]=a[index].fields
And it is giving an error of:
too many values to unpack
Please correct.
First of all, data1 is a list, so you can't unpack it into 2 variables.
If you want the index, you have to use something like enumerate.
Second, you can't assign to a list via indexing if the key doesn't exist. You have to append or use another valid list insert method.
Third, a[index].fields doesn't really make sense - there is no key in a that would be associated with an integer index and fields is not an attribute.
You're probably looking for something like this:
memarr = []
for index, a in enumerate(data1):
memarr.append(a['fields'])
So many things wrong with that snippet...
Anyway:
memarr = [a['fields'] for a in data]