Passing multiple arguments from django template href link to view - python

I am trying to pass some arguments with a link url href in a template to a view.
In my template :
Print
So i am trying to pass 4 arguments to my view.
My view is :
def print_permission_document(request, studentname, studentsurname, studentclass, doctype):
file_write(studentname.encode('utf-8')+" "+studentsurname.encode('utf-8')+" "+studentclass+" "+doctype)
return response
My urls.py is :
url(r'^print-permission-document/.+$', print_permission_document, name='print-permission-document')
But i get below error :
Exception Type: TypeError
Exception Value:
print_permission_document() takes exactly 5 arguments (1 given)

This is not how you specify multiple parameters in a URL, typically you write these in the URL, like:
url(
r'^print-permission-document/(?P<studentname>\w+)/(?P<studentsurname>\w+)/(?P<studentclass>\w+)/(?P<doctype>[\w-]+)/$',
print_permission_document, name='print-permission-document'
)
Then you generate the corresponding URL with:
Print
This will then generate a URL that looks like:
/print-permission-document/somename/someclass/doctype-studentlatepermission
Typically a path does not contain key-value pairs, and if it does, you will need to "decode" these yourself.
You can also generate a querystring (after the question mark), these you can then access in request.GET [Django-doc].

You are passing your URL wrongly. and URL in template is also declared wrongly.
Try this
Print
url(
r'^print-permission-document/(?P<studentname>\w+)/(?P<studentsurname>\w+)/(?P<studentclass>\w+)/(?P<doctype>\w+)/$',
print_permission_document, name='print-permission-document'
)

I had the same error , i corrected it by :
url(r'^auth_app/remove_user/(?P<username2>[-\w]+)/$', views.remove_user, name="remove_user"),
Use this pattern for passing string
(?P<username2>[-\w]+)
This for interger value
(?P<user_id>[0-9]+)

Related

Making URL to accept parameters as optional. Non Capturing

I want to make my url to accept the optional parameters only when given. I am unable to make the parameters optional/non-capturing.
re_path(r'^users/(?:(?P<sort_by>\d+)/)?$', views.UserListView.as_view(), name='user_list'),
I want this url to accept a slug field only when provided to the view. How can I do this?
It is showing an error
Reverse for 'user_list' with keyword arguments '{'sort_by': 'username'}' not found. 1 pattern(s) tried: ['admin/users/(?:(?P<sort_by>\\d+)/)?$']
when I passed sort_by='username'
You could keep your url to:
re_path(r'^users/$', views.UserListView.as_view(), name='user_list'),
And then in your template use
Sort
I would create 2 URLs:
path('users/<str:sort_by>', views.UserListView.as_view(), name='user_list_by_user'),
path('users', views.UserListView.as_view(), {'sort_by': 'default_sort_you_use'}, name='user_list'),
Then you can call the appropriate URL and always have a sort_by value in the view.

Django handle optional url parameter

