def status_(request,id):
stages=['Vendor Quotation','Estimate Generation','Purchase Requsition','Purchase Order','Provision To Invoice','Reimbursement Invoice','Request Receipt#(PTI+RI+PO)','Receipt# Received(Updated PTI)','Request Sales Tax Invoice','Uploaded to Jazz Portal']
ctx={'invoice':Invoices.objects.get(pk=id),'stages':stages}
return render(request,"Invoices/status.html",ctx)
Hi I am trying to pass multiple objects of data for displaying to the template for displaying , I am creating a ctx dictionary with multiple 2 key value pairs ,second Key-value pair is array ,when i access this array in by using
{% for idx in range(0,len(ctx.get("stages")) %}
I get following parsing error
**Could not parse the remainder: '(0,len(ctx.get("stages"))' from 'range(0,len(ctx.get("stages"))'**
You can not make function calls in Django templates with parameters, hence the above wiull not work, but likely you do not need this anyway, you can simply enumerate with:
{% for stage in stages %}
{{ stage }}
{% endfor %}
If you really need to enumerate, then you can pass a range object through the context, but then probably a next problem pops up: you can not subscript with a variable either. It will require using a lot of extra template filters, making it very complicated. Templates are normally not used to implement business logic, therefore Django has a template engine that does not support complicated function calls, etc. to give the developer an incentive to move the business logic to the view.
Related
Lets say I have this model:
class MyLogModel(models.Model):
log_stuff = models.CharField(max_length)
class MoreLogModel(models.Model):
word = models.CharField(max_length)
my_log_model = models.ForeignKey(MyLogModel, related_name="more_log_models")
Now imagine there are 1.000.000.000 MyLogModel and ten times more MoreLogModel which relate to them.
In my view I want to show the user the latest 100 MyLogModel and all the 'word' fields of the MoreLogModel that are relating to them. On average there should be 10 MoreLogModel per MyLogModel.
But if I just use (pseudo code):
my_log_model_query = MyLogModel.objects.get_latest_100
And then loop through it in the template always putting another loop:
{% for my_log in my_log_model_query %}
{% for more_log_model my_log.more_log_models %}
{{ more_log_model.word }}
{% endfor %}
{% endfor %}
That will cause an insane amount of database queries right?
So what I'm wondering is if it is possible to query all MyLogModel with the related "more_log_models" already in a list attached to that model?
The reason why I have the foreign key relationship is because the data comes from a server process that is multi threaded and puts in the "word" whenever it feels like it.
So any ideas how I can solve this problem in general?
Also:
Another way I used before was to have only one model wich has a word field and a group_id. This word field then only contains one word and there is one entry for every word. That causes the 'log_stuff' to be duplicated, but I don't see a big problem with that. What was a huge problem is to go though all these logs and combine them according to the group ids and then sort them based on time again. In the end this causes less queries, but I have to sort everything at least twice which is not very fast.
I have a variable from my view that is the output of a Model.objects.all() call on that Model. I'm passing it to my template in my view, and I'm trying to iterate over it in the template. I can access the first element of it simply by this line of code. 'code' is the name of a field in my django model. This line does print the first element's 'code' attribute correctly.
{{ var_name.0.code }}
However, when I try to iterate over var_name in a template for loop, nothing shows up. I tried the following code:
{% for single_var in var_name %}
{{ single_var.code }}
{% endfor %}
This isn't actually what I want to do in the for loop, but getting this to work will let me do what I need in the template. It may be noteworthy to add that at the moment this list has only one element in it.
This is for a work project, so that's why I changed the variable names to something generic.
I found that changing the name of single_var to something without an underscore seemed to fix it. This doesn't make a lot of sense to me because the Django template language documentation states the following:
Variable names consist of any combination of alphanumeric characters and the underscore ("_").
Does anyone know why this seemed to fix the problem?
I have a list of soccer matches for which I'd like to display forms. The list comes from a remote source.
matches = ["A vs. B", "C vs. D", "E vs, F"]
matchFormset = formset_factory(MatchForm,extra=len(matches))
formset = MatchFormset()
On the template side, I would like to display the formset with the according title (i.e. "A vs. B").
{% for form in formset.forms %}
<fieldset>
<legend>{{TITLE}}</legend>
{{form.team1}} : {{form.team2}}
</fieldset>
{% endfor %}
Now how do I get TITLE to contain the right title for the current form? Or asked in a different way: how do I iterate over matches with the same index as the iteration over formset.forms?
Thanks for your input!
I believe that in the Django template language there is no built-in filter for indexing, but there is one for slicing (slice) -- and therefore I think that, in a pinch, you could use a 1-item slice (with forloop.counter0:forloop.counter) and .first on it to extract the value you want.
Of course it would be easier to do it with some cooperation from the Python side -- you could just have a context variable forms_and_matches set to zip(formset.forms, matches) in the Python code, and, in the template, {% for form, match in forms_and_matches %} to get at both items simply and readably (assuming Django 1.0 or better throughout this answer, of course).
This is an addition to Alex's answer.
I did some reading after my comment on Alex's answer and found that it is important to get the management form (basically a meta-form with information about how many forms are in the formset) into your template for your submitted data to be treated as a formset rather than just a pile of forms. Documentation here.
The only two ways I know to get that into your template are:
Send the formset in addition to whatever data structure you made,
and then render the management form with {{ my_formset.management_form }}
Render the management form in your view and send that as an item to your template
Of course if you use Alex's first method, the formset is already available so you can add the management form directly.
I have written an app and part of it is uses a URL parser to get certain data in a ReST type manner. So if you put /foo/bar as the path it will find all the bar items and if you put /foo it will return all items below foo
So my app has a query like
data = Paths.all().filter('path =', self.request.path).get()
Which works brilliantly. Now I want to send this to the UI using templates
{% for datum in data %}
{{ datum.title }}
{{ datum.content }}
</div>
{% endfor %}
When I do this I get data is not iterable error. So I updated the Django to {% for datum in data.all %} which now appears to pull more data than I was giving it somehow. It shows all data in the datastore which is not ideal. So I removed the .all from the Django and changed the datastore query to
data = Paths.all().filter('path =', self.request.path).fetch(1)
which now works as I intended. In the documentation it says
The db.get() function fetches an
entity from the datastore for a Key
(or list of Keys).
So my question is why can I iterate over a query when it returns with fetch() but can't with get(). Where has my understanding gone wrong?
You're looking at the docs for the wrong get() - you want the get() method on the Query object. In a nutshell, .fetch() always returns a list, while .get() returns the first result, or None if there are no results.
get() requires (I think) that there be exactly one element, and returns it, while fetch() returns a _list_ of the first _n_ elements, where n happens to be 1 in this case.
Thanks to a very helpful hint from another question I learned I can limit the amount of values in a list by slicing it in the template as such:
{% for comment in thread.comment_set.all|slice:":3" %}
Now I would like to get the last 3 results of my comments so I figured a simple ":-3" or "-3" would do the trick, alas:
Caught an exception while rendering: Negative indexing is not supported.
Also using:
{% for comment in thread.comment_set.all|slice:":3" reversed %}
Does not do the trick because if I have 5 comments, instead of 1,2,3 it displays the first three in 3,2,1 order.
Is there any way I can display the last 3 comments of a post without going into my database? I'd love to be able to do this purely using the templating system.
SOLUTION
{% for comment in thread.comment_set.all|dictsortreversed:"created"|slice:"3" %}
Displays the last three thanks to my table having the created timestamp.
Django's database queries are evaluated lazily, so the result of thread.comment_set.all is a QuerySet, not a list. A QuerySet supports many list-like functions, but not negative slicing, so the indexing error is not coming from the template filter itself. (If you're curious, slices on QuerySet objects get translated into a limit clause on the SQL statement, which is why you can't use a negative number).
In general, Django encourages a strict decoupling of templates and models; the views.py module is the glue where you do any work that requires knowledge of database models and queryset methods to translate your model data into simple variables and structures for the template.
Running a related query on a model from a template is not something you typically see in a Django template, and there's a good reason for this. Right now, it may seem very simple to slice the last three elements from the comment_set. Keep in mind, though, that the database will not return results in any guaranteed order. This means that, in addition to your slice, you now also need to add an order_by clause; there's simply no way to express this in a template, nor should there be. Better to think of the view as the translation between your model and the template, and let such database-facing work be done there, rather than embedded in HTML.
In this case, I would encourage you to pass an ordered slice to your template from the view:
# take first three sorted descending
comments = thread.comment_set.order_by('-something')[:3]
context = Context({'comments':comments})
return HttpResponse(tmplt.render(context))
If you must do the slicing in the template, and you really don't care about sorting the results, pass a list to the template. The slice filter will happily do negative slicing:
comments = list(thread.comment_set.all())
context = Context('comments':comments)
In the template:
{% for comment in comments|slice:"-3:" %}
I haven't seen the dictsortreversed filter used too often, and according to the docs it takes a key to sort by
{% for comment in thread.comment_set.all|dictsortreversed:"name"|slice:"3" %}
Use the "ordering" attribute of Meta class of the Comment class to set the required ordering of elements.
IMO templates is not the proper place to order your dataset. Ordering should be done in either Models or Views.
I needed just this and made a more complete solution, I think. Hope people find it useful. The view needs to find the id of the last inserted record (example here). You have to reverse order and get the id (PK) of the newest last record entered which will now be the first record, easy to find now at the top of the heap ;-). Calculate the lower limit id value you desire, then sort from the lower to the newest or last entry using this operator at the end ...[n:m] (I think that is just a list operator), dropping the unwanted records, and then present it in normal order. For a django tables example here is my code:
def showLatestRels(request):
#This view shows the latest 15 entries in the Release table
LastInserted = Release.objects.order_by('-pk')[0]
UpperLimit = LastInserted.id
LowerLimit = UpperLimit - 15
RelTable = Release.objects.all()
tablevalslat = ReleaseTable(RelTable[LowerLimit:UpperLimit])
RequestConfig(request).configure(tablevalslat)
return render(request, 'DCESrtap/latrels.html', {'tablevalslat': tablevalslat}
)
Lots of ways to do it, see Django docs Make/limit Queries
But couldn't get the dictsort idea to work....
Can't you just slice the list before passing it to your template?
You can reverse a queryset if it is already ordered by "created". So here is a faster solution.
{% for comment in thread.comment_set.all.reverse|slice:":3" %}
Also if you don't want in reversed order.
{% for comment in thread.comment_set.all.reverse|slice:":3"|dictsort:"created" %}
Although you should follow Jarrets Hardie advice above and do all that logic in the views, rather then in the templates.