Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
context Django
#3
(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!
Reply


Messages In This Thread
context Django - by Sowmya - Mar-22-2024, 10:47 AM
RE: context Django - by tahirahmedd - May-20-2024, 05:15 AM
RE: context Django - by JamesWilson - Jul-01-2024, 07:12 AM
RE: context Django - by justinbieber - Jul-10-2024, 04:44 AM
RE: context Django - by tiksteg - Feb-04-2025, 04:08 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  DJANGO Looping Through Context Variable with specific data Taz 0 2,622 Feb-18-2021, 03:52 PM
Last Post: Taz
  Django: How to automatically substitute a variable in the admin page at Django 1.11? m0ntecr1st0 3 4,596 Jun-30-2019, 12:21 AM
Last Post: scidam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020