How to use form.cleaned_data django - django

After form.is_valid(), we get form.cleaned_data. How can i use this cleaned data on the next page.
For example, after the form page is processed we redirect the customer to next page, where I want to use the cleaned_data's info like name, contact, address..etc fields to be shown in next page.
def ind(request):
if request.method == 'POST':
form = form_name(request.POST)
if form.is_valid():
print(form.cleaned_data)
return render(request, 'app_one/abc.html', {'data': form.cleaned_data})
# form.save(commit=True)
# return render(request,'app_one/index.html')
else:
form=form_name()
return render(request,'app_one/index.html',{'form':form)

We will have a validated data after calling the form.is_valid() method. Once we have a validated data then we can use as we like.
For your case
customer details which are filled on the first page need show those details on the second page as receipt.
You can create a model named Reciept and save the details in the model for future reference. If you want these details in the other page views then simply pass the model object in context to render the details.
You can use the cleaned data like below
def ind(request):
if request.method == 'POST':
form = form_name(request.POST)
if form.is_valid():
context = {}.update(form.cleaned_data)
return render(request, 'app_one/abc.html', context)
# form.save(commit=True)
# return render(request,'app_one/index.html')
else:
form=form_name()
return render(request,'app_one/index.html',{'form':form)
Example Form:
class MyForm(forms.Form):
reciept_num = forms.CharField()
consider above form as an example
You can access the reciept_num data in template using the name reciept_num.

You can assign the cleaned_data to variables as usual for forms
e.g. your_data=form.cleaned_data['your_data']
After that, pass those variables to context.
e.g. context = {
'your_data':your_data
}
Lastly return the template.
e.g. return(request,'template.html',context=context)
At the 'template.html', use the variables as {{your_data}}.

Related

Django - Previously page with data entered when form is invalid

Can I make my page return with the information previously entered when the form is invalid?
Views.py
def MyView(request):
[...code...]
if request.method == 'POST':
form = MyForm(request.POST or None)
if form.is_valid()
//do something and redirect to success page
else:
//back to the page with the information filled in by the user (HERE IS MY PROBLEM)
the line form = MyForm(request.POST or None) creates a MyForm object called form with request data assigned to it - its kinda like filled out form. The is_valid() method checks for errors in your form and adds particular errors to your form so this is now a filled out form with errors assigned. If you want to return this form to user you should add it to context so considering its a standard django function based view it should look like this:
def MyView(request):
[...code...]
if request.method == 'POST':
form = MyForm(request.POST or None)
if form.is_valid()
form.save()
return render(request, 'succes_page_template.html')
else:
return render(request, 'current_template.html', context = {'form': form})
if the form is invalid the next thing the user sees is same page where he filled out the form ('current_template.html') but with all the fields filled with data he/she already put it also form will have erros assigned to particular fields so you can print them. If you are new to Django I suggest getting into class based views from the start - they do the heavy lifting for you and refactoring + debugging becomes much easier. here is the link cheers!

Is there a method to post form data from one url to another url, and then render the template based on the form data

I am trying to create a simple one item product store, in which customers would go to a product page and choose the quantity they would like to purchase in a form. After completing the form, I would then like for it to redirect to the checkout page and render the quantity they chose. Is there a simple way to do this? At the moment, I am posting the form data to the product page url and then redirecting the user to the checkout page, however I am unsure how to access that data.
def proxy_detail(request, proxy_slug):
if request.method == 'POST':
form = forms.AddProxyAmountForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
number_of_proxies = int(cd['number_of_proxies'])
return redirect('payment:checkout')
else:
add_proxy_form = forms.AddProxyAmountForm()
proxy_product = get_object_or_404(models.ProxyProduct, slug = proxy_slug)
return render(request, 'shop/product/proxy_detail.html', {'proxy_product' : proxy_product, 'add_proxy_form' : add_proxy_form })
Its not an exact answer but I am new here so I can't really comment :p
Anyways, I think in your view, what you can do is, get the data in a variable and pass it as a context to render another page.
def viewname(request):
if request.method == "POST":
#your logic to save here
context = {variableOfInterest : request.POST.valueOfInterest} #considering you are getting it from the form
return render(request, "redirected.html", context)

Create Form and update using same view in django

I am trying to use same view for creating form and updating any object.
My code is as below, I tried in many ways nothing is working, since I am excluding the shof from form and adding it after form.is_valid() it makes lot of confusion. If I update it creates new object. I have two urls one without ql (create new) and one with ql (update existing), I have a class vdview which provides v.shof which needs to applied in the f.shop in form. please help fix this,
#csrf_protect
#login_required
def addmenu(request, qs, ql=None):
v = vdview(request, qs)
ctgobj = get_object_or_404(v.shopcategs, pk=ql) if ql else None # ctgobj = ShopCtg(shop=v.shof)
if ql:
form = ShopCtgForm(instance=ctgobj) # Tried ShopCtgForm(instance=ctgobj, data=request.POST)
else:
form = ShopCtgForm(data= request.POST)
if request.method == 'POST':
if form.is_valid():
f=form.save(commit=False)
f.shop = v.shof
f.save()
#form.save_m2m()
return redirect('vendor-shop', qs) #thing='%s added' %f.name)
else:
pass
#else:
# form = ShopCtgForm()
return render(request,'vendorshop.html', {'shop':v.shof, 'shopcategs':v.shopcategs, 'form': form,
'heading':'Create New Category', 'createcateg': 'createcateg', 'pkaddmenupk':'y' } )
Use try blocks to handle both scenarios. The simplified example below will look for a given model instance pk and if it doesn't find it, will assume you want to create it. try will prevent django from throwing an error if the model instance doesn't exist. Rather, it will just return the empty model form.
It does this first to render the correct form in the template (the first try block) then again in the second try block after request.method == 'POST': to submit new data or update existing data.
Views.py
from .models import Books
from .forms import BookForm
def create_and_update_book_view(request, pk):
books = Books.objects.get(id=pk)
try: # get pre-populated form with model instance data (for update)
form = BookForm(instance=books.id)
except: # If it doesn't exist, show an empty form (for create)
form = BookForm(request.POST or None)
if request.method == 'POST':
try: # Do the same as above
form = BookForm(instance=books.id)
except: # Same as above
form = BookForm(request.POST or None)
if form.is_valid():
form.save()
return render(request, "create_and_update_book_page.html", {'form':form})

Deleting records in Django via forms

I would like to be able to present a form to users with a dropdown list of existing records and a delete action for the selected record. So far all I can find are examples that pass the id of record to the form (such as below) and I can get this to work if I hard code the id in the function, but that's obviously not a solution. What am I missing? Thanks.
def DeleteRecord(request, id):
to_delete = get_object_or_404(MyModel, id=id)
#+some code to check if this object belongs to the logged in user
if request.method == 'POST':
form = DeleteRecordForm(request.POST, instance=to_delete)
if form.is_valid(): # checks CSRF
to_delete.delete()
return HttpResponseRedirect("/")
else:
form = DeleteRecordForm(instance=to_delete)
data = {'form': form}
return render(request, 'deleteprimerpair.html', data)

passing a value to an HttpResponse request

I have a urlpattern that brings a template that allows the fields of a model instance to be viewed:
(r'^display/(?P<id>\w+)/', display_record),
I also have a view function that allows a single instance to be edited. When the object is saved, it simply returns to the same template:
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
After the save, how do I return to the display template, as opposed to refreshing the same view?
the code would look something like the following but I need a way to pass the object "id" to the HttpResponse request:
def edit_record(request, id):
if request.method == 'POST':
a=ProjectRecord.objects.get(pk=id)
form = RecordForm(request.POST, instance=a)
if form.is_valid():
form.save()
return HttpResponseRedirect**('/display/(?P<id>\w+)/')**
else:
a=ProjectRecord.objects.get(pk=id)
form = RecordForm(instance=a)
return render_to_response('productionModulewire.html', {'form': form})
You're overcomplicating things. You already know what the ID is, so why can't you just put it back into the URL?
return HttpResponseRedirect('/display/%s/' % id)
or, better, since it doesn't tie you to a particular hard-coded URL:
return HttpResponseRedirect(reverse('edit_record', kwargs={'id':id}))