PLEASE HELP! Django documentation, Writing Your First App, Part 4

194 views
Skip to first unread message

Atsunori Kaneshige

unread,
Feb 3, 2019, 3:02:14 AM2/3/19
to Django users
Hi Django users,

I started using Django recently.
I am following the official Django tutorial.
I am just at Writing Your First Django App, Part4, and I have been just copying and pasting all codes.

But I have a problem in vote.
I inserted print(question) and this is printed in detail.html
also, question.id is also printed.

BUT, choice part doesn't seem working.

<THIS IS views.py>
def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    print(question)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist) as e:
        # Redisplay the question voting form.
        print(e)
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

<THIS IS details.html>
<h1>{{ question.question_text }}</h1>

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

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

<br>
{{ question }}
#printed 
 <br>
#printed
<br>
{{ question.choice_set.all }}
#<QuerySet []> #what is this? empty? why?
<br>
{{ question.question_text }}
#printed
<br>
<h1>{{ question.question_text }}</h1>
#printed
<ul>
{% for choice in question.choice_set.all %}
    <li>{{ choice.choice_text }}</li>
{% endfor %}
#nothing printed!
</ul>

Also when I click button 'vote', I only get error.
You didn't select a choice.

I am just copying and pasting so that I can understand Django, but I am having hard time in this Part 4.

I really appreciate advice from anybody!

Nori

Atsunori Kaneshige

unread,
Feb 3, 2019, 3:08:55 AM2/3/19
to Django users
Oh, one note is that I am using postgresql.
everything else except vote function in views.py seems working.

Sorry, any help would be really appreciated!

Nori

Nitin Kalmaste

unread,
Feb 3, 2019, 6:56:18 AM2/3/19
to django...@googlegroups.com
Have you migrated database and added any question there?

--
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 https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a581da0f-abd9-435e-8693-db9126b9bac1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Carsten Fuchs

unread,
Feb 3, 2019, 6:57:37 AM2/3/19
to django...@googlegroups.com
Hi Nori,

does the choice actually exist?
Can you find it if you query the choices using the ORM in `./manage.py shell`?

Best regards,
Carsten


Am 03.02.19 um 03:59 schrieb Atsunori Kaneshige:
> Hi Django users,
>
> I started using Django recently.
> I am following the official Django tutorial.
> I am just at Writing Your First Django App, Part4, and I have been just copying and pasting all codes.
>
> But I have a problem in vote.
> I inserted print(question) and this is printed in detail.html
> also, question.id is also printed.
>
> BUT, choice part doesn't seem working.
>
> *<THIS IS views.py>*
> def vote(request, question_id):
>     question = get_object_or_404(Question, pk=question_id)
>     print(question)
>     try:
>         selected_choice = question.choice_set.get(pk=request.POST['choice'])
>     except (KeyError, Choice.DoesNotExist) as e:
>         # Redisplay the question voting form.
>         print(e)
>         return render(request, 'polls/detail.html', {
>             'question': question,
>             'error_message': "You didn't select a choice.",
>         })
>     else:
>         selected_choice.votes += 1
>         selected_choice.save()
>         # Always return an HttpResponseRedirect after successfully dealing
>         # with POST data. This prevents data from being posted twice if a
>         # user hits the Back button.
>         return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
>
> *<THIS IS details.html>*
> <h1>{{ question.question_text }}</h1>
>
> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
>
> <form action="{% url 'polls:vote' question.id %}" method="post">
> {% csrf_token %}
> {% for choice in question.choice_set.all %}
>     <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
>     <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
> {% endfor %}
> <input type="submit" value="Vote">
> </form>
>
> <br>
> {{ question }}
> #printed 
>  <br>
> {{ question.id }}
> #printed
> <br>
> _{{ question.choice_set.all }}_
> _#<QuerySet []> #what is this? empty? why?_
> <br>
> {{ question.question_text }}
> #printed
> <br>
> <h1>{{ question.question_text }}</h1>
> #printed
> <ul>
> _{% for choice in question.choice_set.all %}_
> _    <li>{{ choice.choice_text }}</li>_
> _{% endfor %}_
> _#nothing printed!_
> </ul>
>
> Also when I click button 'vote', I only get error.
> *You didn't select a choice.*
> *
> *

