Skip to content

fix: login_required import and comment author assignment (#140, #118) #186

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions en/homework_create_more_models/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ Currently, we only have a Post model. What about receiving some feedback from yo
Let's open `blog/models.py` and append this piece of code to the end of file:

```python
from django.conf import settings

class Comment(models.Model):
post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=200)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
Expand Down Expand Up @@ -140,7 +142,7 @@ class CommentForm(forms.ModelForm):

class Meta:
model = Comment
fields = ('author', 'text',)
fields = ('text',)
```

Remember to import the Comment model, changing the line:
Expand Down Expand Up @@ -178,24 +180,27 @@ Refresh the page, and we get a different error!
To fix this error, add this view to `blog/views.py`:

```python
@login_required
def add_comment_to_post(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.author = request.user
comment.save()
return redirect('post_detail', pk=post.pk)
else:
form = CommentForm()
return render(request, 'blog/add_comment_to_post.html', {'form': form})
```

Remember to import `CommentForm` at the beginning of the file:
Remember to import `CommentForm` and `login_required` at the beginning of the file:

```python
from .forms import PostForm, CommentForm
from django.contrib.auth.decorators import login_required
```


Expand Down Expand Up @@ -285,21 +290,26 @@ Now, you should see `AttributeError`. To fix this error, add these views in `blo
@login_required
def comment_approve(request, pk):
comment = get_object_or_404(Comment, pk=pk)
if comment.post.author != request.user:
raise PermissionDenied
comment.approve()
return redirect('post_detail', pk=comment.post.pk)

@login_required
def comment_remove(request, pk):
comment = get_object_or_404(Comment, pk=pk)
if comment.author != request.user and comment.post.author != request.user:
raise PermissionDenied
comment.delete()
return redirect('post_detail', pk=comment.post.pk)
```


You'll need to import `Comment` at the top of the file:
You'll need to import `Comment` and `PermissionDenied` at the top of the file:

```python
from .models import Post, Comment
from django.core.exceptions import PermissionDenied
```

Everything works! There is one small tweak we can make. In our post list page -- under posts -- we currently see the number of all the comments the blog post has received. Let's change that to show the number of *approved* comments there.
Expand Down
18 changes: 14 additions & 4 deletions es/homework_create_more_models/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ Actualmente, solamente tenemos un modelo de Post, ¿Qué si queremos recibir ret
Vamos a abrir `blog/models.py` y pega esta pieza de código al final del archivo:

```python
from django.conf import settings

class Comment(models.Model):
post = models.ForeignKey('blog.Post', related_name='comments', on_delete=models.CASCADE)
author = models.CharField(max_length=200)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
Expand Down Expand Up @@ -142,7 +144,7 @@ class CommentForm(forms.ModelForm):

class Meta:
model = Comment
fields = ('author', 'text',)
fields = ('text',)
```

Recuerda importar el modelo Comentario, cambiando la línea:
Expand Down Expand Up @@ -180,24 +182,27 @@ url(r'^post/(?P<pk>\d+)/comment/$', views.add_comment_to_post, name='add_comment
Para agregar este error, agrega esto a `blog/views.py`:

```python
@login_required
def add_comment_to_post(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.author = request.user
comment.save()
return redirect('post_detail', pk=post.pk)
else:
form = CommentForm()
return render(request, 'blog/add_comment_to_post.html', {'form': form})
```

Recuerda importar `CommentForm` al comienzo del archivo:
Recuerda importar `CommentForm` y `login_required` al comienzo del archivo:

```python
from .forms import PostForm, CommentForm
from django.contrib.auth.decorators import login_required
```

Ahora vamos a los detalles de la página y deberíamos ver el botón "Add Comment":
Expand Down Expand Up @@ -279,20 +284,25 @@ Ahora debereias ver un `AttributeError`. Para arreglar este error, agrega las si
@login_required
def comment_approve(request, pk):
comment = get_object_or_404(Comment, pk=pk)
if comment.post.author != request.user:
raise PermissionDenied
comment.approve()
return redirect('post_detail', pk=comment.post.pk)

@login_required
def comment_remove(request, pk):
comment = get_object_or_404(Comment, pk=pk)
if comment.author != request.user and comment.post.author != request.user:
raise PermissionDenied
comment.delete()
return redirect('post_detail', pk=comment.post.pk)
```

Necesitas importar `Comment` al comienzo del archivo:
Necesitas importar `Comment` y `PermissionDenied` al comienzo del archivo:

```python
from .models import Post, Comment
from django.core.exceptions import PermissionDenied
```

¡Todo funciona! Hay un pequeño cambio que podemos hacer. en nuestra página de lista -- debajo de posts -- actualmente vemos el número de los comentarios que el post ha recibifo. Vamos a cambiar esto para ver el número de comentarios aprobados.
Expand Down
18 changes: 14 additions & 4 deletions fa/homework_create_more_models/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
فایل `blog/models.py` را باز کنید و این قطعه کد را به آن اضافه کنید:

```python
from django.conf import settings

class Comment(models.Model):
post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=200)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
Expand Down Expand Up @@ -139,7 +141,7 @@ class CommentForm(forms.ModelForm):

class Meta:
model = Comment
fields = ('author', 'text',)
fields = ('text',)
```

به یاد داشته باشید که مدل کامنت را فراخوانی کنید، خط زیر را پیدا کنید:
Expand Down Expand Up @@ -177,24 +179,27 @@ path('post/<int:pk>/comment/', views.add_comment_to_post, name='add_comment_to_p
برای حل این مشکل به فایل `blog/views.py` بروید و ویو زیر را به آن اضافه کنید:

```python
@login_required
def add_comment_to_post(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.author = request.user
comment.save()
return redirect('post_detail', pk=post.pk)
else:
form = CommentForm()
return render(request, 'blog/add_comment_to_post.html', {'form': form})
```

به یاد داشته باشید که `CommentForm` را در ابتدای فایل فراخوانی کنید:
به یاد داشته باشید که `CommentForm` و `login_required` را در ابتدای فایل فراخوانی کنید:

```python
from .forms import PostForm, CommentForm
from django.contrib.auth.decorators import login_required
```

حالا در صفحه جزییات پست، باید کلید "Add Comment" را ببینید.
Expand Down Expand Up @@ -277,21 +282,26 @@ path('comment/<int:pk>/remove/', views.comment_remove, name='comment_remove'),
@login_required
def comment_approve(request, pk):
comment = get_object_or_404(Comment, pk=pk)
if comment.post.author != request.user:
raise PermissionDenied
comment.approve()
return redirect('post_detail', pk=comment.post.pk)

@login_required
def comment_remove(request, pk):
comment = get_object_or_404(Comment, pk=pk)
if comment.author != request.user and comment.post.author != request.user:
raise PermissionDenied
comment.delete()
return redirect('post_detail', pk=comment.post.pk)
```


لازم است که مدل `Comment` را در ابتدای فایل فراخوانی کنید:
لازم است که مدل `Comment` و `PermissionDenied` را در ابتدای فایل فراخوانی کنید:

```python
from .models import Post, Comment
from django.core.exceptions import PermissionDenied
```

همه چیز کار می‌کند! فقط یک تغییر کوچک باقی مانده که انجام بدهیم. در صفحه لیست پست‌ها، ما تعداد همه کامنت‌هایی که هر پست دریافت کرده را می‌بینیم. بیایید آن را به تعداد کامنت‌های *تأییدشده* تغییر بدهیم.
Expand Down
18 changes: 14 additions & 4 deletions ja/homework_create_more_models/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
`blog/models.py`を開き、このコードをファイルの最後に追加しましょう:

```python
from django.conf import settings

class Comment(models.Model):
post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=200)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
Expand Down Expand Up @@ -140,7 +142,7 @@ class CommentForm(forms.ModelForm):

class Meta:
model = Comment
fields = ('author', 'text',)
fields = ('text',)
```

コメントモデルをインポートすることを忘れないでください。以下の行を変更して:
Expand Down Expand Up @@ -178,24 +180,27 @@ path('post/<int:pk>/comment/', views.add_comment_to_post, name='add_comment_to_p
こちらのエラーを修正するために、`blog/views.py`に以下のビューを追加してください:

```python
@login_required
def add_comment_to_post(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.author = request.user
comment.save()
return redirect('post_detail', pk=post.pk)
else:
form = CommentForm()
return render(request, 'blog/add_comment_to_post.html', {'form': form})
```

`CommentForm`をファイルの先頭でインポートすることを忘れないでください:
`CommentForm` , `login_required`をファイルの先頭でインポートすることを忘れないでください:

```python
from .forms import PostForm, CommentForm
from django.contrib.auth.decorators import login_required
```

今、詳細投稿ページで”Add Comment”というボタンが表示されています。
Expand Down Expand Up @@ -278,20 +283,25 @@ path('comment/<int:pk>/remove/', views.comment_remove, name='comment_remove'),
@login_required
def comment_approve(request, pk):
comment = get_object_or_404(Comment, pk=pk)
if comment.post.author != request.user:
raise PermissionDenied
comment.approve()
return redirect('post_detail', pk=comment.post.pk)

@login_required
def comment_remove(request, pk):
comment = get_object_or_404(Comment, pk=pk)
if comment.author != request.user and comment.post.author != request.user:
raise PermissionDenied
comment.delete()
return redirect('post_detail', pk=comment.post.pk)
```

ファイルの先頭に `Comment`をインポートする必要があります:
ファイルの先頭に `Comment`,`PermissionDenied` をインポートする必要があります:

```python
from .models import Post, Comment
from django.core.exceptions import PermissionDenied
```

すべて動作します!私たちにできる小さな微調整があります。投稿一覧ページ(の投稿の下)には、現在、投稿が受け取ったすべてのコメントの数が表示されます。*承認された* コメントの数を表示するように変更しましょう。
Expand Down
18 changes: 14 additions & 4 deletions ko/homework_create_more_models/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
`blog/models.py` 파일을 열어, 파일의 맨 마지막에 아래 코드를 추가해주세요.

```python
from django.conf import settings

class Comment(models.Model):
post = models.ForeignKey('blog.Post', related_name='comments', on_delete=models.CASCADE)
author = models.CharField(max_length=200)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
Expand Down Expand Up @@ -148,7 +150,7 @@ class CommentForm(forms.ModelForm):

class Meta:
model = Comment
fields = ('author', 'text',)
fields = ('text',)
```

파일 맨 처음에 Comment 모델을 import 하는 것을 잊지 마세요.
Expand Down Expand Up @@ -187,12 +189,14 @@ url(r'^post/(?P<pk>\d+)/comment/$', views.add_comment_to_post, name='add_comment
에러를 해결하려면 `blog/views.py` 파일에서 새로운 뷰를 추가해야해요.

```python
@login_required
def add_comment_to_post(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.author = request.user
comment.post = post
comment.save()
return redirect('post_detail', pk=post.pk)
Expand All @@ -201,10 +205,11 @@ def add_comment_to_post(request, pk):
return render(request, 'blog/add_comment_to_post.html', {'form': form})
```

이번에도 파일 맨 처음에 `CommentForm` 을 import 하는 것을 잊지 마세요.
이번에도 파일 맨 처음에 `CommentForm` , `login_required` 을 import 하는 것을 잊지 마세요.

```python
from .forms import PostForm, CommentForm
from django.contrib.auth.decorators import login_required
```

이제 post_detail 페이지로 가보면, "Add comment" 버튼을 확인할 수 있을 거에요.
Expand Down Expand Up @@ -286,20 +291,25 @@ url(r'^comment/(?P<pk>\d+)/remove/$', views.comment_remove, name='comment_remove
@login_required
def comment_approve(request, pk):
comment = get_object_or_404(Comment, pk=pk)
if comment.post.author != request.user:
raise PermissionDenied
comment.approve()
return redirect('post_detail', pk=comment.post.pk)

@login_required
def comment_remove(request, pk):
comment = get_object_or_404(Comment, pk=pk)
if comment.author != request.user and comment.post.author != request.user:
raise PermissionDenied
comment.delete()
return redirect('post_detail', pk=comment.post.pk)
```

파일 맨 처음에 `Comment`를 import하는 것을 잊지 않았겠죠.
파일 맨 처음에 `Comment`,`PermissionDenied` 를 import하는 것을 잊지 않았겠죠.

```python
from .models import Post, Comment
from django.core.exceptions import PermissionDenied
```

모든 것이 잘 작동되네요! 하지만 마지막 한 가지가 남았어요. 현재 post_list 페이지에서는 등록된 모든 댓글의 개수가 보이는데요. *승인된* 댓글의 개수만 보이게 수정해봅시다.
Expand Down