I want to display a value that user types
I am able to get the value using this lines:
def on_submit_click(req):
name = req.GET['search']
return render(req, 'search_test.html')
But i'm not quite sure how to display it on the website
I tried doing this in the search_test.html:
<h1 class="text-white text-center">{{ name }}</h1>
But it didn't work either.
You're missing the template context in your invocation of render(). render() takese these parameters:
render(request, template_name, context=None, content_type=None, status=None, using=None)
The template context is a dictionary with values which will replace the placeholders in the template. In your case, you want to replace the {{name}} with the search query param, I assume. So, your method should look like this:
def on_submit_click(req):
name = req.GET['search']
return render(req, 'search_test.html', {"name": name}, content_type='application/xhtml+xml')
I've also set the content type
Related
Using Django I want to implement some middleware that will calculate some context that is to be used by the view itself.
For example, I have a middleware that looks at the request, and adds the user's permissions to the request, or some user configuration. The view looks at these permissions and decides how to handle the request using it.
This saves the need for multiple views (and multiple parts within the view) to query for this information.
I'm wondering what is the correct way to do that. One option is to just add request.user_permissions=... directly on the request. But is there some documented and expected way to do that?
There's no real documented way to do that, but Middleware is the correct place to do it and just adding properties to the request object is also the correct way.
You can confirm this, because Django is already doing it:
LocaleMiddelware
AuthenticationMiddleware
RemoteUserMiddleware
CurrentSiteMiddleware
SessionMiddleware
So just pick whatever is the most convenient data structure for your use case and tack that on to the request object.
This is not a perfect answer but at my experience I use this code. Every permission is saved in a boolean value which is true or false. You can access it in a html template like.
{% if request.user.is_admin %}
"Your code here"
{% else %}
"Your code here"
{% endif %}
and to send extra context you should create and pass an dicionary and pass it as as an argument to the render method from the view.
For eg:
def view(request, slug):
context = {'administrator':True}
blog_post = get_object_or_404(BlogPost, slug=slug)
context['blog_post'] = blog_post
return render(request, 'blog/detail_blog.html', context)
and access it like
{% if context.administrator %}
"Your code here"
{% else %}
"Your code here"
{% endif %}
I believe, since your middleware will calculate context, it should be implemented as context processor.
https://docs.djangoproject.com/en/3.1/ref/templates/api/#using-requestcontext
https://docs.djangoproject.com/en/3.1/ref/templates/api/#writing-your-own-context-processors
I'm trying to get all attributes of a single object. I keep getting a "Devices matching query does not exist." I just cannot figure out my issue.
Models.py
`class Devices(models.Model):
category_id = models.ForeignKey(Category, on_delete=models.CASCADE)
device_description = models.CharField(max_length=100)
device_status = models.CharField(max_length=50)
device_date = models.DateTimeField()
device_user = models.CharField(max_length=50)`
Views.py
def view_status(request, pk=None):
device = Devices.objects.get(pk=pk)
return render(request, 'homesite/device_status.html', device)
urls.py
url(r'^viewstatus/$', views.view_status, name='ViewStatus'),
here is the url I use to call http://localhost:8000/homesite/viewstatus/?pk=1
device_satus.html
{% extends "base.html" %}
{% block head %}
<title>Device Status</title>
{% endblock%}
{% block body %}
<h3>Device Status Detail</h3>
{{ devices.device_description }}
{{ devices.device_status }}
{{devices.device_date|date:"Y-m-d H:m:s"}}
{% endblock %}
There are 4 records in my able so I know there is a match for PK=1.
Note, that this is not the usual way to build an URL for accessing a specific object. Below I present first the approach that integrates pk in the URI and second the one passing pk as a parameter.
1. Approach
Here you put the pk in the URI and request something like http://localhost:8000/homesite/viewstatus/1/. If you do so, you need to adapt your urls.py by specifying what part of the URI is the pk you want:
# urls.py
url(r'^viewstatus/(?P<pk>\d+)/$', views.view_status, name='ViewStatus'),
The way you wrote the view is fine:
def view_status(request, pk=None):
if pk is not None:
device = Devices.objects.get(pk=pk)
else:
device = None
return render(request, 'homesite/device_status.html', {'device' : device})
Now, views.view_status will be called with both the request object and the pk as arguments and objects.get will behave as you expected, if the pk you put in the URI exists in you database.
Note that this is the preferred way to get an object.
2. Approach
In this case you pass the pk as a parameter, so call http://localhost:8000/homesite/viewstatus/?pk=1, for example. Now pk is a parameter of a GET request. In this case:
# urls.py
url(r'^viewstatus/$', views.view_status, name='ViewStatus'),
And the view only takes the request object as argument. Within the view you can get the pk as follows:
def view_status(request):
pk = request.GET.get('pk', None)
if pk is not None:
device = Devices.objects.get(pk=int(pk))
else:
device = None
return render(request, 'homesite/device_status.html', {'device' : device})
So in this case your view does not take any arguments other than the request object.
Another issue is in your view function: Django's shortcut render takes a dict object for the optional argument context. Currently you directly pass a Devices object. You need to update your return statement in view_status:
return render(request, 'homesite/device_status.html', {'device' : device})
Hope that helps!
I get an error 'Devices' object is not iterable
urls.py
this is how the url is set up.
url(r'^viewstatus/$', views.view_status, name='ViewStatus'),
but is should be like this
url(r'^viewstatus/(?P<pk>\d+)/$', views.view_status, name='ViewStatus'),
so that I can call like this correct? http://localhost:8000/homesite/viewstatus/1/
views.py
def view_status(request):
pk = request.GET['pk']
device = Devices.objects.get(pk=pk)
return render(request, 'homesite/device_status.html', device
so i need the corresponding views.py code to work with
http://localhost:8000/homesite/viewstatus/1/
I've stared at this for hours so I know I'm missing something simple.
Try changing your view function:
def view_status(request):
pk = request.GET['pk']
device = Devices.objects.get(pk=pk)
return render(request, 'homesite/device_status.html', device)
Let me know if it helps :)
I have edit_client view, Client model and a ClientForm. What I need is to edit an existing record from Client but display it as an editable form, and save the updated record. What should be seen in my views.py and my edit_client.html?
You can create a function named : edit_client into your view file.
As an example, you can use a link in your html like this :
<a href="{% "edit_client" client.pk %}> {{ client.name }} </a>
And your function can be :
def edit_client(request, client_id):
client = Client.objects.get(pk=client_id)
clients = Client.objects.all()
if request.method = "POST":
# what you want to edit (name, age etc ...)
client.save()
return render_to_response('index.html', {"clients":clients}, context_instance=RequestContext(request))
else:
return render_to_response('edit_client.html', {"client":client}, context_instance=RequestContext(request))
Note that it will be different if you want to use a form.
I have seen similar questions and answers but none that address my problem.
I want my view to perform a User Group check and then pass that via variable to the template. The template will then use that to appear differently to different user groups.
My views.py:
def cans(request):
is_canner = request.user.groups.filter(name='canner') #check if user group = canner
can_list = Can.objects.order_by('name')
context = {'can_list': can_list}
return render(request, 'cans/cans.html', context) #need to return is_canner variable here
And in my template I would use the variable like so:
{% if is_canner %} canner stuff goes here {% endif %}
I'm unsure how to pass this variable, I thought it used context to send it like so:
return render(request, 'cans/cans.html', context({"is_canner": is_canner}))
But this gives me errors - context is not callable.
context is not a function, its an argument to the render function, e.g.
context = {"is_canner": is_canner}
return render(request, 'cans/cans.html', context)
docs: https://docs.djangoproject.com/en/dev/topics/http/shortcuts/#render
more background info: Django - what is the difference between render(), render_to_response() and direct_to_template()?
I created a table using django-tables2 and everything is working fince except that I want to add other instances or variable to the url template.
Here is my view:
def SpecificPLayer(request, playerslug):
player = Player_Bios.objects.get(player_id=playerslug)
table= StatTable(BatStat.objects.filter(player_id=playerslug).values('season','team_id'))
RequestConfig(request, paginate=False).configure(table)
return render(request, 'singleplayer.html', {'table': table})
What about if I want to pass the following to the template:
today = date.today()
My common sense told me to do this:
return render(request, 'singleplayer.html','today':taday {'table': table}) #does not work
on my singleplayer.html, I have the following:
{{ today }}
the answer is:
return render(request, 'singleplayer.html', {'table': table, 'today':taday})
You need to have all of the variable that you want to use in the view inside the dictionary.