create project and app, register app in settings.py
django-admin startproject forms_demo
cd forms_demo
code .
python3 manage.py startapp forms_app
- register this app in
settings.py
.
INSTALLED_APPS = [
# Rest of the apps.....
'forms_app', # <----- your app.
]
write urls.py file
- Write the below contents in
urls.py
- In
forms_demo/urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path("",include("forms_app.urls")),
]
write models.py file
- Write the below contents in
models.py
file.
forms_app/models.py
from django.db import models
# Create your models here.
# Existing Student model
class Student(models.Model):
name = models.CharField(max_length=50)
# email = models.EmailField(unique=False)
def __str__(self):
return self.name
# New Project model
class Project(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='projects')
topic = models.CharField(max_length=200)
languages = models.CharField(max_length=200)
duration = models.PositiveIntegerField(help_text='Duration in months')
def __str__(self):
return f'{self.topic} by {self.student.name}'
register models in admin.py
- Write the below contents in
admin.py
file to register the models.
from django.contrib import admin
from .models import Student,Project
# Register your models here.
admin.site.register(Student)
admin.site.register(Project)
- Write below contents in
forms_app/forms.py
file.
from django import forms
from .models import Project, Student
class ProjectForm(forms.ModelForm):
student_name = forms.CharField(max_length=50, required=True, label='Student Name')
class Meta:
model = Project
fields = ['student_name', 'topic', 'languages', 'duration']
def save(self, commit=True):
student_name = self.cleaned_data['student_name']
student, created = Student.objects.get_or_create(name=student_name)
self.instance.student = student
return super().save(commit=commit)
Write views.py file
- Write the below contents in
forms_app/views.py
file.
from django.shortcuts import render, redirect
from django.contrib import messages
from .models import Project
from .forms import ProjectForm
def register_project(request):
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
form.save()
# return redirect('project_success') # Redirect to a success page or another view
messages.success(request, 'Student successfully added to the course.')
return redirect('register_project')
else:
form = ProjectForm()
return render(request, 'project_form.html', {'form': form})
def project_success(request):
return render(request, 'project_success.html')
Write urls.py file to link the views
from django.urls import path
from . import views
urlpatterns = [
path('register_project/', views.register_project, name='register_project'),
]
Write templates
- Create a templates folder in the project folder not in any apps.
- Register the folder in the templates section of settings.py file by adding this line in the list
'DIRS': [ BASE_DIR / "templates" ],
- add
project_form.html
file in templates directory and write the below contents.
<!DOCTYPE html>
<html>
<head>
<title>Project Registration</title>
</head>
<body>
<h2>Register Project</h2>
<form method="post" action="{% url 'register_project' %}">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register Project</button>
</form>
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
</body>
</html>
make migrations and create superuser
- In terminal make migrations and migrate the database before creating superuser.
- enter
python3 manage.py makemigrations
, after the enter python3 manage.py migrate
- Now crate a superuser with command
python3 manage.py createsuperuser
, Enter the required credentials and create super user.
- Now run the local server and go to this url pattern
http://127.0.0.1:8000/register_project/
- Now you would be able to register the students and see the registered students data in admin panel by logging in as a super user.