How to use Django session variable in models.py - python

I wanna use the Django session variable on models.py file. How can I do it?
I want to get the user's Pincode/zip and have to run a query using that.
pin_code = #wanna get from session
price = ProductPrice.objects.get(product=self.pk, pincode=pin_code)
I need to get Pincode from the session.

In your model method you don't have access to the request so you do not have access to the session. One way that you could call the method with the session is to add a template tag that passes the value from the session to your method
#register.simple_tag(takes_context=True)
def price(context, product):
return product.get_price(pin_code=context.request.session.get('pin_code'))
In your template you would use the following, if the above code was added to a file with the path app_name/templatetags/product_tags.py
{% load product_tags %}
{% price item %}
Docs on where to put custom template tags

Related

Render dynamic value inside content django template

Please, I would like to render a varible in django template, kind of {{ user.name }} inside of a textfield from database, that I filled up on the django admin. like this
how can I manage to achieve it please, thank you all, have a good day.
If you are using custom form then try using
value={{ user.name }}
and if you are letting Django render the form for you as like "form.as_p" then you can try
form_instance = Form(request.POST)
and send the form instance to the template
After a while of looking, I found out that the right solution of accomplishing such a thing is by creating a filter or tag and affecting it to the content rendered from the database based on the Django documentation link to create custom filters and tags, I created a filter that takes the content as a variable and scanned whenever I find the variable I replace it with the content from the database
# This code goes in the filter logic
values = model.objects.all()
content.replace('{{ user.name }}',values.name)
# This is how the content is rendered on the template
{{content | filter_name}}

How can I pass a client-side parameter to a server-side route without using forms?

I have a simple Flask web app. My index template has various ways of interacting with clients using javascript and HTML. I am also have a form that, upon submission, routes to another flask process and uses the request.form command to retrieve user-submitted data.
However, I want to do something a little different. I would like to initiate a Flask redirection upon javascript event but include a parameter, and not use form.
For example, my index.html file would display something like this after template rendering:
function startRedirect(parameter) {
window.location.pathname = '/myRedirect';
}
<input type="checkbox" id="sample" name="sample" onChange="startRedirect(parameter);">
And part of my Flask script would have:
#app.route('/myRedirect')
def myRedirectFunction():
# do something with the parameter here
return render_template('index.html')
I realize this can be done with using a form, but I am interested in accomplishing this task without having a form. I was thinking about somehow using request.args, but don't quite understand what to do.
You can use a dynamic route to capture a simple input and pass it to the route's function.
app.route('/myRedirect/<param>')
def myRedirectFunction(param='hello world'):
return render_template('index.html', param=param)
Using this route as a redirect, you can pass a single param (or multiple if you serialize them) that you can use to do something. From there, you can either display or you can redirect again to a common endpoint so the user does not see the param in the url.
There's no need for a form or an explicit redirect, just attach a route and some parameter to the dynamic route.
Let's say you have a model to list the departments in your company:
class Departments(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), unique=True)
Now you have a department selection page:
#app.route('/departments_home', methods=['GET'])
def departments_home():
departments = Departments.query.all()
return render_template('departments_home.html',
departments=departments)
On the frontend you might have a variety of selections, each giving a link to the same route but with a different department_id:
{% for department in departments %}
Click to go to {{ department.name }}
{% endfor %}
Now you just need another route to handle this, taking the variable department_id that was passed in the GET request:
#app.route('/load_department/<department_id>', methods=['GET'])
def load_department(department_id):
department = Departments.query.get(int(department_id))
department_data = # do stuff here with the specific department

How to access to get URL address by name in Django at model file (like {{ url 'urlname' }} at template)

Need to access URL by name at model, can't just hardcode it. Need it for error message for a new object creating. Any suggestions?
Update: Just need to put url to error message, not reverse
Your question is not totally clear, but I think you are asking about the reverse function.
You can define get_absolute_url method in your model and than access it in other model's methods. Check https://docs.djangoproject.com/en/2.1/ref/models/instances/#get-absolute-url
I suggest you use a template tag. You can build one for your model and avoid polluting the model about stuff not related to the domain level and keep the presentation level to the template.
Check the docs here on how add a templatetags your app.: https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/
Here a snippet of code to use as starting point for your url generation
from django import template
register = template.Library()
#register.simple_tag(takes_context=True)
def url_for_object(context, object):
# you have both the context and the object available to
# generate your url here
url = ....
return url
In your template use
{% url_for_object my_object %}

Why is the get_absolute_url() defined in the models.py?

I am trying to redo my app views with a Class Based Views(CBV) and stumbled across this function get_absolute_url() being defined in the models.py, generic editing views
I have created models and have never used this function before. Is this specific to CBVs?
It's not specific to CBV, you can use it anywhere in your application. It makes it much easier to get the url for a model instance without having to mess around with url resolving. Also it is much easier to get the definitive url for your object in a template when you can call get_absolute_url on the object itself. For example, if you are looping through a list of objects:
{% for post in blog_posts %}
read post
{% endfor %}
That said, there's nothing stopping you using the method in your view either:
post = BlogPost.objects.get(...)
url = post.get_absolute_url()
There's also is nothing at all special about the method though. You can write your own get_foo_url() if you like instead. For example, I wrote a blog post about a get_admin_url, a method to allow you to get the Django admin url to an object:
class Book(models.Model):
...
def get_admin_url(self):
content_type = ContentType \
.objects \
.get_for_model(self.__class__)
return reverse("admin:%s_%s_change" % (
content_type.app_label,
content_type.model),
args=(self.id,))
# {{ book.get_admin_url }}

How to access properties of referenced objects in Jinja2 templates (Google App Engine)

Consider the following data model in Google App Engine
class A(ndb.Model):
name = ndb.StringProperty()
b = ndb.KeyProperty(Kind='B')
class B(ndb.Model):
name = StringProperty()
now suppose that in a Python Http Request Handler I execute this query
entities = A.query().fetch(200)
and I pass entities as template value to a Jinja2 template
where I iterate over A objects like
{%for a in entities%}
{{a.name}}
{% endfor %}
The question is: how can I access the properties of the B object referenced by A in the Jinja2 template? Something like {{a.b.name}}
You have the key (b) to the entity, so you can get it directly:
{% set b_entity = a.b.get() %}
{{ b_entity.name }}
(Using the set in case you have other properties in the entity. That way you only need to do the get() once)
This is a case where the ndb asyc api might be useful...
#ndb.tasklet
def get_b_instances_from_a_instances(a_instance):
b_instance = yield a_instance.b.get_async()
raise ndb.Return((a_instance, b_instance))
entities = A.query().map(get_b_instances_from_a_instances, limit=200)
Now your entities will be a list of 2-tuples where each has an instance of A and it's corresponding instance of B.

Categories

Resources