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')
Related
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!
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}}.
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
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.
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}))