Malick Cisse

unread,
Feb 3, 2019, 2:08:53 PM2/3/19
to Django users
Hi, copy and paste wouldn't actually make you understand Django. Try to write the code yourself and you see how quickly your understanding grow. 


On Saturday, February 2, 2019 at 10:02:14 PM UTC-5, Atsunori Kaneshige wrote:

Atsunori Kaneshige

unread,
Feb 3, 2019, 3:22:56 PM2/3/19
to Django users
Hi Nitin,

Thank you for your comment.

I did 

jango-admin startproject mysite


and cd mysite, then

python manage.py runserver


and server is working, so I did

opython manage.py startapp polls


polls app was successfully created, and stopped the server because I wanted to user postgresql instead of the default SQLite3(?).
I did below

pg_ctl -D /user/local/var/posgres start


postgres successfully started running, then stopped

By the way, I registered polls app in settings.py (I just copied and pasted part of codes from the file below)
INSTALLED_APPS = [
    'polls.apps.PollsConfig',

Also, I followed the way to add postgres as database, I looked as Django docs
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'Koitaro',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}

I did migration too, like migrate, makemigration etc, just copied and pasted from Django Docs
This is my models.py

import datetime
from django.db import models
from django.utils import timezone

# Create your models here.


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

mygration was successfully generated
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Choice',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('choice_text', models.CharField(max_length=200)),
                ('votes', models.IntegerField(default=0)),
            ],
        ),
        migrations.CreateModel(
            name='Question',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('question_text', models.CharField(max_length=200)),
                ('pub_date', models.DateTimeField(verbose_name='date published')),
            ],
        ),
        migrations.AddField(
            model_name='choice',
            name='question',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Question'),
        ),
    ]

When I go to admin, I added 5 or 6 questions, and successfully added in database.
the database name I made is 'Koitaro'.
I registered in settings.py and I have this database named as Koitaro in my posgresql


question has data, but choice thing doesn't seem having any data...

I really appreciate your thoughts.

Nori

Atsunori Kaneshige

unread,
Feb 3, 2019, 3:23:51 PM2/3/19
to Django users

Atsunori Kaneshige

unread,
Feb 3, 2019, 3:55:48 PM2/3/19
to Django users
Hi Carsten,

Sorry, are you talking about Writing Your First App, Part2? The page below?

Yeah, when I tried this, there was something wrong.

I did that again. I copied and pasted my terminal below.
seems like migration was successful when I did before.
I am not sure what 'python sqlmigrate polls 001' is doing.


MacBook-Pro-3:mysite Koitaro$ python manage.py migrate

/Applications/anaconda3/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.

  """)

Operations to perform:

  Apply all migrations: admin, auth, contenttypes, polls, sessions

Running migrations:

  No migrations to apply.

MacBook-Pro-3:mysite Koitaro$ python manage.py makemigrations polls

/Applications/anaconda3/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.

  """)

No changes detected in app 'polls'

MacBook-Pro-3:mysite Koitaro$ python manage.py sqlmigrate polls 0001

/Applications/anaconda3/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.

  """)

BEGIN;

--

-- Create model Choice

--

CREATE TABLE "polls_choice" ("id" serial NOT NULL PRIMARY KEY, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);

--

-- Create model Question

--

CREATE TABLE "polls_question" ("id" serial NOT NULL PRIMARY KEY, "question_text" varchar(200) NOT NULL, "pub_date" timestamp with time zone NOT NULL);

--

-- Add field question to choice

--

ALTER TABLE "polls_choice" ADD COLUMN "question_id" integer NOT NULL;

CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");

ALTER TABLE "polls_choice" ADD CONSTRAINT "polls_choice_question_id_c5b4b260_fk_polls_question_id" FOREIGN KEY ("question_id") REFERENCES "polls_question" ("id") DEFERRABLE INITIALLY DEFERRED;

COMMIT;

MacBook-Pro-3:mysite Koitaro$ 




After this, when I typed 'python manage.py shell',
By the way, I am not doing this in virtual environment, is it fine?
Django docs doesn't say anything about it.

Here is the result of shell

MacBook-Pro-3:mysite Koitaro$ python manage.py shell

/Applications/anaconda3/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.

  """)

