def altword_list(self, request, word_id):

28 views
Skip to first unread message

Pepsodent Cola

unread,
Oct 14, 2013, 9:45:36 PM10/14/13
to django...@googlegroups.com
Hi,

I got some help by somebody on #django IRC.  They gave me this code snippet to fix my problem.  But I'm having problems incorporating that code into my Class file because Template file says "No list is available" when I try to access the list variable.  What am I doing wrong?

# Filter 8
    def altword_list(self, request, word_id):
        #object_list = AltWord.objects.filter(word__pk=word_id).order_by('-votes')
        object_list = Altword.objects.filter(word__pk=word_id).order_by('-votes')

        return render(request, 'navi_polls/altword_list.html', {
            'poll_list': object_list,
        })



Views
#_______________________________________________________________________________

class AltwordlistView(generic.DetailView):
    #model = Word
    model = Altword
    template_name = 'navi_polls/altword_list.html'
    context_object_name = 'poll'

    def get_queryset(self):
# Filter 5
        #return Word.objects.filter(direct_transl_word='')


    def get_context_data(self, **kwargs):
        context = super(AltwordlistView, self).get_context_data(**kwargs)
# Filter 4b
        filter_4b = Altword.objects.filter(rosword__direct_transl_word='').order_by('-votes')
# Filter 7
        filter_7 = Altword.objects.vote_order()
# Filter 8b
#        filter_8b = Altword.objects.filter(word__pk=word_id).order_by('-votes')


        context.update({
            "filter_4b": filter_4b,
            "filter_7": filter_7
 #           "filter_8b": filter_8b
        })
        return context


# Filter 8
    def altword_list(self, request, word_id):
        #object_list = AltWord.objects.filter(word__pk=word_id).order_by('-votes')
        object_list = Altword.objects.filter(word__pk=word_id).order_by('-votes')

        return render(request, 'navi_polls/altword_list.html', {
            'poll_list': object_list,
        })
#_______________________________________________________________________________


Template
#_______________________________________________________________________________

<!-- Filter 8 -->
{% if poll_list %}
    <ul>
    {% for row in poll_list %}
        <li>( id:{{ row.id }} ) - {{ row.rosword }}</li>
    {% endfor %}
    </ul>
{% else %}
    <p>No list is available.</p>
{% endif %}


<!-- poll.altword_set.all.order_by('-votes') -->
<!-- for choice in poll.altword_set.all -->
<!-- for choice in poll %} -->

<!-- for choice in poll_list -->
<!-- for choice in poll_list.altword_rosword.all -->
{% for choice in poll_list %}

Leonardo Giordani

unread,
Oct 15, 2013, 2:30:05 AM10/15/13
to django...@googlegroups.com
Can you check the code you posted? The get_query() function is empty so this code, as posted, can not run.
Please post even the urls you are using to call the view.

Cheers,

Leo

Leonardo Giordani
Author of The Digital Cat
My profile on About.me - My GitHub page - My Coderwall profile


2013/10/15 Pepsodent Cola <pepsod...@gmail.com>

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/d8f21d91-e06d-428d-923d-08ace9d8df8a%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Pepsodent Cola

unread,
Oct 15, 2013, 6:50:13 AM10/15/13
to django...@googlegroups.com

Hi Leo,

get_query() function in class AltwordlistView which I refer to as Filter-5 didn't give me the ordered list result that I wanted.  So somebody on #django IRC helped me to fix that problem by giving me altword_list() function which I refer to as Filter-8.
You can basically ignore all the other Filter codes but I left it there in case it might help you see what I'm trying to do.

My main focus right now is to connect the Filter-8 code to my template altword_list.html but I don't know how to do it.

urls.py
http://dpaste.com/1417526/

views
http://dpaste.com/1417533/

altword_list.html
http://dpaste.com/1417534/





* urls.py

from django.conf.urls import patterns, url
from navi_polls import views
#_______________________________________________________________________________

