DEV Community

Sami Ullah Saleem
Sami Ullah Saleem

Posted on

Django Notes

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
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
]
Enter fullscreen mode Exit fullscreen mode
  1. Add the view function in your app urls.py file
  2. Create a templates folder in your app folder
  3. Add app templates folder in settings.py file in project folder using TEMPLATES list
  4. Add the path using the following code
'DIRS': [os.path.join(BASE_DIR, 'myapp/templates')],
Enter fullscreen mode Exit fullscreen mode
  1. First user autheticate then view the page
def index(request):
    if request.user.is_authenticated:
        print(request.user)
        return render(request, 'index.html')
    else:
        return redirect('login')
Enter fullscreen mode Exit fullscreen mode
  1. How to create a user and check if the admin is login or not
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')
Enter fullscreen mode Exit fullscreen mode
  1. redirect takes on argument of the funtion where you want to redirect.
  2. While render is the function which render the page
  3. For Authentication, Use
from django.contrib.auth.forms import UserCreationForm,AuthenticationForm
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
Enter fullscreen mode Exit fullscreen mode
  1. If you want that a view should login then call use the below code before the view function or class line
@login_required(login_url='/loginpage')
Enter fullscreen mode Exit fullscreen mode
  1. 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
<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>
Enter fullscreen mode Exit fullscreen mode

Here is the python login view funtion with next in query string

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})  
Enter fullscreen mode Exit fullscreen mode

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

            user = form.get_user()
            login(request, user)
Enter fullscreen mode Exit fullscreen mode

and after it we will check if the next is coming then we will redirect the user after login to that page

Top comments (0)