Django Notes
Tags: python, django, news, programming
Published: 2022-12-31 17:18:00

# Django Developer Notes

1. Create a project 
2. Create an app. A project can have multiple apps
3. Register that app in INSTALLED_APPS list in settings.py folder
4. Create a url.py file in your project folder because it might not contained it.
5. Add this file in your projects url file as follow
6. Create a view.py file in your app folder
7. Create a function in your view.py file
8. Create a urls.py file in your app folder
9. Add the url in your app urls.py file

```python 
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('demo',include('demoapp.urls')) # demoapp.urls is url file in demoapp folder which contains all the urls for that app
]
```
10. Add the view function in your app urls.py file
11. Create a templates folder in your app folder
12. Add app templates folder in settings.py file in project folder using TEMPLATES list
13. Add the path using the following code

```python
'DIRS': [os.path.join(BASE_DIR, 'myapp/templates')],
```
14. First user autheticate then view the page
```python
def index(request):
    if request.user.is_authenticated:
        print(request.user)
        return render(request, 'index.html')
    else:
        return redirect('login')
```
15. How to create a user and check if the admin is login or not
```python
def createUser(request):
    if request.user.is_authenticated:
        if request.method == "POST":
            username = request.POST['username']
            password = request.POST['password']
            email = request.POST['email']
            user = User.objects.create_user(username, email, password)
            user.save()
            return redirect('admin/login')
        else:
            return render(request, 'createUser.html')
    else:
        return redirect('admin/login')
```
16. redirect takes on argument of the funtion where you want to redirect.
17. While render is the function which render the page
18. For Authentication, Use 
```python
from django.contrib.auth.forms import UserCreationForm,AuthenticationForm
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
```
19. If you want that a view should login then call use the below code before the view function or class line
```python
@login_required(login_url='/loginpage')
```
20. As you can see in the above line, I am telling to login but what will happen after login. We have to redirect the user to something and that redirection will come in the url with next query string. We have to build the logic in both html and python login view
### Here is the Html Login Page
```html 
<body>
    <form action={% url 'personalDiary:login' %} method="post">
        {% csrf_token %}
        {{ form }}
        {% if request.GET.next %}
            <input type="hidden" name="next" value="{{request.GET.next}}">
        {% endif %}
        <input type="submit" value="Login">
    </form>
</body>
```
### Here is the python login view funtion with next in query string
```python
def login_view(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            if 'next' in request.POST:
                return redirect(request.POST['next'])
            else:
                return render(request,'createpage.html')
        else:
            return render(request, 'loginpage.html', {'form': form})
    else:
        form = AuthenticationForm(request)
        return render(request, 'loginpage.html', {'form': form})  
```
We have to create a form using AuthenticationForm function and then send it to our login page which is loginpage.html in this  case. If we are getting a post request then first get the data using request.post and send it to data variable in AuthenticationForm(data=request.POST) function and then create a form. After that we will check if the form is valid then login by using the below function
```python
            user = form.get_user()
            login(request, user)
```
and after it we will check if the next is coming then we will redirect the user after login to that page