urlpatterns = patterns('',
    # ex: /polls/
    url(r'^$', views.IndexView.as_view(), name='index'),
    # ex: /polls/5/
    url(r'^specifics/(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
    # ex: /polls/5/results/
    url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
    # ex: /polls/5/vote/
    url(r'^(?P<word_id>\d+)/vote/$', views.vote, name='vote'),

    # ex: /polls/5/
    url(r'^altword_list/(?P<pk>\d+)/$', views.AltwordlistView.as_view(), name='altword_list'),
)



* views.py

from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone

from navi_polls.models import Word, Altword
#_______________________________________________________________________________

class IndexView(generic.ListView):
    template_name = 'navi_polls/index.html'
    context_object_name = 'latest_poll_list'

    def get_queryset(self):
# Filter 1
        """
        Return the last five published polls
        (not including those set to be published in the future).
        """
        return Word.objects.filter(pub_date__lte=timezone.now()
                ).order_by('-pub_date')[:5]

        #"""
        #Return the last five published polls
        #(including those set to be published in the future).
        #"""
        #return Word.objects.order_by('-pub_date')[:5]


    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
# Filter 2
        filter_2 = Word.objects.filter(direct_transl_word='')
# Filter 4
        filter_4 = Altword.objects.filter(rosword__direct_transl_word='')

        context.update({
            "filter_2": filter_2,
            "filter_4": filter_4
        })
        return context
#_______________________________________________________________________________


#_______________________________________________________________________________

class AltwordlistView(generic.DetailView):
    #model = Word
    model = Altword
    template_name = 'navi_polls/altword_list.html'
    context_object_name = 'poll'

    def get_queryset(self):
        #"""
        #Excludes any polls that aren't published yet.
        #"""
        #return Word.objects.filter(pub_date__lte=timezone.now())
# Filter 5
        #return Word.objects.filter(direct_transl_word='')
        #return Word.objects.filter(direct_transl_word='').order_by('-votes')

        return Word.objects.filter(direct_transl_word='').order_by('-altword_rosword__votes')

        #return Altword.objects.filter(rosword__direct_transl_word='')
        #return Altword.objects.filter(word__direct_transl_word='')


    def get_context_data(self, **kwargs):
        context = super(AltwordlistView, self).get_context_data(**kwargs)
# Filter 4b
        filter_4b = Altword.objects.filter(rosword__direct_transl_word='').order_by('-votes')
# Filter 7
        filter_7 = Altword.objects.vote_order()
# Filter 8b
#        filter_8b = Altword.objects.filter(word__pk=word_id).order_by('-votes')


        context.update({
            "filter_4b": filter_4b,
            "filter_7": filter_7
 #           "filter_8b": filter_8b
        })
        return context


# Filter 8
    def altword_list(self, request, word_id):
        #object_list = AltWord.objects.filter(word__pk=word_id).order_by('-votes')
        object_list = Altword.objects.filter(word__pk=word_id).order_by('-votes')

        return render(request, 'navi_polls/altword_list.html', {
            'poll_list': object_list,
        })



* altword_list.html

<h1>{{ poll.rosword }} - id:{{ poll.id }}</h1>


<!-- Filter 8 -->
{% if poll_list %}
    <ul>
    {% for row in poll_list %}
        <li>( id:{{ row.id }} ) - {{ row.rosword }}</li>
    {% endfor %}
    </ul>
{% else %}
    <p>No list is available.</p>
{% endif %}


<h3>Filter 8</h3><!-- Filter 8 -->

<table border="1">
<tr>
<th>Altword_id</th>
<th>Rosword</th>
<th>Alt ros word</th>
<th>Alt transl word</th>
<th>Articulate</th>
<th>Votes</th>
</tr>

<!-- poll.altword_set.all.order_by('-votes') -->
<!-- for choice in poll.altword_set.all -->
<!-- for choice in poll %} -->

<!-- for choice in poll_list -->
<!-- for choice in poll_list.altword_rosword.all -->
{% for choice in poll_list %}
<tr>
    <td>{{ choice.id }}</td>
    <td>{{ choice.rosword }}</td>
    <td>{{ choice.alt_ros_word }}</td>
    <td>{{ choice.alt_transl_word }}</td>
    <td>{{ choice.articulate }}</td>
    <td>{{ choice.votes }}</td>
</tr>
{% endfor %}
</table>



<h3>Filter 5</h3><!-- Filter 5 -->

<table border="1">
<tr>
<th>Altword_id</th>
<th>Rosword</th>
<th>Alt ros word</th>
<th>Alt transl word</th>
<th>Articulate</th>
<th>Votes</th>
</tr>

<!-- poll.altword_set.all.order_by('-votes') -->
<!-- for choice in poll.altword_set.all -->
<!-- for choice in poll %} -->
{% for choice in poll.altword_rosword.all %}
<tr>
    <td>{{ choice.id }}</td>
    <td>{{ choice.rosword }}</td>
    <td>{{ choice.alt_ros_word }}</td>
    <td>{{ choice.alt_transl_word }}</td>
    <td>{{ choice.articulate }}</td>
    <td>{{ choice.votes }}</td>
</tr>
{% endfor %}
</table>



<h3>Filter 7</h3>
<!-- Filter 7 -->
<ul>
{% for choice in filter_7 %}
<li>{{ choice }}  = {{ choice.votes }} votes</li>
{% endfor %}
</ul>

