---
description: >-
  We have to start protecting our views against non-authorized users. So far we
  have the following view to start new posts:
---

# Protecting View

### Views.py

```python
from django.contrib.auth.decorators import login_required

@login_required
def new_topic(request, pk):
pass
```

### If User Logged In

### Views.py

```python
from django.contrib.auth import login, authenticate, logout
  
    if request.method == 'GET':
        if request.user.is_authenticated:
            return redirect('posts')
```

### Html Template

#### Example 1 : Show Login/Logout Button Based On User Loggin/logout

```html
  		{%if request.user.is_authenticated %}
  			<span>Hi {{ request.user.username | title }}</span>
  			<a href="{% url 'logout' %}">Logout</a>
  		{%else%}
  			<a href="{% url 'login' %}">Login</a>
  		{%endif%}

```

#### Example 2 : Show post Delete / Edit Option Based On User Loggin/Logout

```
		{% if request.user.is_authenticated %}
		<p>
			<a href="{% url 'post-edit' post.id %}">Edit</a> 
			<a href="{% url 'post-delete' post.id%}">Delete</a>
		</p>
		{% endif %}
```

### Only Owner Can Delete/Edit Post

```
@login_required    
def edit_post(request, id):
    queryset = Post.objects.filter(author=request.user)
    post = get_object_or_404(queryset, pk=id)

    if request.method == 'GET':
        context = {'form': PostForm(instance=post), 'id': id}
        return render(request,'blog/post_form.html',context)
```