Python 3.6.5 |Anaconda, Inc.| (default, Apr 26 2018, 08:42:37) 

Type 'copyright', 'credits' or 'license' for more information

IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.


In [1]: from polls.models import Choice, Question


In [2]: Question.objects.all()

Out[2]: <QuerySet [<Question: What's up?>, <Question: How's going?>, <Question: Oh, are you OK?>, <Question: Where is she?>]>


In [3]: from django.utils import timezone


In [4]: q = Question(question_text='What's up?,pub_data=timezone.now())

  File "<ipython-input-4-85ce5789a277>", line 1

    q = Question(question_text='What's up?,pub_data=timezone.now())

                                     ^

SyntaxError: invalid syntax



In [5]: q = Question(question_text="What's up?",pub_data=timezone.now())

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-5-bae574063418> in <module>()

----> 1 q = Question(question_text="What's up?",pub_data=timezone.now())


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/base.py in __init__(self, *args, **kwargs)

    483                     pass

    484             for kwarg in kwargs:

--> 485                 raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg)

    486         super().__init__()

    487         post_init.send(sender=cls, instance=self)


TypeError: 'pub_data' is an invalid keyword argument for this function


In [6]: q = Question(question_text="What's up?",pub_date=timezone.now())


In [7]: q.save()


In [8]: q.id

Out[8]: 5


In [9]: q.question_text

Out[9]: "What's up?"


In [10]: q.pub_date

Out[10]: datetime.datetime(2019, 2, 3, 15, 43, 10, 354354, tzinfo=<UTC>)


In [11]: q.question_text = "What's up?"


In [12]: q.save()


In [13]: Question.objects.all()

