PLEASE HELP! Django documentation, Writing Your First App, Part 4
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. ** 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,))) ** {{ question.question_text }} {% if error_message %}{{ error_message }}{% endif %} {% csrf_token %} {% for choice in question.choice_set.all %} {{ choice.choice_text }} {% endfor %} {{ question }} #printed {{ question.id }} #printed *{{ question.choice_set.all }}* *# #what is this? empty? why?* {{ question.question_text }} #printed {{ question.question_text }} #printed *{% for choice in question.choice_set.all %}* *{{ choice.choice_text }}* *{% endfor %}* *#nothing printed!* 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 django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@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/81acb823-ce5b-40c5-8060-573a61136697%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: PLEASE HELP! Django documentation, Writing Your First App, Part 4
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 On Saturday, February 2, 2019 at 10:02:14 PM UTC-5, Atsunori Kaneshige wrote: > > 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. > > ** > 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,))) > > ** > {{ question.question_text }} > > {% if error_message %}{{ error_message }}{% endif > %} > > > {% csrf_token %} > {% for choice in question.choice_set.all %} > value="{{ choice.id }}"> > {{ choice.choice_text > }} > {% endfor %} > > > > > {{ question }} > #printed > > {{ question.id }} > #printed > > *{{ question.choice_set.all }}* > *# #what is this? empty? why?* > > {{ question.question_text }} > #printed > > {{ question.question_text }} > #printed > > *{% for choice in question.choice_set.all %}* > *{{ choice.choice_text }}* > *{% endfor %}* > *#nothing printed!* > > > 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 django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@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.
Re: PLEASE HELP! Django documentation, Writing Your First App, Part 4
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 On Sunday, February 3, 2019 at 1:56:18 AM UTC-5, Nitin Kalmaste wrote: > > Have you migrated database and added any question there? > > On Sun, Feb 3, 2019, 8:39 AM Atsunori Kaneshige wrote: > >> 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 >> >> On Saturday, February 2, 2019 at 10:02:14 PM UTC-5, Atsunori Kaneshige >> wrote: >>> >>> 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. >>> >>> ** >>> 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 t
Re: PLEASE HELP! Django documentation, Writing Your First App, Part 4
On Sunday, February 3, 2019 at 10:22:56 AM UTC-5, Atsunori Kaneshige wrote: > > 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 > > > > > > > > > > > On Sunday, February 3, 2019 at 1:56:18 AM UTC-5, Nitin Kalmaste wrote: >> >> Have you migrated database and added any question there? >> >> On Sun, Feb 3, 2019, 8:39 AM Atsunori Kaneshige > >>> 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 >>> >>> On Saturday, February 2, 2019 at 10:02:14 PM UTC-5, Atsunori Kaneshige >>> wrote: >>>> >>>> Hi Django users, >>>> >>>> I started using Django recently. >>>> I am following the official Django tutorial. >>>> I am ju
Re: PLEASE HELP! Django documentation, Writing Your First App, Part 4
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 "", 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. > > > > ** > > 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,))) > > > > ** > > {{ question.question_text }} > > > > {% if error_message %}{{ error_message }}{% > endif %} > > > > > > {% csrf_token %} > > {% for choice in question.choice_set.all %} > > value="{{ choice.id }}"> > > {{ choice.choice_text > }} > > {% endfor %} > > > > > > > > > > {{ question }} > > #printed > > > > {{ question.id }} > > #printed > > > > _{{ question.choice_set.all }}_ > > _# #what is this? empty? why?_ > > > > {{ question.question_text }} > > #printed > > > > {{ question.question_text }} > > #printed > > > > _{% for choice in question.choice_set.all %}_ > > _{{ choice.choice_text }}_ > > _{% endfor %}_ > > _#nothing printed!_ > > > > > > 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 django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@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/79f1289a-7413-4976-8fcb-610fa76bd78e%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: PLEASE HELP! Django documentation, Writing Your First App, Part 4
*Here is the codes about choice* In [27]: q = Question.objects.get(pk=1) In [28]: q.choice_set.all() Out[28]: In [29]: q.choice_set.create(choice_text='Not much',votes=0) Out[29]: In [30]: q.choice_set.create(choice_text='The sky',votes=0) Out[30]: In [31]: c = q.choice_set.create(choice_text='Just hacking again',votes=0) In [32]: c.question Out[32]: In [33]: q.choice_set.all() Out[33]: , , ]> 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/ > > 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]: Ques
Re: PLEASE HELP! Django documentation, Writing Your First App, Part 4
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 On Sunday, February 3, 2019 at 11:08:34 AM UTC-5, Nitin Kalmaste wrote: > > You have to add Choices for each questions you have created in database > like the process is same as you used for the questions. > On Sun, Feb 3, 2019, 8:53 PM Atsunori Kaneshige wrote: > >> 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. >> >
Re: PLEASE HELP! Django documentation, Writing Your First App, Part 4
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 On Sunday, February 3, 2019 at 3:20:39 PM UTC-5, Carsten Fuchs wrote: > > 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]: > > > > > > In [29]: q.choice_set.create(choice_text='Not much',votes=0) > > > > Out[29]: > > > > > > In [30]: q.choice_set.create(choice_text='The sky',votes=0) > > > > Out[30]: > > > > > > In [31]: c = q.choice_set.create(choice_text='Just hacking > again',votes=0) > > > > > > In [32]: c.question > > > > Out[32]: > > > > > > In [33]: q.choice_set.all() > > > > Out[33]: , , > ]> > > > > > > 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 > &
columns were not added/created to my database table (postgresql) after makemigrations/migrate
Hi, Django masters! My app has simple models.py just two fields like below. #models.py class List(models.Model): item = models.CharField(max_length=200) completed = models.BooleanField(default=False) #migration 0001 class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='List', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('item', models.CharField(max_length=200)), ('completed', models.BooleanField(default=False)), ], ), ] and after makemigrations/migrate, the app was working no problem. *Then, I wanted to try adding two more fields.* #new models.py class List(models.Model): item = models.CharField(max_length=200) completed = models.BooleanField(default=False) *created_at = models.DateTimeField('date', auto_now_add=True, null = True) * * updated_at = models.DateTimeField('update', auto_now=True, null = True) * #migrations 0002 class Migration(migrations.Migration): dependencies = [ ('pages', '0001_initial'), ] operations = [ migrations.AddField( model_name='list', name='created_at', field=models.DateTimeField(auto_now_add=True, null=True, verbose_name='date'), ), migrations.AddField( model_name='list', name='updated_at', field=models.DateTimeField(auto_now=True, null=True, verbose_name='update'), ), ] Django doc says that I need to add '*null = True*' because I am using postgresql as my database. Without '*null = True*', the program throws an error saying that column pages_list.created_at doesn't exist etc. when I try to see the web page. But, with '*null = True*', I successfully did makemigration and migrate, then web page showed up without any problem. *But, when I go to admin, I could not find any fields that I though I created.* I also looked at the table in my postgresql, but again, there are only original columns, but not other two columns. Do you know how to add new columns by changing models.py?? What should I take care to successfully modify models and add new columns in my database table (postgresql in my case). I really appreciate your advice! Looking forward to hearing from you. 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 django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@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/a1d71d4c-1500-4972-af57-dc23f5d1ff20%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: columns were not added/created to my database table (postgresql) after makemigrations/migrate
Hi Nitin, Thank you for your comment. I did not add any additional class in models.py. I just added two fields under the same class, List. class List(models.Model): item = models.CharField(max_length=200) completed = models.BooleanField(default=False) *created_at = models.DateTimeField('date', auto_now_add=True, null = True) * * updated_at = models.DateTimeField('update', auto_now=True, null = True) * In admin.py, I did not change anything. #this is my admin.py from django.contrib import admin from .models import List # Register your models here. then go to admin page and re-load admin.site.register(List) Why new columns (or in other words, new fields) do not show up in my admin site? Even though I did makemigrations/migrate. Thank you for your help! Nori On Tuesday, February 5, 2019 at 9:58:30 PM UTC-5, Nitin Kalmaste wrote: > > You need to add python's magic method in order to return something from > the models you have created. Also you have to register your models to > admin.py file. You can refer Django documents for that. > > On Wed, Feb 6, 2019, 8:03 AM Atsunori Kaneshige wrote: > >> Hi, Django masters! >> >> My app has simple models.py >> just two fields like below. >> >> #models.py >> class List(models.Model): >> item = models.CharField(max_length=200) >> completed = models.BooleanField(default=False) >> >> #migration 0001 >> class Migration(migrations.Migration): >> >> initial = True >> >> dependencies = [ >> ] >> >> operations = [ >> migrations.CreateModel( >> name='List', >> fields=[ >> ('id', models.AutoField(auto_created=True, >> primary_key=True, serialize=False, verbose_name='ID')), >> ('item', models.CharField(max_length=200)), >> ('completed', models.BooleanField(default=False)), >> ], >> ), >> ] >> >> and after makemigrations/migrate, the app was working no problem. >> *Then, I wanted to try adding two more fields.* >> >> #new models.py >> class List(models.Model): >> item = models.CharField(max_length=200) >> completed = models.BooleanField(default=False) >> *created_at = models.DateTimeField('date', auto_now_add=True, null = >> True) * >> * updated_at = models.DateTimeField('update', auto_now=True, null = >> True) * >> >> #migrations 0002 >> class Migration(migrations.Migration): >> >> dependencies = [ >> ('pages', '0001_initial'), >> ] >> >> operations = [ >> migrations.AddField( >> model_name='list', >> name='created_at', >> field=models.DateTimeField(auto_now_add=True, null=True, >> verbose_name='date'), >> ), >> migrations.AddField( >> model_name='list', >> name='updated_at', >> field=models.DateTimeField(auto_now=True, null=True, >> verbose_name='update'), >> ), >> ] >> >> >> Django doc says that I need to add '*null = True*' because I am using >> postgresql as my database. >> Without '*null = True*', the program throws an error saying that column >> pages_list.created_at doesn't exist etc. when I try to see the web page. >> But, with '*null = True*', I successfully did makemigration and migrate, >> then web page showed up without any problem. >> >> *But, when I go to admin, I could not find any fields that I though I >> created.* >> I also looked at the table in my postgresql, but again, there are only >> original columns, but not other two columns. >> >> Do you know how to add new columns by changing models.py?? >> What should I take care to successfully modify models and add new columns >> in my database table (postgresql in my case). >> >> I really appreciate your advice! >> >> Looking forward to hearing from you. >> >> 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 django-users...@googlegroups.com . >> To post to this group, send email to django...@googlegroups.com >> . >> Vi
Django, Markdownx, image upload from admin after deployment
Hi, everyone, I have a problem in uploading image from admin site of my simple blog. Everything works fine locally. *I implemented Markdownx and I can drag and drop images into new blog in admin.* The uploaded images from admin site are stored in media/markdownx folder as expected. I did deployment and everything works fine *However, only image uploading from admin site in production is not working.* Since everything works fine locally, I have trouble in figuring out what is a possible solution for this. Could anyone give an advice about this image upload issue? I really appreciate your advice! 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 django-users+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/009f5d42-f25a-4094-9389-e1513035d979%40googlegroups.com.
Re: Django, Markdownx, image upload from admin after deployment
Hi, Yashwanth, Thank you for your reply. I watched it, but this is nothing to do with markdownx. I implemented markdownx, https://github.com/neutronX/django-markdownx. This is working properly locally and I can upload images by drag&drop in my admin site. *However, I cannot drag and drop images from my admin site in production.* *Everything else works fine in production.* I have no clue how to fix this issue in production since this is working fine locally. Nori On Saturday, May 2, 2020 at 1:03:42 PM UTC-4, yashwanth balanagu wrote: > > https://www.youtube.com/watch?v=0Ov1Yd1uCuA > > once see this video > -- 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+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/07241a2a-d4ca-4470-9d0a-6441dd976d58%40googlegroups.com.
Question about form_valid: how to automatically set multiple fields when users input data via CreateView supported form?
I really appreciate if anybody could give me an advice about form_valid. Here is what I want to do. I am making a simple blog. I am making simple features: 1) only superuser can create articles. 2) logged-in users can make comments to articles. I followed along tutorials and mostly done. *But last thing I want to do is that when users make comments to any articles, I want author field and article field to be automatically set.* *Currently, users need to choose author field and article field to make comments as well as comment texts.* The tutorial that I followed along uses form_valid and by using form_valid, now I don't need to choose author. But I have been struggling with how to automatically set article field by using form_valid. I have a simple models.py and views.py below. class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) class Comment(models.Model): # new article = models.ForeignKey( Article, on_delete=models.CASCADE, related_name = 'comments', ) comment = models.CharField(max_length=140) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.comment def get_absolute_url(self): return reverse('article_list') ...(not showing all) #for comment class ArticleCommentCreateView(LoginRequiredMixin, CreateView): model = Comment template_name = 'article_comment_new.html' fields = ('comment',) login_url = 'login' def form_valid(self, form): form.instance.author = self.request.user *form.instance.article = self.request.article* return super().form_valid(form) I keep getting errors with this code. I know that *form.instance.article = self.request.article* is something wrong, but I am having hard time to figure out how to set article field to be automatically set. Please give any advice about this. I really appreciate. Looking forward to hearing from anyone. Best regards, 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 django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@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/fe3a8f1d-2e97-41f8-8af4-fe638cb9e787%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: Question about form_valid: how to automatically set multiple fields when users input data via CreateView supported form?
Sorry, when I make a comment, I get this error. Any advice would be really appreciated! AttributeError at /articles/2/comment/ 'WSGIRequest' object has no attribute 'article' Request Method: POST Request URL: http://127.0.0.1:8000/articles/2/comment/ Django Version: 2.1.5 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'article' Exception Location: /Users/Koitaro/Desktop/Web_Development/MMBlog/articles/views.py in form_valid, line 75 Python Executable: /Users/Koitaro/.local/share/virtualenvs/MMBlog-58h299OP/bin/python Python Version: 3.6.5 Python Path: ['/Users/Koitaro/Desktop/Web_Development/MMBlog', '/Users/Koitaro/.local/share/virtualenvs/MMBlog-58h299OP/lib/python36.zip', '/Users/Koitaro/.local/share/virtualenvs/MMBlog-58h299OP/lib/python3.6', '/Users/Koitaro/.local/share/virtualenvs/MMBlog-58h299OP/lib/python3.6/lib-dynload', '/Applications/anaconda3/lib/python3.6', '/Users/Koitaro/.local/share/virtualenvs/MMBlog-58h299OP/lib/python3.6/site-packages'] Server time: Sat, 27 Apr 2019 21:24:45 + On Saturday, April 27, 2019 at 5:07:19 PM UTC-4, Atsunori Kaneshige wrote: > > I really appreciate if anybody could give me an advice about form_valid. > > Here is what I want to do. > I am making a simple blog. > I am making simple features: > 1) only superuser can create articles. > 2) logged-in users can make comments to articles. > > I followed along tutorials and mostly done. > *But last thing I want to do is that when users make comments to any > articles, I want author field and article field to be automatically set.* > *Currently, users need to choose author field and article field to make > comments as well as comment texts.* > > The tutorial that I followed along uses form_valid and by using > form_valid, now I don't need to choose author. > But I have been struggling with how to automatically set article field by > using form_valid. > > I have a simple models.py and views.py below. > > > > class Article(models.Model): > title = models.CharField(max_length=255) > body = models.TextField() > date = models.DateTimeField(auto_now_add=True) > author = models.ForeignKey( > get_user_model(), > on_delete=models.CASCADE, > ) > > def __str__(self): > return self.title > > def get_absolute_url(self): > return reverse('article_detail', args=[str(self.id)]) > > class Comment(models.Model): # new > article = models.ForeignKey( > Article, > on_delete=models.CASCADE, > related_name = 'comments', > ) > comment = models.CharField(max_length=140) > author = models.ForeignKey( > get_user_model(), > on_delete=models.CASCADE, > ) > > def __str__(self): > return self.comment > > def get_absolute_url(self): > return reverse('article_list') > > > ...(not showing all) > #for comment > class ArticleCommentCreateView(LoginRequiredMixin, CreateView): > model = Comment > template_name = 'article_comment_new.html' > fields = ('comment',) > login_url = 'login' > > def form_valid(self, form): > form.instance.author = self.request.user > *form.instance.article = self.request.article* > return super().form_valid(form) > > I keep getting errors with this code. > I know that *form.instance.article = self.request.article* is something > wrong, but I am having hard time to figure out how to set article field to > be automatically set. > > > Please give any advice about this. > I really appreciate. > > Looking forward to hearing from anyone. > > Best regards, > > 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 django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@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/352ed4ec-fcf8-4590-ae0b-9c97e29d80ef%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: Question about form_valid: how to automatically set multiple fields when users input data via CreateView supported form?
Hi, Britto, Thank you very much for your reply! I tried form.instance.article = *self.*request.POST.get('article'), I still got an error shown below. RelatedObjectDoesNotExist at /articles/2/comment/ Comment has no article. Request Method: POST Request URL: http://127.0.0.1:8000/articles/2/comment/ Django Version: 2.1.5 Exception Type: RelatedObjectDoesNotExist Exception Value: Comment has no article. Exception Location: /Users/Koitaro/.local/share/virtualenvs/MMBlog-58h299OP/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py in __get__, line 188 Python Executable: /Users/Koitaro/.local/share/virtualenvs/MMBlog-58h299OP/bin/python Python Version: 3.6.5 When I tried print(dir(self.request.POST)), I got the below. ['__class__', '__contains__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_assert_mutable', '_encoding', '_getlist', '_mutable', 'appendlist', 'clear', 'copy', 'dict', 'encoding', 'fromkeys', 'get', 'getlist', 'items', 'keys', 'lists', 'pop', 'popitem', 'setdefault', 'setlist', 'setlistdefault', 'update', 'urlencode', 'values'] When I tried print(self.request.POST.items), I got the blow, for example. > I typed the message ('I am maru') and needed to specify the article that I made the message to. I needed to set fields = ('comment','article',) in CommentCreateView, otherwise, I get an error like the below. RelatedObjectDoesNotExist at /articles/2/comment/ Comment has no article. Request Method: POST Request URL: http://127.0.0.1:8000/articles/2/comment/ Django Version: 2.1.5 Exception Type: RelatedObjectDoesNotExist Exception Value: Comment has no article. Exception Location: /Users/Koitaro/.local/share/virtualenvs/MMBlog-58h299OP/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py in __get__, line 188 Python Executable: /Users/Koitaro/.local/share/virtualenvs/MMBlog-58h299OP/bin/python I tried other listed attributes, but seems like I could not find 'article' information. When I set the article field and choose an article, I get like 'article': ['2']. Regarding user, by adding form.instance.author = self.request.user, 'author' was automatically set without choosing it in the form. But, I did not see any author information when I tried several print(self.request.POST.XXX) thing. When I tried print(self.request.user), the user was printed in terminal. But, when I tried print(self.request.POST.user), I got an error like below. AttributeError at /articles/2/comment/ 'QueryDict' object has no attribute 'user' Request Method: POST Request URL: http://127.0.0.1:8000/articles/2/comment/ Django Version: 2.1.5 Exception Type: AttributeError Exception Value: 'QueryDict' object has no attribute 'user' When I set the article field, and choose an article in the comment form, I tried print(form.instance.article). Then, the article I chose was printed in the terminal. So, seems like form.instance.article is correct. But how can I set the right part? form.instance.article = self.response.X??? Where is the user information? I successfully can access to user by self.request.user, but currently I have no idea how to access to article information. Sorry, any advice I can try would be really appreciated! Looking forward to hearing advice. Best regards, Nori On Saturday, April 27, 2019 at 10:41:14 PM UTC-4, SimpleHumble wrote: > > The best way to debug it is add a print function with dir function just > before the error occurring line and see what are available attributes in > request.POST object like this print(dir("", request.POST, > "")) . Also without dir function will show what is available in > POST. > Look at the terminal after running development server and your action to > trigger error, see what are th
Re: Question about form_valid: how to automatically set multiple fields when users input data via CreateView supported form?
Hi, Britto, Wow, it's working as expected! Thank you so much. (*So sorry, one more question below, please find it!*) Basically, you added blank=True for author field and article field in Comment model. In this way, I don't need to set author/article field in CommentCreateView. Instead, we have post function to pass around args and kwargs such as pk. You created form.py and author and article fields will be automatically selected via post function. I checked admin site and comments I made were successfully saved in database now! New views.py class ArticleCommentCreateView(LoginRequiredMixin, CreateView): model = Comment template_name = 'article_comment_new.html' fields = ('comment',) # I don't need 'article' field here, because I set blank=True in Comment model login_url = 'login' success_url = "/" def post(self, request, *args, **kwargs): pk = kwargs['pk'] form = CommentForm(request.POST, pk) if form.is_valid(): new_comment = form.save(commit=False) new_comment.author = request.user new_comment.article = Article.objects.get(id=pk) new_comment.save() return HttpResponseRedirect('/') ** By the way, one last thing I wanted to do on top of what we did here is that I wanted to display all comments associated with each article. I have been trying to take data from Comment database, but I am not successful about it. I am able to take out article data by using *object_list.* *But I cannot do the same thing for comments.* I still set related_name='comment' in Comment model. With this related_name, *{% for comment in article.comments %} *worked in previous program. But now, I cannot take out comment data from database. Sorry many questions and stealing your time. I really appreciate your advice. P.S. I run shell in my terminal by typing python manage.py shell. I did from article.models import Comment and I did Comment.objects.all(), then I got all comments printed in my terminal. I read somewhere in Django docs, saying that I can implement this kind of query in django program. But I also read that this is not best practice in Django if I remember correctly. Sorry, I am looking forward to any advice to take out Comment data and display them in the template. Best regards, Nori Here is article_list.html {% extends 'base.html' %} {% block title %}Articles{% endblock title %} {% block content %} * {% for article in object_list %}* {{ article.title }} · by {{ article.author }} | {{ article.date }} {{ article.body }} Edit Delete * {% for comment in article.comments %} # this one doesn't work now.* {{ comment.author }} · {{ comment }} {% endfor %} {% endfor %} {% endblock content %} On Sunday, April 28, 2019 at 3:35:23 PM UTC-4, SimpleHumble wrote: > > Sorry there was a mistake in previous mail please ignore. > form_valid function will not work use post function above it in > ArticleCommentCreateView > Find attached file for reference, > > > Regards > Britto > > > On Mon, 29 Apr 2019 at 00:54, Britto . > > wrote: > >> There was few changes made to template, models and view. Find attached >> zip file. >> >> in ArticleCommentCreateView added a post function to test first also a >> supporting forms.py now commented it. >> form_valid function working fine after added **kwargs parameter. >> >> You could always use a requirements file while sharing code files. For >> that use pip freeze > requirements.txt command. >> >> >> Regards >> Britto >> >> >> On Sun, 28 Apr 2019 at 20:04, Atsunori Kaneshige > > wrote: >> >>> Hi Britto, >>> >>> Thank you! Let me try that. >>> >>> Also, please find the attached file. >>> This is whole thing I have. >>> I did not use anything like docker. You might need some installation. >>> But I guess, after installing django by pipenv install django==2.1.5 in >>> the directory and pipenv shell, I hope you can run the program with python >>> manage.py runserver. >>> >>> I think, you need to create superuser. >>> Then you will be able to make a comment to any article. >>> Right now, I don't have link to go to comment form, so you need to type >>> url directly. >>> You will need to post some articles and then you can make comments on >>> them. >>> Please look at urls.py too see what url you need to put to go to comment >>> form. >>&
Re: Question about form_valid: how to automatically set multiple fields when users input data via CreateView supported form?
Hi, Britto, Sorry for my late reply. Thank you so much! I learnt a lot. Looks like you created a function called get_context_data and put all comment data from Comment database into context with key 'comments'. You then called 'comments' in the template. Now I don't need reated_name='comment' in models.py To upload images, MEDIA_URL and MEDIA_ROOT are configured in settings.py and urls.py image field is added accordingly in models.py Thank you very much! I will keep adding features to make my first blog app! Best regards, Nori On Monday, April 29, 2019 at 11:12:08 AM UTC-4, SimpleHumble wrote: > > Find attached final version with image upload too. You need to pip install > pillow this to work. > > > Regards > Britto > > > On Mon, 29 Apr 2019 at 16:17, Britto . > > wrote: > >> Find attached zip for the comments version. Added comments to context of >> ListView then displayed it in template. >> Always think about Function Based View first then convert it to Class >> Based View, it would help you learn well. >> >> >> Regards >> Britto >> >> >> On Mon, 29 Apr 2019 at 03:45, Atsunori Kaneshige > > wrote: >> >>> Hi, Britto, >>> >>> Let me attach current looking. >>> Now I am trying to display all related comments blow each article. >>> I guess I need to add correct logic in article_list.html. >>> >>> Please find pics too. >>> >>> Sorry, any advice would be really appreciated. >>> >>> Best regards, >>> >>> Nori >>> >>> >>> On Sunday, April 28, 2019 at 6:06:37 PM UTC-4, Atsunori Kaneshige wrote: >>>> >>>> Hi, Britto, >>>> >>>> Wow, it's working as expected! >>>> Thank you so much. (*So sorry, one more question below, please find >>>> it!*) >>>> >>>> Basically, you added blank=True for author field and article field in >>>> Comment model. >>>> In this way, I don't need to set author/article field in >>>> CommentCreateView. >>>> >>>> Instead, we have post function to pass around args and kwargs such as >>>> pk. >>>> You created form.py and author and article fields will be automatically >>>> selected via post function. >>>> I checked admin site and comments I made were successfully saved in >>>> database now! >>>> >>>> New views.py >>>> >>>> class ArticleCommentCreateView(LoginRequiredMixin, CreateView): >>>> model = Comment >>>> template_name = 'article_comment_new.html' >>>> fields = ('comment',) >>>> # I don't need 'article' field here, because I set blank=True in >>>> Comment model >>>> login_url = 'login' >>>> success_url = "/" >>>> >>>> def post(self, request, *args, **kwargs): >>>> pk = kwargs['pk'] >>>> form = CommentForm(request.POST, pk) >>>> if form.is_valid(): >>>> new_comment = form.save(commit=False) >>>> new_comment.author = request.user >>>> new_comment.article = Article.objects.get(id=pk) >>>> new_comment.save() >>>> return HttpResponseRedirect('/') >>>> >>>> ** >>>> By the way, one last thing I wanted to do on top of what we did here is >>>> that I wanted to display all comments associated with each article. >>>> I have been trying to take data from Comment database, but I am not >>>> successful about it. >>>> >>>> I am able to take out article data by using *object_list.* >>>> *But I cannot do the same thing for comments.* >>>> >>>> I still set related_name='comment' in Comment model. >>>> With this related_name, *{% for comment in article.comments %} *worked >>>> in previous program. >>>> But now, I cannot take out comment data from database. >>>> >>>> Sorry many questions and stealing your time. >>>> I really appreciate your advice. >>>> >>>> P.S. >>>> I run shell in my terminal by typing python manage.py shell. >>>> I did from article.models import Comment >>>> and I did Comment.objects.all(), then I got all comments printed in my &g