Re: Question about form_valid: how to automatically set multiple fields when users input data via CreateView supported form?

2019-11-22 Thread techguy
SimpleHumble I need your help with this common commment fault 

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.
>>>
>>> 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 >>> }} > 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,  
 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.user
>  return 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.
>>
>>
>> Regards
>> Britto
>>
>>
>> On Sun, 28 Apr 2019 at 09:30, Atsunori Kaneshige  
>> 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', 

Re: Question about form_valid: how to automatically set multiple fields when users input data via CreateView supported form?

2019-04-29 Thread Atsunori Kaneshige
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 
 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 %}


>

Re: Question about form_valid: how to automatically set multiple fields when users input data via CreateView supported form?

2019-04-28 Thread Atsunori Kaneshige
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.
>>>
>>> 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

Re: Question about form_valid: how to automatically set multiple fields when users input data via CreateView supported form?

2019-04-28 Thread Britto .
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 
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, 
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.user
>  return 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.
>>
>>
>> Regards
>> Britto
>>
>>
>> On Sun, 28 Apr 2019 at 09:30, Atsunori Kaneshige 
>> 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.
>>>
>>>
>>> >> {'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 

Re: Question about form_valid: how to automatically set multiple fields when users input data via CreateView supported form?

2019-04-28 Thread chirag soni
Please share the form and form template as well.

On Sun, 28 Apr 2019, 02:37 Atsunori Kaneshige  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.
>

-- 
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/CABCRpYPSLS1tYJRv23LiQM6LfaFQhvLbinVbXoX2cnnYmaDrcA%40mail.gmail.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?

2019-04-27 Thread Britto .
set form.instance.article = request.POST.get('article')
and add article in fields too like fields = ('comment', 'article')
it should work flawlessly.


Regards
Britto


On Sun, 28 Apr 2019 at 09:30, Atsunori Kaneshige  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.
>
>
>  ['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.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 the attributes available for your request.
>>
>> Probably you have to set form.instance.article = request.POST.get('article')
>> would work.
>>
>> Regards
>> Britto
>>
>>
>> On Sun, 28 Apr 2019 at 02:56, Atsunori Kaneshige 
>> wrote:
>>
>>> Sorry, when

Re: Question about form_valid: how to automatically set multiple fields when users input data via CreateView supported form?

2019-04-27 Thread Atsunori Kaneshige
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 the attributes available for your request.
>
> Probably you have to set form.instance.article = request.POST.get('article') 
> would work.
>
> Regards
> Britto
>
>
> On Sun, 28 Apr 2019 at 02:56, Atsunori Kaneshige  > 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, l

Re: Question about form_valid: how to automatically set multiple fields when users input data via CreateView supported form?

2019-04-27 Thread Britto .
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.

Regards
Britto


On Sun, 28 Apr 2019 at 02:56, Atsunori Kaneshige  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 +
>
>
> 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://group

Re: Question about form_valid: how to automatically set multiple fields when users input data via CreateView supported form?

2019-04-27 Thread Atsunori Kaneshige
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.


Question about form_valid: how to automatically set multiple fields when users input data via CreateView supported form?

2019-04-27 Thread Atsunori Kaneshige
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.