47👍
You can only send data to Django views from the template with 4 different methods. In your case you will probably only be able to use option 1 and 4 if you don’t want the information in the URL.
1. Post
So you would submit a form with value.
# You can retrieve your code in your views.py via
request.POST.get('value')
2. Query Parameters
You would pass //localhost:8000/?id=123
.
# You can retrieve your code in your views.py via
request.GET.get('id')
3. From the URL (See here for example)
You would pass //localhost:8000/12/results/
.
# urls.py
urlpatterns = patterns(
# ...
url(r'^(?P<question_id>\d+)/results/$', views.results, name='results'),
# ...
)
In your views:
# views.py
# To retrieve (question_id)
def detail(request, question_id):
# ...
return HttpResponse("blahblah")
Downside of using session is you would have had to pass it to the view or set it earlier.
# views.py
# Set the session variable
request.session['uid'] = 123456
# Retrieve the session variable
var = request.session.get('uid')
3👍
To add to JJK’s answer, here’s the detailed way to pass a variable from template to view using form.
Template :
<form action="{% url 'INI:fbpages' SocialAccount.uid %}" method="post">
..
</form>
Above, ‘INI:fbpages’ is the url pattern name defined in urls.py
SocialAccount.uid is the variable that you want to pass to the view.
Note that the double curly braces used in variable rendering in django templates are not used here.
View :
This variable can be directly accessed in the view as the fbuser command argument
def fbpages(request, fbuser):
..
- [Django]-Type object 'X' has no attribute 'objects'
- [Django]-Do CSRF attacks apply to API's?
- [Django]-Django-celery: No result backend configured
0👍
We also use like this:
from django.urls import path
from . import views
urlpatterns = [
path('articles/2003/', views.special_case_2003),
path('articles/<int:year>/', views.year_archive),
path('articles/<int:year>/<int:month>/', views.month_archive),
path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),
]
- [Django]-Django Tag model design
- [Django]-How to setup SSL on a local django server to test a facebook app?
- [Django]-Why does Django REST Framework provide different Authentication mechanisms