Out[13]: <QuerySet [<Question: What's up?>, <Question: How's going?>, <Question: Oh, are you OK?>, <Question: Where is she?>, <Question: What's up?>]>


In [14]: from polls.models import Choice, Question


In [15]: Question.objects.all()

Out[15]: <QuerySet [<Question: What's up?>, <Question: How's going?>, <Question: Oh, are you OK?>, <Question: Where is she?>, <Question: What's up?>]>


In [16]: Question.objects.filter(question_text_startswith='What')

---------------------------------------------------------------------------

FieldError                                Traceback (most recent call last)

<ipython-input-16-09474b7667e7> in <module>()

----> 1 Question.objects.filter(question_text_startswith='What')


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/manager.py in manager_method(self, *args, **kwargs)

     80         def create_method(name, method):

     81             def manager_method(self, *args, **kwargs):

---> 82                 return getattr(self.get_queryset(), name)(*args, **kwargs)

     83             manager_method.__name__ = method.__name__

     84             manager_method.__doc__ = method.__doc__


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/query.py in filter(self, *args, **kwargs)

    842         set.

    843         """

--> 844         return self._filter_or_exclude(False, *args, **kwargs)

    845 

    846     def exclude(self, *args, **kwargs):


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/query.py in _filter_or_exclude(self, negate, *args, **kwargs)

    860             clone.query.add_q(~Q(*args, **kwargs))

    861         else:

--> 862             clone.query.add_q(Q(*args, **kwargs))

    863         return clone

    864 


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py in add_q(self, q_object)

   1261         # So, demotion is OK.

   1262         existing_inner = {a for a in self.alias_map if self.alias_map[a].join_type == INNER}

-> 1263         clause, _ = self._add_q(q_object, self.used_aliases)

   1264         if clause:

   1265             self.where.add(clause, AND)


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py in _add_q(self, q_object, used_aliases, branch_negated, current_negated, allow_joins, split_subq)

   1285                     child, can_reuse=used_aliases, branch_negated=branch_negated,

   1286                     current_negated=current_negated, allow_joins=allow_joins,

-> 1287                     split_subq=split_subq,

   1288                 )

   1289                 joinpromoter.add_votes(needed_inner)


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py in build_filter(self, filter_expr, branch_negated, current_negated, can_reuse, allow_joins, split_subq, reuse_with_filtered_relation)

   1162         if not arg:

   1163             raise FieldError("Cannot parse keyword query %r" % arg)

-> 1164         lookups, parts, reffed_expression = self.solve_lookup_type(arg)

   1165 

   1166         if not getattr(reffed_expression, 'filterable', True):


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py in solve_lookup_type(self, lookup)

   1026             if expression:

   1027                 return expression_lookups, (), expression

-> 1028         _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())

   1029         field_parts = lookup_splitted[0:len(lookup_splitted) - len(lookup_parts)]

   1030         if len(lookup_parts) > 1 and not field_parts:


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py in names_to_path(self, names, opts, allow_many, fail_on_missing)

   1387                     )

   1388                     raise FieldError("Cannot resolve keyword '%s' into field. "

-> 1389                                      "Choices are: %s" % (name, ", ".join(available)))

   1390                 break

   1391             # Check if we need any joins for concrete inheritance cases (the


FieldError: Cannot resolve keyword 'question_text_startswith' into field. Choices are: choice, id, pub_date, question_text


In [17]: Question.objects.filter(question_text__startswith='What')

Out[17]: <QuerySet [<Question: What's up?>, <Question: What's up?>]>


In [18]: from django.utils import timezone


In [19]: current_year = timezone.now().year


In [20]: Question.objects.get(pub_date__year=current_year)

---------------------------------------------------------------------------

MultipleObjectsReturned                   Traceback (most recent call last)

<ipython-input-20-05adfe5e79c1> in <module>()

----> 1 Question.objects.get(pub_date__year=current_year)


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/manager.py in manager_method(self, *args, **kwargs)

     80         def create_method(name, method):

     81             def manager_method(self, *args, **kwargs):

---> 82                 return getattr(self.get_queryset(), name)(*args, **kwargs)

     83             manager_method.__name__ = method.__name__

     84             manager_method.__doc__ = method.__doc__


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/query.py in get(self, *args, **kwargs)

    401         raise self.model.MultipleObjectsReturned(

    402             "get() returned more than one %s -- it returned %s!" %

--> 403             (self.model._meta.object_name, num)

    404         )

    405 


MultipleObjectsReturned: get() returned more than one Question -- it returned 5!


In [21]: current_year = timezone.now().year


In [22]: Question.objects.get(pub_date__year=current_year)

---------------------------------------------------------------------------

MultipleObjectsReturned                   Traceback (most recent call last)

<ipython-input-22-05adfe5e79c1> in <module>()

----> 1 Question.objects.get(pub_date__year=current_year)


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/manager.py in manager_method(self, *args, **kwargs)

     80         def create_method(name, method):

     81             def manager_method(self, *args, **kwargs):

---> 82                 return getattr(self.get_queryset(), name)(*args, **kwargs)

     83             manager_method.__name__ = method.__name__

     84             manager_method.__doc__ = method.__doc__


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/query.py in get(self, *args, **kwargs)

    401         raise self.model.MultipleObjectsReturned(

    402             "get() returned more than one %s -- it returned %s!" %

--> 403             (self.model._meta.object_name, num)

    404         )

    405 


MultipleObjectsReturned: get() returned more than one Question -- it returned 5!


In [23]: Question.objects.get(id=2)

Out[23]: <Question: How's going?>


In [24]: Question.objects.get(pk=1)

Out[24]: <Question: What's up?>


In [25]: q = Question.objects.get(pk=1)


In [26]: q.was_published_recently()

Out[26]: True


In [27]: q = Question.objects.get(pk=1)


In [28]: q.choice_set.all()

Out[28]: <QuerySet []>


In [29]: q.choice_set.create(choice_text='Not much',votes=0)

Out[29]: <Choice: Not much>


In [30]: q.choice_set.create(choice_text='The sky',votes=0)

Out[30]: <Choice: The sky>


In [31]: c = q.choice_set.create(choice_text='Just hacking again',votes=0)


In [32]: c.question

Out[32]: <Question: What's up?>


In [33]: q.choice_set.all()

Out[33]: <QuerySet [<Choice: Just hacking again>, <Choice: The sky>, <Choice: Not much>]>


In [34]: q.choice_set.count()

Out[34]: 3


In [35]: Choice.objects.filter(question_pub_date__year=current_year)

---------------------------------------------------------------------------

FieldError                                Traceback (most recent call last)

<ipython-input-35-ae43afb24822> in <module>()

----> 1 Choice.objects.filter(question_pub_date__year=current_year)


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/manager.py in manager_method(self, *args, **kwargs)

     80         def create_method(name, method):

     81             def manager_method(self, *args, **kwargs):

---> 82                 return getattr(self.get_queryset(), name)(*args, **kwargs)

     83             manager_method.__name__ = method.__name__

     84             manager_method.__doc__ = method.__doc__


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/query.py in filter(self, *args, **kwargs)

    842         set.

    843         """

--> 844         return self._filter_or_exclude(False, *args, **kwargs)

    845 

    846     def exclude(self, *args, **kwargs):


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/query.py in _filter_or_exclude(self, negate, *args, **kwargs)

    860             clone.query.add_q(~Q(*args, **kwargs))

    861         else:

--> 862             clone.query.add_q(Q(*args, **kwargs))

    863         return clone

    864 


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py in add_q(self, q_object)

   1261         # So, demotion is OK.

   1262         existing_inner = {a for a in self.alias_map if self.alias_map[a].join_type == INNER}

-> 1263         clause, _ = self._add_q(q_object, self.used_aliases)

   1264         if clause:

   1265             self.where.add(clause, AND)


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py in _add_q(self, q_object, used_aliases, branch_negated, current_negated, allow_joins, split_subq)

   1285                     child, can_reuse=used_aliases, branch_negated=branch_negated,

   1286                     current_negated=current_negated, allow_joins=allow_joins,

-> 1287                     split_subq=split_subq,

   1288                 )

   1289                 joinpromoter.add_votes(needed_inner)


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py in build_filter(self, filter_expr, branch_negated, current_negated, can_reuse, allow_joins, split_subq, reuse_with_filtered_relation)

   1162         if not arg:

   1163             raise FieldError("Cannot parse keyword query %r" % arg)

-> 1164         lookups, parts, reffed_expression = self.solve_lookup_type(arg)

   1165 

   1166         if not getattr(reffed_expression, 'filterable', True):


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py in solve_lookup_type(self, lookup)

   1026             if expression:

   1027                 return expression_lookups, (), expression

-> 1028         _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())

   1029         field_parts = lookup_splitted[0:len(lookup_splitted) - len(lookup_parts)]

   1030         if len(lookup_parts) > 1 and not field_parts:


/Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.py in names_to_path(self, names, opts, allow_many, fail_on_missing)

   1387                     )

   1388                     raise FieldError("Cannot resolve keyword '%s' into field. "

-> 1389                                      "Choices are: %s" % (name, ", ".join(available)))

   1390                 break

   1391             # Check if we need any joins for concrete inheritance cases (the


FieldError: Cannot resolve keyword 'question_pub_date' into field. Choices are: choice_text, id, question, question_id, votes


In [36]: c = q.choice_set.filter(choice_text__startswith='Just hackin'))

  File "<ipython-input-36-93150b748243>", line 1

    c = q.choice_set.filter(choice_text__startswith='Just hackin'))

                                                                  ^

SyntaxError: invalid syntax



In [37]: c = q.choice_set.filter(choice_text__startswith='Just hackin')


In [38]: c.delete()

Out[38]: (1, {'polls.Choice': 1})


In [39]: 



Seems like choice exites and shell thing is working correctly???


Thank you for your comment.

looking forward to hearing from you.

Nori

Atsunori Kaneshige

unread,
Feb 3, 2019, 3:58:49 PM2/3/19
to Django users
Here is the codes about choice



In [27]: q = Question.objects.get(pk=1)


In [28]: q.choice_set.all()

Out[28]: <QuerySet []>


In [29]: q.choice_set.create(choice_text='Not much',votes=0)

Out[29]: <Choice: Not much>


In [30]: q.choice_set.create(choice_text='The sky',votes=0)

Out[30]: <Choice: The sky>


In [31]: c = q.choice_set.create(choice_text='Just hacking again',votes=0)


In [32]: c.question

Out[32]: <Question: What's up?>


In [33]: q.choice_set.all()

Out[33]: <QuerySet [<Choice: Just hacking again>, <Choice: The sky>, <Choice: Not much>]>


In [34]: q.choice_set.count()

Out[34]: 3



choice exits, or correctly working?

Nori

