I'm relatively new to Django and as a test of my knowledge I'm trying to set up a project where it displays a list of games between anchor tags, when one of the game tags is clicked on, it pulls information about that game from a model using the ID (primary key) relative to that name. For instance the first games ID would be 1 and so on.
However, I am uncertain as to how to approach building a view for this. The only way I was able to get information from a template before was from user input (input tag) and then using request.GET to take the information from the input.
So far in this project, anchor tags are linking to a different URL which has the view which gets the information based on the id, then it should refresh the page and the information should display. Everything should be easy, but I'm just having trouble thinking of a way to get the id of the game based on which link is clicked. Is there a way I can simply set the value of this ID somewhere and reference it in the view, or rather pull the id of the game based on which link is clicked?
Code:
{% extends "base.html" %} <!-- Extends the base models html design-->
{% block title %}Arcade{% endblock %}
{% block content %}
{% if games %}
<p>Found {{ games|length }} game{{ games|pluralize }}</p>
{% for game in games %}
<li>{{ game.game_name }}</li><!--Game Link->
{% endfor %}
{% else %}
<p>There are currently no games in the database.</p>
{% endif %}
{% if results %}
{% endif %}
{% endblock %}
I hope I did an adequate job explaining this problem.
To simplify it further: How do I pull any kind of value from a template?
Thank You
Keith
This is simple. In each iteration of your for loop, you have an object called game, which is presumably a model instance. So you can just do:
<li>{{ game.game_name }}</li>
Or, even better, use the reverse URL functionality:
<li>{{ game.game_name }}</li>
You should look at using AJAX for this.
When the user clicks a tag, have the page asynchronously GET or POST to your django backend. If you want to GET, write a url to the effect of
^/data/game/(\d+)
then grab the id, get your model instance, and return some json or xml.
Related
Here is a Django template.
{% for balance in balances %}
{{ balance.amount }}
{% endfor %}
{% for price in price %}
{{ price.amount}}
{% endfor %}
I would like to show multiple values in Django template like one after another. I also need to print the page number.
For example, 1,2,3,4 page for balance and 5,6,7 is used for the price.
So is there any way I can print it?
For the first request, explain yourself better.
For paging of one or more lists of objects there is already a Class Based View that allows it. The following documentation explains everything clearly:
https://docs.djangoproject.com/en/4.0/topics/pagination/
I'm trying to return a different value for my model object rather than the information stored in the field.
I'm running this in my html file. I've passed a query of 'localcampaigns' to my html file.
In my HTML file I have:
{% for campaign in localcampaigns %}
{{campaign.title}}
{{campaign.time}}
{{campaign.event_date}}
{{campaign.project_focus}}
{% endfor %}
So specifically, say I run this and for the {{campaign.project_focus}} I receive the database object of 'community001' - I want to take this and return something different than this 'community001' like "Community Project"
I've tried to do this by:
{% if '{{campaign.project_focus}}' == 'community001' %}
Community Project
{% endif %}
But I'm unsuccessful. whenever I run != in the template tag, I get the response. So I know that the two don't match. How do I make the two match? Thanks.
{% if campaign.project_focus == 'community001' %}
Community Project
{% endif %}
campaign.project_focus without {{ }} because it's recognized inside the for loop
A simple and logical extension of the tutorial polls app would be showing several questions per page with a single 'submit' button. I've got a hybrid design that uses ModelForms for multi-field questions but individually rendered fields for single-field questions. So the standard question_set page is rendered by:
{% load custom_tags %}
{% block question_set %}
<form action="{% url 'polls:answer' user.username %}" method="POST">
{% csrf_token %}
{% for question in page_question_list %}
<hr/>
{% if question.answer_type == "CH" %}
{% include "polls/Choice_Answer_form.html" %} {%endif%}
{% if question.answer_type == "SA" %}
{% include "polls/Short_Answer_form.html" %} {%endif%}
{% if question.answer_type == "LA" %}
{% include "polls/Long_Answer_form.html" %} {%endif%}
{% if question.answer_type == "E3" %}
{% include "polls/EJ_Answer_form.html" with form=forms|get_item:question%}
{%endif%}
{% if question.answer_type == "E4" %}
{% include "polls/EJ_Answer_form.html" with form=forms|get_item:question%}
{%endif%}
{% if question.answer_type == "BS" %}
{% include "polls/brainstorm_form.html" %}
{% endif %}
{% endfor %}
<br/>
<hr/>
<input type="submit" value="Submit" />
</form>
{% endblock %}
I have a sense that I have missed something fundamental about how forms are supposed to work. When you create a ModelForm object and send it out to be rendered, it knows what instance (in my case, question number and user_id) it corresponds to in the model. When it comes back from the browser, that information is gone if you have disabled, read-only'd or hidden those (id, pk etc) fields. You could put that information in the url, but it will only be feasible if you are dealing with a single row of data on each page. In the docs are [examples][1] cheerfully showing how to ModelForm(request=request, instance=instance) but I don't know how to design it so that the request and the instance stay in sync.
Some strategies I've looked into:
bundle needed forms in formsets and use the 'prefix' to differentiate them. Not sure that the question number association can be retained for rendering (suspect it can) or recovered if it is still dropped from the POST data (suspect it can't).
modifying the rendered field-names to include the Key information (question number, user) to prevent them overlapping in html namespace and only the last values being submitted e.g. generate a new field for the form with the data in it to be rendered and presumably passed back or define a function to set a html_field_name in the constructor.
use the form 'auto_id' (see docs) string to give every field a unique name that encodes question number - suspect this ought to be redundant and better handled by the pros in a formset, but see my first idea.
I probably want to try the easiest and best first; any advice gratefully received.
(I had a bunch more links but am not allowed to post them with so little status)
I found that loading and retrieving the question number from the 'prefix' (but not auto_id) field as a string "qNN#" for each form can work (because the prefix is applied to the element name and auto_id applies to the id, and its the name that the POST data uses). I've put all this logic in 'views.py'
The view that catches the submitted form has to look at the keys in request.POST and when it finds a key beginning with q, it works out what question the fields come from and passes the request off with the question to create the form from the request + prefix.
This means that request.POST is sent to my form_instantiator helper function each time there is form_data to be found, rather than submitting them as a group to be iterated over.
I feel guilty of cruelty to Django, somehow.
I am currently facing a serious problem.
I use the standard django admin interface incl. change list to display one of my models.
The model has got a field, which includes a link (e.g. in database: http://localhost:8000/data/somefile.pdf'>link).
What I want now is that this string is rendered unescaped and displayed as link. I already tried the following in "change_list_results.html":
{% for result in results %}
<tr id="{{ result.1|adminfilter }}" class="{% cycle 'row1' 'row2' %}">
{% for item in result %}
{{ item|safe }}
{% endfor %}</tr>
{% endfor %}
I used "|safe" on the actual item that is output. Furthermore i tried "{% autoescape off %}". Same result, the String got escaped.
Do you see any other way to get the String displayed unescaped?
You want to set allow_tags=True on your method. It's a bit hidden, but it is described in the documentation - about a screen or so down from where this link takes you.
Am working with django Publisher example, I want to list all the publishers in the db via my list_publisher.html template, my template looks like;
{% extends "admin/base_site.html" %}
{% block title %}List of books by publisher{% endblock %}
{% block content %}
<div id="content-main">
<h1>List of publisher:</h1>
{%regroup publisher by name as pub_list %}
{% for pub in pub_list %}
<li>{{ pub.name }}</li>
{% endfor %}
</div>
{% endblock %}
but when I run "http://127.0.0.1:8000/list_publisher/" the template just prints the page title with no error! What am I doing wrong?
A few suggestions:
check that your base_site.html does define a {% block content %}{% endblock %} section to be refine by your my list_publisher.html
check the cardinality of your list: {%regroup publisher by name as pub_list %}{{ pub_list|length }}. That should at least display the length of your list. If is is '0'... you know why it does not display anything
check that your list is indeed sorted by name before using regroup, or use a {% regroup publisher|dictsort:"name" by name as pub_list %} to be sure
If the length is '0', you have to make sure publisher is defined (has been initialized from the database), and sorted appropriately.
In other word, do you see anywhere (in your template or in the defined templates):
publisher = Publisher.objects.all().order_by("name")
?
(again, the order by name is important, to ensure your regroup tag works properly)
Good answer by VonC.
A quick and dirty way to look at pub_list is to stick [{{pub_list}}] in your template. I put it in square brackets in case it's empty. BTW, you may get something that looks like [,,,,,]. This is because object references are wrapped in <> and your browser is going WTF? Just do a View Source and you'll see the full result.