<ul>
{% for choice in filter_7 %}
<li>{{ choice.rosword }} - {{ choice.alt_ros_word }}  = {{ choice.votes }} votes</li>
{% endfor %}
</ul>


<h3>Filter 4b</h3>
<!-- Filter 4b -->
<ul>
{% for choice in filter_4b %}
    <li>{{ choice.rosword }} - {{ choice.alt_ros_word }} - {{ choice.alt_transl_word }} - {{ choice.articulate }} = {{ choice.votes }} votes</li>
{% endfor %}
</ul>









--
You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/32WV-oD5rSc/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users...@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.

Leonardo Giordani

unread,
Oct 16, 2013, 6:29:01 AM10/16/13
to django...@googlegroups.com
Well, I tried to understand the code. Correct me if I did not understand it:

* you are calling AltwordlistView from r'^altword_list/(?P<pk>\d+)/$
* being a DetailedView on Altword, AltwordlistView extracts the Altword with the given pk with a query like Altword.objects.get(pk=pk)
* you set the context you send to the template, in the get_context_data

There, in get_context_data() you have to initialize all the keywords you are going to use in the template. In this case poll_list.

Note that you define a get_queryset() method in AltwordlistView, but I think it is not called in a DetailedView, only ListView uses it.

So I'd fix the whole thing this way:

* get rid of get_queryset()
* get rid of the altword_list() function view
* put something like context['poll_list'] = Altword.objects.filter(word__pk=word_id).order_by('-votes') in get_context_data()

If you are trying to show a list of objects, however, I suggest you to try and use a ListView, where you can define your queryset, as you tried to do with the get_queryset() method.

Try and let me know if something starts to work. Feel free to ask further if the matter is not clear.

Cheers,

Leo

2013/10/15 Pepsodent Cola <pepsod...@gmail.com>

Pepsodent Cola

unread,
Oct 16, 2013, 8:38:39 AM10/16/13
to django...@googlegroups.com
Hi Leo,

Most of what you describe looks familiar, but I'm not 100% sure that what you say is what I'm trying to do.  One thing you said though stands out which was new to me, which was the difference between ListViews and DetailViews.  I'm not very experienced with those and thus don't understand them fully yet.

Note that you define a get_queryset() method in AltwordlistView, but I think it is not called in a DetailedView, only ListView uses it.



Let me try to walk you through visually what I'm trying to do with my messy and confusing code.  :)

1.)
My ERD diagram.

2.)
My Index page list the words that I want in Filter 2 (from Word table).  You can basically ignore everything else my main focus is on Filter 2.  I then click on the word "( id: 1 ) - Page" which then sends me to the AltwordlistView.

3.)
The next page I see is altword_list.html.  Here I am trying to integrate the new Filter 8 code into my project but it's not working.  The template file altword_list.html can't receive any Filter 8 variable from my AltwordlistView.

Only my Filter 5 code is closest to what I am trying to achieve.  It just won't order the votes. :(
Filter 5 code uses get_queryset() so I'm reluctant to throw away that method from AltwordlistView(generic.DetailView).

On this screenshot only Filter 8 and Filter 5 is of interest.  You can basically ignore the rest which are old filter experiments.



4.)
So I'd fix the whole thing this way:
* get rid of get_queryset()
* get rid of the altword_list() function view
* put something like context['poll_list'] = Altword.objects.filter(word__pk=word_id).order_by('-votes') in get_context_data()

I kept the get_queryset() for now because of the above explanation from Step 3.  Until I see a better replacement code.
But I tried to do what you say by integrating the new Filter 8 code into get_context_data().

Views

altword_list.html


What I get is the below exception, so it seems I'm having issues with connecting the PK in my View code.  How do I deal with this kind of problem?

Exception Value: global name 'word_id' is not defined
Exception Location:  Navi/Django/navi/navi_polls/views.py in get_context_data, line 118










Leonardo Giordani

unread,
Oct 21, 2013, 3:02:16 AM10/21/13
to django...@googlegroups.com
Hi,

thank you for attempting to explain the whole code, but really I cannot get the whole thing.
It seems to me that you are trying to implement something too big in a single giant step.

Try to export the meaningful code to a new Django project and reduce it to a couple of models, views and templates; moreover I suggest you to rename functions to something easier to grasp, filter1, filter2, filter3 are really too difficult to remember if you are not the code's author.

As for the DetailView and ListView difference: part 4 of the official Django tutorial talks about this topic, did you run through it? Views and generic views are the basics in Django, if you did not understand them, it would be difficult for you to accomplish something useful.

