passing a value to an HttpResponse request - django

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}))

Related

Suggestions on improving a form view

I'm building an app where the user enters data and then gets redirected to a page that shows results based on their input with some simple equations. However, every time I refresh the results page, a new model instance is saved on the database.
Is there another (more efficient and effective) way of passing the data from this view to another view where I have access to the instance of that model submitted through the form view? What's the Django way of passing form data to a view?
The only limitation is I don't want user authentication so using self.request.user is not an option unless it can be implemented in a way that doesn't require users to sign up and sign in.
I'm still somewhat new to Django so any pointers to obvious solutions that I'm overlooking would be greatly appreciated.
This is the view that processes the model form:
def createcalculation(request):
form = CalcForm()
if request.method == 'POST':
form = CalcForm(request.POST)
if form.is_valid():
item = form.save()
m_data = get_object_or_404(Calculate, id=item.id)
context = {'c_data': form.cleaned_data, 'm_data': m_data}
return render(request, 'calc/res_ca.html', context)
context = {'c_form': form}
return render(request, 'calc/calc.html', context)
It is advisable to always do a redirect after a successful POST. Your code should look something like this:
from django.shortcuts import get_object_or_404, render, redirect
from django.urls import reverse
...
def createcalculation(request):
form = CalcForm()
if request.method == 'POST':
form = CalcForm(request.POST)
if form.is_valid():
item = form.save()
m_data = get_object_or_404(Calculate, id=item.id)
context = {
'c_data': form.cleaned_data,
'm_data': m_data
}
return redirect(reverse('app_name:view_name', kwargs=context))
context = {'c_form': form}
return render(request, 'calc/calc.html', context)
You can pass the newly created item object in the context as well. Also, you should change app_name and view_name text to match your situation.

Passing multiple arguments in django view

I have tree different users and I want to use one view function and three different forms. So I need to pass two arguments to user_signup view: the request object and the form Class. In urls.py I have the following code
path('signup/admin/', views.user_signup(request, AdminSignupForm), name='admin_signup')
in views.py I defined user_signup function
def user_signup(request, form, template_name='users/signup_staff.html'):
if request.method == 'POST':
form = form(request.POST)
if form.is_valid():
user = form.save() # save function is redefined in AdminSignupForm
else:
form = form()
return render(request, template_name, {'form': form})
How can I pass a request object to user_signup?
Use the third argument to the path function.
path('signup/admin/', views.user_signup, {'form': AdminSignupForm}, name='admin_signup')

How to use form.cleaned_data 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}}.

Delete record without accessing it directly

I am creating a data visualisation site in django and using the rest api for my data. Is there any way of deleting a record without accessing its url directly, as in this case it is impossible.
Something like
def employee_delete(request):
instance = Employee.objects.get(social_security=request.POST)
instance.delete()
return render(request, "dashboard.html")
This only works if you have access to the console as I learned, so I tried to access the data from a form like so
def employee_delete(request):
if request.method == "POST":
form = delete_EmployeeForm(request.POST, request.FILES)
if form.is_valid():
instance = Employee.objects.get(social_security=request.POST)
instance.delete()
return render(request, "dashboard.html")
else:
form = delete_EmployeeForm()
return render(request, "deleteemployee.html",{'form': form})
Would this work if I was able to be more specific about which piece of data I was accessing from the form? I got a typeError trying to use request.Post in that manner. That form contained a single field in 'social_security' from the Employee model.
Thanks
def employee_delete(request):
if request.method == "POST":
form = delete_EmployeeForm(request.POST, request.FILES)
if form.is_valid():
instance = Employee.objects.get(social_security=request.POST['social_security'])
instance.delete()
return render(request, "dashboard.html")
else:
form = delete_EmployeeForm()
return render(request, "deleteemployee.html",{'form': form})
use this in your view

Unknown view function

I have a form that should redirect to another view function called content to predict. I receive an error saying that the form doesn't exist when it does as shown in my code:
def content_to_predict(request):
if request.method == "POST":
form = InputForm(request.POST)
if form.is_valid():
return redirect('content_to_predict')
else:
form = InputForm()
return render(request, 'prediction/content_input.html', {'form': form})
def show_prediction_result(request):
return HttpResponse('hello')
What's the problem?
Figured it out. Instead of using redirect, just make a call to another function itself by:
return show_prediction_result(request)
I can't say one way or another as to why redirect doesn't work. If anyone has any input in regards to that. I'd appreciate it.