Horje
Build a Flashcards using Django

Flashcards are an effective tool for studying and memorizing information. Building a flashcards application using Django allows you to create a robust, scalable, and easy-to-maintain web application. This article will guide you through the process of creating a flashcard app using Django. In this article, we will guide you through creating a Language-Flashcards using Django.

Language Flashcards using Django

Below, is the step-by-step Implementation of the language Flashcards using Django:

Starting the Project Folder

To start the project use this command

django-admin startproject flashcards
cd flashcards

To start the app use this command

python manage.py startapp home

Now add this app to the ‘settings.py’

INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"home",
]

Setting Necessary Files

home/models.py: Below, models.py file defines Django models including UserProfile, Category, Flashcard. Each model encapsulates specific attributes and relationships for user profiles,question,answer and category. These models form the foundation for structuring data.

Python
# flashcards/models.py
from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Flashcard(models.Model):
    question = models.CharField(max_length=255)
    answer = models.TextField()
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

    def __str__(self):
        return self.question

home/forms.py: Below, Django form file in the language_flashcards directory defines Django forms such as FlashcardForm,CategoryForm.

Python
from django import forms
from .models import Flashcard,Category

class FlashcardForm(forms.ModelForm):
    class Meta:
        model = Flashcard
        fields = ['question', 'answer', 'category']

class CategoryForm(forms.ModelForm):
    class Meta:
        model = Category
        fields = ['name']

home/views.py: Below code contains Django views.

Python
# flashcards/views.py

from django.shortcuts import render, get_object_or_404, redirect
from .models import Flashcard
from .forms import FlashcardForm

def flashcard_list(request):
    flashcards = Flashcard.objects.all()
    return render(request, 'flashcard_list.html', {'flashcards': flashcards})

def flashcard_detail(request, pk):
    flashcard = get_object_or_404(Flashcard, pk=pk)
    return render(request, 'flashcard_detail.html', {'flashcard': flashcard})

def flashcard_new(request):
    if request.method == "POST":
        form = FlashcardForm(request.POST)
        if form.is_valid():
            flashcard = form.save()
            return redirect('flashcard_detail', pk=flashcard.pk)
    else:
        form = FlashcardForm()
    return render(request, 'flashcard_edit.html', {'form': form})

def flashcard_edit(request, pk):
    flashcard = get_object_or_404(Flashcard, pk=pk)
    if request.method == "POST":
        form = FlashcardForm(request.POST, instance=flashcard)
        if form.is_valid():
            flashcard = form.save()
            return redirect('flashcard_detail', pk=flashcard.pk)
    else:
        form = FlashcardForm(instance=flashcard)
    return render(request, 'flashcard_edit.html', {'form': form})

def flashcard_delete(request, pk):
    flashcard = get_object_or_404(Flashcard, pk=pk)
    if request.method == 'POST':
        flashcard.delete()
        return redirect('flashcard_list')
    return render(request, 'flashcard_confirm_delete.html', {'flashcard': flashcard})

from .forms import CategoryForm

def category_new(request):
    if request.method == "POST":
        form = CategoryForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('flashcard_list')
    else:
        form = CategoryForm()
    return render(request, 'category_form.html', {'form': form})

Creating GUI

templates/create_community_post : This HTML template renders a form to create a new community post in the Language flashcards. It includes fields for the post title and content, with validation to ensure they are required.

templates/base.html:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Language Flashcards</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="{% url 'flashcard_list' %}">Flashcards</a>
    </nav>
    <div class="container mt-4">
        {% block content %}
        {% endblock %}
    </div>
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>

templates/category_form.html:

HTML
{% extends 'base.html' %}

{% block content %}
<h1>New Category</h1>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="btn btn-primary">Save</button>
    <a class="btn btn-secondary" href="{% url 'flashcard_list' %}">Cancel</a>
</form>
{% endblock %}

templates/flashcards_delete.html

HTML
{% extends 'base.html' %}

{% block content %}
<h1>Confirm Delete</h1>
<p>Are you sure you want to delete this flashcard?</p>
<p><strong>Question:</strong> {{ flashcard.question }}</p>
<form method="post">
    {% csrf_token %}
    <button type="submit" class="btn btn-danger">Delete</button>
    <a class="btn btn-secondary" href="{% url 'flashcard_list' %}">Cancel</a>
