Jul-01-2024, 07:12 AM
(Mar-22-2024, 10:47 AM)Sowmya Wrote: Hi all
I have 3 html pages
index.html - It contains form
result.html - when you click on submit in index.html it will display result.html page in this page we have context i.e {{result}}
I want to show this context in database
when we click on submit in index.html the data will store in database for this i created si class in models.py
Please anyone can help me.
Hey! I think, first, make sure you have a form in your index.html that sends data to your backend. In your Django views, you’ll handle the form submission and save the data to your database.
You should have a form like this:
<form action="{% url 'save_data' %}" method="POST"> {% csrf_token %} <input type="text" name="data" placeholder="Enter data"> <button type="submit">Submit</button> </form>In your models.py, create a model to store the data:
from django.db import models class DataModel(models.Model): data = models.CharField(max_length=255)In your views.py, handle the form submission and save the data.
from django.shortcuts import render, redirect from .models import DataModel def save_data(request): if request.method == "POST": data = request.POST['data'] DataModel.objects.create(data=data) return redirect('result', result=data) return render(request, 'index.html') def result(request, result): return render(request, 'result.html', {'result': result})In your urls.py, set up the URLs for your views.
from django.urls import path from . import views urlpatterns = [ path('', views.save_data, name='save_data'), path('result/<str:result>/', views.result, name='result'), ]Finally, in your result.html, display the result:
<h1>Result: {{ result }}</h1>When you submit the form in index.html, it should hit the save_data view, save the data to the database, and redirect to result.html with the saved data. Hope this helps!