I want url to have optional url parameter. Primary url is:
url(r'^(?P<letnik_id>[1-4])/(?P<classes_id>[A-G])/(?P<subject_id>[\w\-]+)$', views.subject, name="subject_id"),
but after subject id i want to be able to add optional parameter that is always a number:
url(r'^(?P<letnik_id>[1-4])/(?P<classes_id>[A-G])/(?P<subject_id>[\w\-]+)/(?P<digit>\d+)/$'', views.subject, name="subject_id_optional"),
Im not even sure if did that correctly, as i dont know how to set number for parameter. So after the parameter is passed i want the (template?) or maybe view to read the number (which is model's ID number) and add css class ) .highlited-model {background-color: red;} to that model.
How would i achieve this and how should i handle it in views or template, wherever it makes more sense?
I think you can just have two urls pointing to the same view, one with your optional parameter, and one without:
urls = [
url(r'^(?P<letnik_id>[1-4])/(?P<classes_id>[A-G])/(?P<subject_id>[\w\-]+)/(?P<digit>\d+)/$', views.subject, name="subject_id_optional"),
url(r'^(?P<letnik_id>[1-4])/(?P<classes_id>[A-G])/(?P<subject_id>[\w\-]+)$', views.subject, name="subject_id"),
]
def subject(request, optional_parameter=''):
return render(
request,
"template.html",
{
"optional_parameter": optional_parameter
}
)
Then you can get the parameter in your template as you would any other variable passed into the context.

Django cannot retrieve url parameter

I'm trying to retrieve a url parameter as part of a simple query within Django but calling kwargs from within the view.py seems to return an empty value (e.g. self.kwargs[name] returns a blank/empty value), it seems Im not picking up the 'name' parameter from the url?
Im pretty new to Django so expect I'm doing something dumb?
I'm using the following url:
myIpAddress:8000/contacts/search_name/?name=gordon
my code:
URL pattern - works fine.
urlpatterns = [
url(r'^contacts/$', ContactList.as_view()),
url(r'^contacts/search_name/(?P<name>\w{0,50})$', ContactDetail.as_view()),
]
view:
class ContactDetail(generics.ListAPIView):
serializer_class = ContactSerializer
def get_queryset(self):
return Contact.objects.filter(name=self.kwargs['name'])
Not sure if it's the best way but I managed to grab the URL parameter using:
self.request.GET.get('name')
This returns the parameter supplied within the url.

How do I pass parameters via url in django?

I am trying to pass a parameter to my view, but I keep getting this error:
NoReverseMatch at /pay/how
Reverse for 'pay_summary' with arguments '(False,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['pay/summary/$']
/pay/how is the current view that I'm at. (that is the current template that that view is returning).
urls.py
url(r'^pay/summary/$', views.pay_summary, name='pay_summary')
views.py
def pay_summary(req, option):
if option:
#do something
else:
#do something else
....
template
my link
EDIT
I want the view should accept a POST request, not GET.
To add to the accepted answer, in Django 2.0 the url syntax has changed:
path('<int:key_id>/', views.myview, name='myname')
Or with regular expressions:
re_path(r'^(?P<key_id>[0-9])/$', views.myview, name='myname')
You need to define a variable on the url. For example:
url(r'^pay/summary/(?P<value>\d+)/$', views.pay_summary, name='pay_summary')),
In this case you would be able to call pay/summary/0
It could be a string true/false by replacing \d+ to \s+, but you would need to interpret the string, which is not the best.
You can then use:
my link

Django Rest Framework for function based views

I'm having trouble getting the JSON for function based views in django. I have the below code. I basically would like the function to return either json or an html page based on the user request.
#api_view(['GET'])
#renderer_classes((JSONRenderer,TemplateHTMLRenderer,BrowsableAPIRenderer))
def meld_live_orders(request):
if request.method =='GET':
current_orders = Meld_Sales.objects.values_list('TicketNo',flat=True).distinct()
prev_orders = Meld_Order.objects.values_list('TicketNo',flat =True).distinct()
live_orders = live_order_generator(current_orders,prev_orders)
return render(request,'live_orders.html',{'live_orders':live_orders})
When i go to the url - http://localhost:8000/live-orders.json
I'm getting an error which states the below -meld_live_orders() got an unexpected keyword argument 'format'
Is this because i need to include the serializer class somewhere the same way in CBVs? Doesnt the #API_VIEW serialize the response?
i tried including format = '' in the function argument. but the problem is that it still renders html when i want it to render json.
You need to make some changes to your code.
Firstly, you need to use format_suffix_patterns in your urls if you have not defined it. This will allow us to use filename extensions on URLs thereby providing an endpoint for a given media type.
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
...
]
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html']) # allow us to use '.json' and '.html' at the end of the url
Secondly. your view does not have a format parameter in the definition.
When using format_suffix_patterns, you must make sure to add the
'format' keyword argument to the corresponding views.
#api_view(['GET'])
#renderer_classes((JSONRenderer,TemplateHTMLRenderer,BrowsableAPIRenderer))
def meld_live_orders(request, format=None): # add a 'format' parameter
...
Thirdly, you need to return a DRF response and not a Django response which you are returning at the end of the view.
You must have match a format parameter in the url pattern, but in the view function there is not an argument named format. Change the view definition into:
def meld_live_orders(request, format = ""):

Categories

Resources