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 <atsunori@umich.edu> 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 = Commenttemplate_name = 'article_comment_new.html'fields = ('comment',)# I don't need 'article' field here, because I set blank=True in Comment modellogin_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.usernew_comment.article = Article.objects.get(id=pk)new_comment.save()return HttpResponseRedirect('/')<One more question>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 Commentand 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,NoriHere is article_list.html{% extends 'base.html' %}{% block title %}Articles{% endblock title %}{% block content %}{% for article in object_list %}<div class="card"><div class="card-header"><span class="font-weight-bold">{{ article.title }}</span> ·<span class="text-muted">by {{ article.author }} |{{ article.date }}</span></div><div class="card-body"><p>{{ article.body }}</p><a href="{% url 'article_edit' article.pk %}">Edit</a><a href="{% url 'article_delete' article.pk %}">Delete</a></div><div class="card-footer">{% for comment in article.comments %} # this one doesn't work now.<p><span class="font-weight-bold">{{ comment.author }} ·</span>{{ comment }}</p>{% endfor %}</div></div><br />{% 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 ArticleCommentCreateViewFind attached file for reference,
RegardsBrittoOn Mon, 29 Apr 2019 at 00:54, Britto . <brit...@gmail.com> 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.
RegardsBrittoOn Sun, 28 Apr 2019 at 20:04, Atsunori Kaneshige <atsu...@umich.edu> 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.Sorry for this confusion.I am still a django beginner, so wish I could know exactly I need to tell you for you to run the program.Thank you very much for your help.Please find the zip file.Best regards,Nori
On Sunday, April 28, 2019 at 10:00:00 AM UTC-4, SimpleHumble wrote:If you don't want to display article and author in the template. Use custom form design instead of {% form.as_p %} tag.Something like <input name={{ form.comment }} value = {{ form.comment }} > this will render only comment field on template. You should not remove those fields as those are required to process form.Share the code as zip will exam it and let you know.On Sun, 28 Apr, 2019, 7:10 PM Atsunori Kaneshige, <atsu...@umich.edu> wrote:Hi Britto,--Thank you for your reply.It's been working fine when I add ('comment', 'article',).The fields for CommentCreateView used to be ('comment', 'article','author',)But I wanted to get rid of 'author' and 'article' from comment form.def form_valid(self, form):form.instance.author = self.request.userreturn super().form_valid(form)On Sunday, April 28, 2019 at 1:10:24 AM UTC-4, SimpleHumble wrote:set form.instance.article = request.POST.get('article')and add article in fields too like fields = ('comment', 'article')it should work flawlessly.
RegardsBrittoOn Sun, 28 Apr 2019 at 09:30, Atsunori Kaneshige <atsu...@umich.edu> wrote:--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.<bound method MultiValueDict.items of <QueryDict: {'csrfmiddlewaretoken': ['qRGlWdPTX9qxpFidwKT8bvY3vWXx5caE2wJZSQTtyWodYSICmW4yMwXG3FAn9oQk'], 'comment': ['I am maru'], 'article': ['2']}>>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.XXXXX???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 the attributes available for your request.Probably you have to set form.instance.article = request.POST.get('article') would work.
RegardsBrittoOn Sun, 28 Apr 2019 at 02:56, Atsunori Kaneshige <atsu...@umich.edu> wrote: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 +0000 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.<models.py>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.titledef get_absolute_url(self):return reverse('article_detail', args=[str(self.id)])class Comment(models.Model): # newarticle = 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.commentdef get_absolute_url(self):return reverse('article_list')<views.py>...(not showing all)#for commentclass ArticleCommentCreateView(LoginRequiredMixin, CreateView):model = Commenttemplate_name = 'article_comment_new.html'fields = ('comment',)login_url = 'login'def form_valid(self, form):form.instance.author = self.request.userform.instance.article = self.request.articlereturn 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...@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/352ed4ec-fcf8-4590-ae0b-9c97e29d80ef%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
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...@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/220604e7-a433-4771-b52e-b9eede1b61e4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
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...@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/2a71817a-10fa-41f5-8514-8c7d952952f6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
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...@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/7720c361-a774-4dd7-94e2-3553cc6408ca%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
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+unsubscribe@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/102f9c87-6872-4cde-84b7-937099b45858%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
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+unsubscribe@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/CAF0v3b4FuGvkXfW9uy2ieZtOHK8p2xV1SGdttrQ%3DP3GUAQy%3DeA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment