Displaying Django Form Results - python

I have a Django Form (ModelForm) which has a number of fields. When the user presses submit these are then saved to a database. What I am struggling to work out is, how do I then output/render these results in some other HTML page.
Models.py
from django.db import models
# Create your models here.
class Contract(models.Model):
name = models.CharField(max_length=200)
doorNo = models.SlugField(max_length=200)
Address = models.TextField(blank=True)
Forms.py
from django import forms
from contracts.models import Contract
class GenerateContract(forms.ModelForm):
class Meta():
model = Contract
fields = '__all__'
Views.py
from django.shortcuts import render
from contracts.forms import GenerateContract
# Create your views here.
def index(request):
return render(request, 'contracts/index.html')
def contractview(request):
form = GenerateContract()
if request.method == "POST":
form = GenerateContract(request.POST)
if form.is_valid():
form.save(commit=True)
return index(request)
else:
print('ERROR')
return render(request,'contracts/contracts.html',{'form':form})
At the moment, I am returning the 'Index' Home page of the app as a placeholder.

After validation, the form data is found in form.cleaned_data dictionary. So you can pass that back to the template and display it as you see fit.
from django.shortcuts import render
from contracts.forms import GenerateContract
# Create your views here.
def index(request):
return render(request, 'contracts/index.html')
def contractview(request):
form = GenerateContract()
if request.method == "POST":
form = GenerateContract(request.POST)
if form.is_valid():
form.save(commit=True)
return render(request,'contracts/contracts.html',{'form_data': form.cleaned_data})
else:
print('ERROR')
return render(request,'contracts/contracts.html',{'form':form})

If you want to show the form with the saved values, you can render the template with form and fill the instance input . like this:
from django.shortcuts import render
from contracts.forms import GenerateContract
# Create your views here.
def index(request):
return render(request, 'contracts/index.html')
def contractview(request):
form = GenerateContract()
if request.method == "POST":
form = GenerateContract(request.POST)
if form.is_valid():
saved_instance = form.save(commit=True)
return render(request,'contracts/contracts.html',{'form':GenerateContract(instance=saved_instance)})
else:
print('ERROR')
return render(request,'contracts/contracts.html',{'form':form})

Related

Can't get form class object in template view

I want to get the form object from self.Form
This is my form
class ActionLogSearchForm(forms.Form):
key_words = forms.CharField(required=False)
and I set form as form_class, however I can't fetch the form data in view
class ActionLogListView(LoginRequiredMixin, ListSearchView):
template_name = "message_logs/action_log.html"
form_class = ActionLogSearchForm
def get_queryset(self):
res = []
form = self.form ## somehow form is None
print(form.cleaned_data) # error occurs here. 'NoneType' object has no attribute 'cleaned_data'
I think this is the simplest set, but how can I make it work?
Try this:
from django.http import HttpResponseRedirect
from django.shortcuts import render
class ActionLogSearchForm(forms.Form):
key_words = forms.CharField(required=False)
class ActionLogListView(LoginRequiredMixin, ListSearchView, request):
form_class = ActionLogSearchForm
def get_queryset(self, request):
res = []
if request.method == 'POST':
form = self.form(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
return render(request, 'message_logs/action_log.html', {'form': form})

Why Djano forms fields value not rendering in html template for function based update view?

This is my update views:
def EditDoctor(request,slug=None):
if request.method == "POST":
obj = get_object_or_404(Doctor,slug=slug)
form = DoctorUpdateFrom(request.POST,instance=obj)
if form.is_valid():
form.save()
return redirect('hospital:all-doctor')
else:
form = DoctorUpdateFrom()
context = {'doctor_form':form}
return render (request,'hospital/edit-doctor.html', context)
The main problems I am not seeing any existing value in my forms. it's just rendering an empty forms.
You need to pass the instance to the form in case of a GET request as well:
def EditDoctor(request,slug=None):
obj = get_object_or_404(Doctor,slug=slug) # 🖘 fetch the object for both paths
if request.method == "POST":
form = DoctorUpdateFrom(request.POST,instance=obj)
if form.is_valid():
form.save()
return redirect('hospital:all-doctor')
else:
form = DoctorUpdateFrom(instance=obj) # 🖘 pass the instance to edit
context = {'doctor_form':form}
return render (request,'hospital/edit-doctor.html', context)

Redirect to function based detail view after submitting form

I created a model named Student. I created a model form. I want to go to detail view not the list view, after submitting model form.
How do i do that ?
model.py
class Student(models.Model):
student_name = models.CharField(max_length=100)
father_name = models.CharField(max_length=100)
forms.py
class AdmissionForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'
views.py
def admission_form(request):
form = AdmissionForm()
if request.method == 'POST':
form = AdmissionForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('student-list') # i want to redirect to detail view
context = {'form':form}
return render(request, 'student/admission_form.html', context)
In this admission form, i want to redirect to detail view of the student not the list view. How can i do that. In this code, i have redirected to list view.
def student_detail(request, id):
stud = Student.objects.get(id=id)
context = {'stud':stud}
return render(request, 'student/student_detail.html', context)
urls.py
urlpatterns = [
path('admission_form/', views.admission_form, name = 'admission-form'),
path('student/', views.student_list, name = 'student-list'),
path('student/<int:id>/', views.student_detail, name = 'student-detail'),
]
form.save() will return an instance of Student model. You can use it's id in redirect like this:
def admission_form(request):
form = AdmissionForm()
if request.method == 'POST':
form = AdmissionForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save()
return redirect('student-detail', id=instance.pk)

How to create a unique reference for the result each time?

In general, I make a page on the site. The meaning is this: a person comes in, loads an xml file, selects several parameters, and outputs the result. I did not find how to handle the xml file at once. So I upload its file with the parameters to the database, and then redirect us to the page with the result. Everything works fine, but there is a problem. I have not figured out how to create a unique link for the result each time. Now I have one link for the results and it just shows the last one ...
views.py of uploader
def upload_file(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('lessons:index')
else:
form = DocumentForm()
return render(request, 'templates/upload/upload.html', {'form': form})
downloader
views.py of handler
def lessons_view(request):
a = keker()
return render(request, 'templates/lessons/ocenki.html', {'ocenki': a})
keker if handler function
Try code like this (python 3.6):
# models.py
class Document(Model):
...
reference = CharField(max_length=128, db_index=True, null=False)
...
# forms.py
import secrets
...
class DocumentForm(ModelForm):
...
def save(self, commit=True):
self.instance.reference = secrets.token_hex(128)
return super().save(commit)
# views.py
...
def upload_file(request):
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('lessons:index', kwargs=dict(reference=form.instance.reference))
else:
form = DocumentForm()
return render(request, 'templates/upload/upload.html', {'form': form})
...
def lessons_view(request, reference):
a = keker(reference)
return render(request, 'templates/lessons/ocenki.html', {'ocenki': a})
# urls.py
...
url(r'^/(?P<reference>\w+)/$', 'index', name='index'),
...

Page Processor is not working

processors.py file:
from django import forms
from django.http import HttpResponseRedirect
from mezzanine.pages.page_processors import processor_for
from .models import Author
class AuthorForm(forms.Form):
name = forms.CharField()
email = forms.EmailField()
#processor_for(Author)
def author_form(request, page):
form = AuthorForm()
if request.method == "POST":
form = AuthorForm(request.POST)
if form.is_valid():
# Form processing goes here.
redirect = request.path + "?submitted=true"
return HttpResponseRedirect(redirect)
return {"form": form}
here define urls.py file where i define processor like:
url("^xyz/$", "mezzanine.pages.views.page", {"slug": "Author"}, name="Author"),
The form still doesn't display. How do I solve this error?
Mistake: Always define processor name in " " like #processor_for("Author")
**#processor_for("Author")**
def author_form(request, page):
form = AuthorForm()
if request.method == "POST":
form = AuthorForm(request.POST)
if form.is_valid():
# Form processing goes here.
redirect = request.path + "?submitted=true"
return HttpResponseRedirect(redirect)
return {"form": form}

Categories