Mysql Crud Operations Using Django
Mysql Crud Operations Using Django
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'student_db', # your database name
'USER': 'root', # your database user
'PASSWORD': 'password',# your database password
'HOST': 'localhost',
'PORT': '3306',
}
}
INSTALLED_APPS = [
...
'students',
]
class Student(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(unique=True)
course = models.CharField(max_length=100)
def __str__(self):
return f"{self.first_name} {self.last_name}"
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['first_name', 'last_name', 'email', 'course']
def student_list(request):
students = Student.objects.all()
return render(request, 'students/student_list.html', {'students': students})
def student_create(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()
return redirect('student_list')
else:
form = StudentForm()
return render(request, 'students/student_form.html', {'form': form})
urlpatterns = [
path('', views.student_list, name='student_list'),
path('new/', views.student_create, name='student_create'),
path('<int:pk>/edit/', views.student_update, name='student_update'),
path('<int:pk>/delete/', views.student_delete, name='student_delete'),
]
urlpatterns = [
path('admin/', admin.site.urls),
path('students/', include('students.urls')),
]
students/templates/students/student_list.html:
<!DOCTYPE html>
<html>
<head>
<title>Student List</title>
</head>
<body>
<h1>Students</h1>
<a href="{% url 'student_create' %}">Add Student</a>
<ul>
{% for student in students %}
<li>{{ student.first_name }} {{ student.last_name }} -
{{ student.course }}
<a href="{% url 'student_update' student.pk %}">Edit</a>
<a href="{% url 'student_delete' student.pk %}">Delete</a>
</li>
{% endfor %}
</ul>
</body>
</html>
students/templates/students/student_form.html:
<!DOCTYPE html>
<html>
<head>
<title>Student Form</title>
</head>
<body>
<h1>{% if form.instance.pk %}Edit{% else %}New{% endif %} Student</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
<a href="{% url 'student_list' %}">Back to Student List</a>
</body>
</html>
students/templates/students/student_confirm_delete.html:
<!DOCTYPE html>
<html>
<head>
<title>Delete Student</title>
</head>
<body>
<h1>Are you sure you want to delete {{ student.first_name }}
{{ student.last_name }}?</h1>
<form method="post">
{% csrf_token %}
<button type="submit">Confirm</button>
</form>
<a href="{% url 'student_list' %}">Cancel</a>
</body>
</html>
You can now navigate to http://127.0.0.1:8000/students/ to see the list of students and perform CRUD
operations.