Try to come up to a simpler code and we will dig into it.

Regards,
Leo


Leonardo Giordani
Author of The Digital Cat
My profile on About.me - My GitHub page - My Coderwall profile


2013/10/16 Pepsodent Cola <pepsod...@gmail.com>

Pepsodent Cola

unread,
Oct 22, 2013, 8:27:49 PM10/22/13
to django...@googlegroups.com
Hello again I am back with a simplified project!

This is my new Presidents ERD-diagram:

I have attached my Presidents project with this email.  Hopefully you will be able to run my example codes.
To access the admin page user/pass=joe/joe.

When you surf to the detail.html page there will be a table.  I want to order this table based on the Votes column from highest to lowest vote count.
How can I accomplish this?

#_______________________________________________________________________________

def detail(request, poll_id):
        #context = Politicalparty.objects.get(pk=poll_id)
        #context = Politicalparty.objects.get(pk=poll_id).order_by('-president_poll__votes')
        context = get_object_or_404(Politicalparty, pk=poll_id)
        return render(request, 'presidents_polls/detail.html', {'poll_key': context})
#_______________________________________________________________________________
presidents_05_Public.tar.gz

Leonardo Giordani

unread,
Oct 23, 2013, 2:56:13 AM10/23/13
to django...@googlegroups.com
Hi! Thank you for simplifying the code.

Well, your question has a very simple answer. I took however the liberty of adjust some other parts of the code.
The resulting files are (just the modified parts) the following, with a brief comment.

urls.py

[...]
    url(r'^(?P<party_id>\d+)/$', views.detail, name='detail'),
    # ex: /presidents_polls/5/results/
    url(r'^(?P<party_id>\d+)/results/$', views.results, name='results'),
    # ex: /presidents_polls/5/vote/
    url(r'^(?P<party_id>\d+)/vote/$', views.vote, name='vote'),
[...]


You are using the views to extract objects from the Politicalparty model, so here it is better to be clear and use party_id instead of poll_id. It is always an integer, so the code works anyway, but it confused me at first glance, so chances are that you will be confused in a month or two.

views.py

[...]
def detail(request, party_id):
    party = get_object_or_404(Politicalparty, pk=party_id)
    presidents = party.president_set.all().order_by('-votes')
    context = {'party':party, 'presidents':presidents}

    return render(request, 'presidents_polls/detail.html', context)
#_______________________________________________________________________________

def results(request, party_id):
    party = get_object_or_404(Politicalparty, pk=party_id)
    return render(request, 'presidents_polls/results.html', {'poll_key': party})
#_______________________________________________________________________________

def vote(request, party_id):
    p = get_object_or_404(Politicalparty, pk=party_id)



The change of the parameter name (polls_id to party_id) reflects here the change in urls.py. The detail() view extracts a party (the name of the variable is important just for clarity's sake), then I extract the presidents list, ordering it by votes (reverse). I suggest you to avoid as much as possible to perform database lookups in the template and to move them to the relative view. So I just moved the .president_set.all here (remember that views.py is valid Python while templates are not, so here you need the brackets).
After that I compile a context dictionary and return it in the response. Again, keys in the context shall be carefully named to avoid confusion.

Please note that I did not change the results() and vote() views, but they can be modified accordingly: for example returning poll_key in results() is misleading.

detail.html

<h1>[id: {{ party.id }}] - {{ party.party }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'presidents_polls:vote' party.id %}" method="post">
{% csrf_token %}
{% for choice in presidents %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
    <label for="choice{{ forloop.counter }}">{{ choice.name }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>


<table border="1">
<tr>
    <th>President_id</th>
    <th>Politicalparty_party</th>
    <th>Name</th>
    <th>Votes</th>
</tr>
{% for row in presidents %}
<tr>
    <td>{{ row.id }}</td>
    <td>{{ row.poll }}</td>
    <td>{{ row.name }}</td>
    <td>{{ row.votes }}</td>

</tr>
{% endfor %}
</table>


Changes here just reflect the changes in the rest of the code.

So, here it is! Hopefully this can help you moving forward. Let me know if there are still dark corners in what I told you, and feel free to ask again.

Cheers,

Leo


Leonardo Giordani
Author of The Digital Cat
My profile on About.me - My GitHub page - My Coderwall profile


2013/10/23 Pepsodent Cola <pepsod...@gmail.com>

Pepsodent Cola

unread,
Oct 23, 2013, 10:37:16 AM10/23/13
to django...@googlegroups.com
Hi Leo,

I changed everything that you suggested and things are working perfect.  Thank you!!! :)

[Solved]
Reply all
Reply to author
Forward
0 new messages