---> 82                 return getattr(self.get_queryset(), name)(*args,<span c

Nitin Kalmaste

unread,
Feb 3, 2019, 4:08:34 PM2/3/19
to django...@googlegroups.com
You have to add Choices for each questions you have created in database like the process is same as you used for the questions.

Carsten Fuchs

unread,
Feb 3, 2019, 8:20:39 PM2/3/19
to django...@googlegroups.com
Well, you're adding choices to q = Question.objects.get(pk=1).
But is this also the question you call the view with?

I suggest you add a few more print statements below your existing

print(question)

For example:

print(question.pk)
print(question.choice_set.all())

# Or, a bit more verbose, for example:
for c in question.choice_set.all():
print(c.pk, c)

# Is the following a valid PK among the choices printed above?
print(request.POST['choice'])

Best regards,
Carsten


Am 2019-02-03 um 16:58 schrieb Atsunori Kaneshige:
> *_Here is the codes about choice_*
>
>
> In [27]: q = Question.objects.get(pk=1)
>
>
> In [28]: q.choice_set.all()
>
> Out[28]: <QuerySet []>
>
>
> In [29]: q.choice_set.create(choice_text='Not much',votes=0)
>
> Out[29]: <Choice: Not much>
>
>
> In [30]: q.choice_set.create(choice_text='The sky',votes=0)
>
> Out[30]: <Choice: The sky>
>
>
> In [31]: c = q.choice_set.create(choice_text='Just hacking again',votes=0)
>
>
> In [32]: c.question
>
> Out[32]: <Question: What's up?>
>
>
> In [33]: q.choice_set.all()
>
> Out[33]: <QuerySet [<Choice: Just hacking again>, <Choice: The sky>, <Choice: Not much>]>
>
>
> In [34]: q.choice_set.count()
>
> Out[34]: 3
>
>
>
> choice exits, or correctly working?
>
> Nori
>
> On Sunday, February 3, 2019 at 10:55:48 AM UTC-5, Atsunori Kaneshige wrote:
>
> Hi Carsten,
>
> Sorry, are you talking about Writing Your First App, Part2? The page below?
> https://docs.djangoproject.com/en/2.1/intro/tutorial02/ <https://docs.djangoproject.com/en/2.1/intro/tutorial02/>
>
> Yeah, when I tried this, there was something wrong.
>
> *_I did that again. I copied and pasted my terminal below._*
> *_seems like migration was successful when I did before._*
> *_I am not sure what 'python sqlmigrate polls 001' is doing._*
>
>
> MacBook-Pro-3:mysite Koitaro$ python manage.py migrate
>
> /Applications/anaconda3/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>>.
>
>   """)
>
> Operations to perform:
>
>   Apply all migrations: admin, auth, contenttypes, polls, sessions
>
> Running migrations:
>
>   No migrations to apply.
>
> MacBook-Pro-3:mysite Koitaro$ python manage.py makemigrations polls
>
> /Applications/anaconda3/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>>.
>
>   """)
>
> No changes detected in app 'polls'
>
> MacBook-Pro-3:mysite Koitaro$ python manage.py sqlmigrate polls 0001
>
> /Applications/anaconda3/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>>.
>
>   """)
>
> BEGIN;
>
> --
>
> -- Create model Choice
>
> --
>
> CREATE TABLE "polls_choice" ("id" serial NOT NULL PRIMARY KEY, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);
>
> --
>
> -- Create model Question
>
> --
>
> CREATE TABLE "polls_question" ("id" serial NOT NULL PRIMARY KEY, "question_text" varchar(200) NOT NULL, "pub_date" timestamp with time zone NOT NULL);
>
> --
>
> -- Add field question to choice
>
> --
>
> ALTER TABLE "polls_choice" ADD COLUMN "question_id" integer NOT NULL;
>
> CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");
>
> ALTER TABLE "polls_choice" ADD CONSTRAINT "polls_choice_question_id_c5b4b260_fk_polls_question_id" FOREIGN KEY ("question_id") REFERENCES "polls_question" ("id") DEFERRABLE INITIALLY DEFERRED;
>
> COMMIT;
>
> MacBook-Pro-3:mysite Koitaro$ 
>
>
>
>
> *_After this, when I typed 'python manage.py shell',_*
> *_By the way, I am not doing this in virtual environment, is it fine?_*
> *_Django docs doesn't say anything about it._*
>
> *_Here is the result of shell_*
>
> MacBook-Pro-3:mysite Koitaro$ python manage.py shell
>
> /Applications/anaconda3/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>>.
>
>   """)
>
> Python 3.6.5 |Anaconda, Inc.| (default, Apr 26 2018, 08:42:37) 
>
> Type 'copyright', 'credits' or 'license' for more information
>
> IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.
>
>
> In [1]: frompolls.modelsimportChoice, Question
>
>
> In [2]: Question.objects.all()
>
> Out[2]: <QuerySet [<Question: What's up?>, <Question: How's going?>, <Question: Oh, are you OK?>, <Question: Where is she?>]>
>
>
> In [3]: fromdjango.utilsimporttimezone
>
>
> In [4]: q = Question(question_text='What's up?,pub_data=timezone.now())
>
>   File "<ipython-input-4-85ce5789a277>", line 1
>
>     q = Question(question_text='What's up?,pub_data=timezone.now())
>
>                                      ^
>
> SyntaxError:invalid syntax
>
>
>
> In [5]: q = Question(question_text="What's up?",pub_data=timezone.now())
>
> ---------------------------------------------------------------------------
>
> TypeError                                Traceback (most recent call last)
>
> <ipython-input-5-bae574063418>in <module>()
>
> ----> 1q =Question(question_text="What's up?",pub_data=timezone.now())
>
>
> /Applications/anaconda3/lib/python3.6/site-packages/django/db/models/base.pyin __init__(self, *args, **kwargs)
>
>     483                    pass
>
>     484            forkwarg inkwargs:
>
> --> 485                raiseTypeError("'%s' is an invalid keyword argument for this function"%kwarg)
>
>     486        super().__init__()
>
>     487        post_init.send(sender=cls,instance=self)
>
>
> TypeError: 'pub_data' is an invalid keyword argument for this function
>
>
> In [6]: q = Question(question_text="What's up?",pub_date=timezone.now())
>
>
> In [7]: q.save()
>
>
> In [8]: q.id <http://q.id>
>
> Out[8]: 5
>
>
> In [9]: q.question_text
>
> Out[9]: "What's up?"
>
>
> In [10]: q.pub_date
>
> Out[10]: datetime.datetime(2019, 2, 3, 15, 43, 10, 354354, tzinfo=<UTC>)
>
>
> In [11]: q.question_text = "What's up?"
>
>
> In [12]: q.save()
>
>
> In [13]: Question.objects.all()
>
> Out[13]: <QuerySet [<Question: What's up?>, <Question: How's going?>, <Question: Oh, are you OK?>, <Question: Where is she?>, <Question: What's up?>]>
>
>
> In [14]: frompolls.modelsimportChoice, Question
>
>
> In [15]: Question.objects.all()
>
> Out[15]: <QuerySet [<Question: What's up?>, <Question: How's going?>, <Question: Oh, are you OK?>, <Question: Where is she?>, <Question: What's up?>]>
>
>
> In [16]: Question.objects.filter(question_text_startswith='What')
>
> ---------------------------------------------------------------------------
>
> FieldError                                Traceback (most recent call last)
>
> <ipython-input-16-09474b7667e7>in <module>()
>
> ----> 1Question.objects.filter(question_text_startswith='What')
>
>
> /Applications/anaconda3/lib/python3.6/site-packages/django/db/models/manager.pyin manager_method(self, *args, **kwargs)
>
>      80        defcreate_method(name,method):
>
>      81            defmanager_method(self,*args,**kwargs):
>
> ---> 82                returngetattr(self.get_queryset(),name)(*args,**kwargs)
>
>      83            manager_method.__name__ =method.__name__
>
>      84            manager_method.__doc__ =method.__doc__
>
>
> /Applications/anaconda3/lib/python3.6/site-packages/django/db/models/query.pyin filter(self, *args, **kwargs)
>
>     842        set.
>
>     843        """
>
> --> 844        returnself._filter_or_exclude(False,*args,**kwargs)
>
>     845 
>
>     846    defexclude(self,*args,**kwargs):
>
>
> /Applications/anaconda3/lib/python3.6/site-packages/django/db/models/query.pyin _filter_or_exclude(self, negate, *args, **kwargs)
>
>     860            clone.query.add_q(~Q(*args,**kwargs))
>
>     861        else:
>
> --> 862            clone.query.add_q(Q(*args,**kwargs))
>
>     863        returnclone
>
>     864 
>
>
> /Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.pyin add_q(self, q_object)
>
>    1261        # So, demotion is OK.
>
>    1262        existing_inner ={a fora inself.alias_map ifself.alias_map[a].join_type ==INNER}
>
> -> 1263        clause,_ =self._add_q(q_object,self.used_aliases)
>
>    1264        ifclause:
>
>    1265            self.where.add(clause,AND)
>
>
> /Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.pyin _add_q(self, q_object, used_aliases, branch_negated, current_negated, allow_joins, split_subq)
>
>    1285                    child,can_reuse=used_aliases,branch_negated=branch_negated,
>
>    1286                    current_negated=current_negated,allow_joins=allow_joins,
>
> -> 1287                    split_subq=split_subq,
>
>    1288                )
>
>    1289                joinpromoter.add_votes(needed_inner)
>
>
> /Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.pyin build_filter(self, filter_expr, branch_negated, current_negated, can_reuse, allow_joins, split_subq, reuse_with_filtered_relation)
>
>    1162        ifnotarg:
>
>    1163            raiseFieldError("Cannot parse keyword query %r"%arg)
>
> -> 1164        lookups,parts,reffed_expression =self.solve_lookup_type(arg)
>
>    1165 
>
>    1166        ifnotgetattr(reffed_expression,'filterable',True):
>
>
> /Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.pyin solve_lookup_type(self, lookup)
>
>    1026            ifexpression:
>
>    1027                returnexpression_lookups,(),expression
>
> -> 1028        _,field,_,lookup_parts =self.names_to_path(lookup_splitted,self.get_meta())
>
>    1029        field_parts =lookup_splitted[0:len(lookup_splitted)-len(lookup_parts)]
>
>    1030        iflen(lookup_parts)>1andnotfield_parts:
>
>
> /Applications/anaconda3/lib/python3.6/site-packages/django/db/models/sql/query.pyin names_to_path(self, names, opts, allow_many, fail_on_missing)
>
>    1387                    )
>
>    1388                    raise FieldError("Cannot resolve keyword '%s' into field. "
>
> -> 1389                                      "Choices are: %s" % (name, ", ".join(available)))
>
>    1390                break
>
>    1391            # Check if we need any joins for concrete inheritance cases (the
>
>
> FieldError: Cannot resolve keyword 'question_text_startswith' into field. Choices are: choice, id, pub_date, question_text
>
>
> In [17]: Question.objects.filter(question_text__startswith='What')
>
> Out[17]: <QuerySet [<Question: What's up?>, <Question: What's up?>]>
>
>
> In [18]: fromdjango.utilsimporttimezone
>
>
> In [19]: current_year = timezone.now().year
>
>
> In [20]: Question.objects.get(pub_date__year=current_year)
>
> ---------------------------------------------------------------------------
>
> MultipleObjectsReturned                  Traceback (most recent call last)
>
> <ipython-input-20-05adfe5e79c1>in <module>()
>
> ----> 1Question.objects.get(pub_date__year=current_year)
>
>
> /Applications/anaconda3/lib/python3.6/site-packages/django/db/models/manager.pyin manager_method(self, *args, **kwargs)
>
>      80        defcreate_method(name,method):
>
>      81            defmanager_method(self,*args,**kwargs):
>
> ---> 82                returngetattr(self.get_queryset(),name)(*args,<span c
>
> --

Atsunori Kaneshige

unread,
Feb 4, 2019, 1:45:34 AM2/4/19
to Django users
Hi Nitin,

Thank you!
I finally understood what you said.
Now working fine. Actually it was working, but I did not understand.

Thank you!

Nori

Atsunori Kaneshige

unread,
Feb 4, 2019, 1:52:44 AM2/4/19
to Django users
Hi Carsten,

Thank you!
I finally understood what's happening.
I should have added choices into each question.
Now, choice_set.all thing is working!

Thank you for your advice!

Nori
Reply all
Reply to author
Forward
0 new messages