Create Forms And Update Values Received to Database in Django
- Create a file named forms.html in templates > mainApp and add the following to it.
<!DOCTYPE html><html>
<head>
<meta charset="utf-8"><title>Sign Up</title><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"></head>
<body>
<div class="container"><h1>Sign Up</h1><form method="POST">{{ form.as_p }} {% csrf_token %} <input type="submit" class="btn btn-primary" value="Submit"></form>
</div>
</body>
</html>
- In urls.py in Project Folder add the following line to urlpatterns:
url(r'^signup/', views.signup, name='signup')
- In views.py in mainApp add the following function
def signup(request): form = NewUserForm() if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): form.save(commit=True) return users(request) else: print("ERROR: FORM INVALID") return render(request, 'mainApp/signup.html', {'form':form})
- Add the following to urls.py file under mainApp folder in urlpatterns list.
url(r'^signup', views.signup, name='signup')
- Create a file named forms.py in mainApp and add the following code to it.
from django import forms from mainApp.models import User class NewUserForm(forms.ModelForm): class Meta: model = User fields = '__all__'
- Now the form is ready and connected to database. Run the server to test it in browser.
python manage.py runserver
- See you in the next blog.
Comments
Post a Comment