</form>
{% endblock %}

templates/flashcards_detail.html

HTML
{% extends 'base.html' %}

{% block content %}
<h1>Flashcard Detail</h1>
<p><strong>Question:</strong> {{ flashcard.question }}</p>
<p><strong>Answer:</strong> {{ flashcard.answer }}</p>
<p><strong>Category:</strong> {{ flashcard.category.name }}</p>
<a class="btn btn-secondary" href="{% url 'flashcard_list' %}">Back to list</a>
<a class="btn btn-warning" href="{% url 'flashcard_edit' flashcard.pk %}">Edit</a>
<form method="post" action="{% url 'flashcard_delete' flashcard.pk %}" style="display:inline;">
    {% csrf_token %}
    <button type="submit" class="btn btn-danger">Delete</button>
</form>
{% endblock %}

templates/flashcards_edit.html:

HTML
{% extends 'base.html' %}

{% block content %}
<h1>{% if form.instance.pk %}Edit{% else %}New{% endif %} Flashcard</h1>
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="btn btn-primary">{% if form.instance.pk %}Update{% else %}Create{% endif %}</button>
    <a class="btn btn-secondary" href="{% url 'flashcard_list' %}">Cancel</a>
</form>
{% endblock %}

templates/flashcards_list.html

HTML
{% extends 'base.html' %}

{% block content %}
<h1>Flashcards</h1>
<a class="btn btn-primary mb-3" href="{% url 'flashcard_new' %}">Add New Flashcard</a>
<a class="btn btn-primary mb-3" href="{% url 'category_new' %}">Add New Category</a>
<table class="table table-bordered">
    <thead>
        <tr>
            <th>Question</th>
            <th>Category</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        {% for flashcard in flashcards %}
        <tr>
            <td>{{ flashcard.question }}</td>
            <td>{{ flashcard.category.name }}</td>
            <td>
                <a class="btn btn-info btn-sm" href="{% url 'flashcard_detail' flashcard.pk %}">View</a>
                <a class="btn btn-warning btn-sm" href="{% url 'flashcard_edit' flashcard.pk %}">Edit</a>
                <form method="post" action="{% url 'flashcard_delete' flashcard.pk %}" style="display:inline;">
                    {% csrf_token %}
                    <button type="submit" class="btn btn-danger btn-sm">Delete</button>
                </form>
            </td>
        </tr>
        {% endfor %}
    </tbody>
</table>
{% endblock %}

home/urls.py : This urlpatterns list defines paths for the Django project: admin/ for the admin interface and ” for URLs defined in the “home” app

Python
# flashcards/urls.py

from django.urls import path
from . import views

urlpatterns = [
 
    path('', views.flashcard_list, name='flashcard_list'),
    path('flashcard/<int:pk>/', views.flashcard_detail, name='flashcard_detail'),
    path('flashcard/new/', views.flashcard_new, name='flashcard_new'),
    path('flashcard/<int:pk>/edit/', views.flashcard_edit, name='flashcard_edit'),
    path('flashcard/<int:pk>/delete/', views.flashcard_delete, name='flashcard_delete'),
    path('category/new/', views.category_new, name='category_new'),
]

flashcards/urls.py: These urlpatterns in Django project correspond to views.

Python
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include("home.urls"))
] 


admin.py: Here we are registering our models.

Python
# flashcards/admin.py

from django.contrib import admin
from .models import Category, Flashcard

admin.site.register(Category)
admin.site.register(Flashcard)

Deployement of the Project

Run these commands to apply the migrations:

python3 manage.py makemigrations
python3 manage.py migrate

Create the superuser using the below command :

python3 manage.py createsuperuser

Run the server with the help of following command:

python3 manage.py runserver

Output:

Screenshot-(185)Screenshot-(186)Screenshot-(187)Screenshot-(188)

Output Video





Reffered: https://www.geeksforgeeks.org


Python

Related
How to Use CSS in Python Flask How to Use CSS in Python Flask
10 Best Image Processing Libraries for Media Manipulation 10 Best Image Processing Libraries for Media Manipulation
PyVista PolyData PyVista PolyData
Access the Actual Tab Widget of ttk.Notebook in Python Tkinter Access the Actual Tab Widget of ttk.Notebook in Python Tkinter
How to Install Python yfinance using GitHub How to Install Python yfinance using GitHub

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
23