Hi Carsten,

Sorry, are you talking about Writing Your First App, Part2? The page below?
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>.

  """)

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

On Sunday, February 3, 2019 at 1:57:37 AM UTC-5, Carsten Fuchs wrote:
>
> 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.* 
> > * 
> > * 
> > 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 
> > 
>
>

-- 
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 [email protected].
To post to this group, send email to [email protected].
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/79f1289a-7413-4976-8fcb-610fa76bd78e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to